sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/SDC-*.zip
sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/sdctool.tar
sdc-os-chef/.idea/*
+node/*
# chef
.delivery
protected ResourceReqDetails resourceDetailsVFC_02;
protected ResourceReqDetails resourceDetailsVF_01;
protected ResourceReqDetails resourceDetailsVF_02;
+ protected ResourceReqDetails resourceDetailsPNF_01;
protected ResourceReqDetails resourceDetailsCP_01;
protected ResourceReqDetails resourceDetailsCP_02;
protected ResourceReqDetails resourceDetailsVL_01;
resourceDetailsVFC_02 = ElementFactory.getDefaultResourceByType("ciVFC200", NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString());
resourceDetailsVF_01 = ElementFactory.getDefaultResourceByType("ciVF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
resourceDetailsVF_02 = ElementFactory.getDefaultResourceByType("ciVF200", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsPNF_01 = ElementFactory.getDefaultResourceByType("ciPNF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.PNF.toString());
resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("ciCP100", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
resourceDetailsCP_02 = ElementFactory.getDefaultResourceByType("ciCP200", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("ciVL100", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
Function<? super Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
- setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
+ setupContainerExpectedReqCap(uniqueId, name, originComponentId, resourceRequirements, resourceCapabilities);
if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
- setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
+ setupConstInstExpectedReqCap(uniqueId, name, originComponentId, reqCopy, capCopy);
}
// adding entry for expected componentInstance
expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
}
- private void setupContainerExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ private void setupContainerExpectedReqCap(String uniqueId, String name, String componentId, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
List<RequirementDefinition> reqListToAdd = resReq.getValue();
for (RequirementDefinition requirementDefinition : reqListToAdd) {
requirementDefinition.setOwnerId(uniqueId);
requirementDefinition.setOwnerName(name);
+ requirementDefinition.addToPath(uniqueId);
+ requirementDefinition.setSource(componentId);
+ requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
}
List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
if (expectedReqList == null) {
for (CapabilityDefinition capDefinition : capListToAdd) {
capDefinition.setOwnerId(uniqueId);
capDefinition.setOwnerName(name);
+ capDefinition.addToPath(uniqueId);
+ capDefinition.setSource(componentId);
+ capDefinition.setLeftOccurrences(capDefinition.getMaxOccurrences());
}
List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
if (expectedCapList == null) {
}
}
- private void setupConstInstExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ private void setupConstInstExpectedReqCap(String uniqueId, String name, String componentId, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
List<RequirementDefinition> reqListToAdd = resReq.getValue();
for (RequirementDefinition requirementDefinition : reqListToAdd) {
requirementDefinition.setOwnerId(uniqueId);
requirementDefinition.setOwnerName(name);
+ requirementDefinition.addToPath(uniqueId);
+ requirementDefinition.setSource(componentId);
+ requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
}
}
for (CapabilityDefinition capDefinition : capListToAdd) {
capDefinition.setOwnerId(uniqueId);
capDefinition.setOwnerName(name);
+ capDefinition.addToPath(uniqueId);
+ capDefinition.setSource(componentId);
}
}
}
return component;
}
+ protected Component getComponentAndValidateRIsOnly(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
+
+ RestResponse getResponse = null;
+ Component component = null;
+ if (componentDetails instanceof ResourceReqDetails) {
+ getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (componentDetails instanceof ServiceReqDetails) {
+ getResponse = ServiceRestUtils.getService((ServiceReqDetails) componentDetails, sdncAdminDetails);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else if (componentDetails instanceof ProductReqDetails) {
+ getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
+ } else {
+ Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
+ }
+ ResourceRestUtils.checkSuccess(getResponse);
+ int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size() : 0;
+ int numberOfActualRelations = component.getComponentInstancesRelations() != null ? component.getComponentInstancesRelations().size() : 0;
+ assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
+ assertEquals("Check number of RI relations meet the expected number", numberOfRelations, numberOfActualRelations);
+
+ return component;
+ }
+
protected void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws IOException, Exception {
updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations);
ResourceRestUtils.checkCreateResponse(createVfResponse);
}
+ protected void createPNF(ResourceReqDetails resourceDetails) throws Exception {
+ createVF(resourceDetails, sdncDesignerDetails);
+ }
+
protected void createService(ServiceReqDetails serviceDetails) throws Exception {
createService(serviceDetails, sdncDesignerDetails);
}
final String GET_SERVICE_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/latestversion/notabstract";
+ final String GET_RESOURCE_METADATA_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/latestversion/notabstract/metadata";
+
// Get resource artifact list:
// http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts
final String GET_RESOURCE_ARTIFACTS_LIST = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts";
// ***********************************External API's
// (AssetData)****************************************
- final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts/%s";
- final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/artifacts/%s";
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
- final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts/%s";
- final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
- final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts";
- final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/artifacts";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts";
- final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/resources/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/resources/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
- final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/asdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/sdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
- final String GET_ASSET_LIST = "http://%s:%s/asdc/v1/catalog/%s";
- final String GET_FILTERED_ASSET_LIST = "http://%s:%s/asdc/v1/catalog/%s?%s";
- final String GET_TOSCA_MODEL = "http://%s:%s/asdc/v1/catalog/%s/%s/toscaModel";
- // https://{serverRoot}/asdc/v1/catalog/{assetType}/{uuid}/metadata, where
+ final String GET_ASSET_LIST = "http://%s:%s/sdc/v1/catalog/%s";
+ final String GET_FILTERED_ASSET_LIST = "http://%s:%s/sdc/v1/catalog/%s?%s";
+ final String GET_TOSCA_MODEL = "http://%s:%s/sdc/v1/catalog/%s/%s/toscaModel";
+ // https://{serverRoot}/sdc/v1/catalog/{assetType}/{uuid}/metadata, where
// assetType in {resources, services}
- final String GET_ASSET_METADATA = "http://%s:%s/asdc/v1/catalog/%s/%s/metadata";
+ final String GET_ASSET_METADATA = "http://%s:%s/sdc/v1/catalog/%s/%s/metadata";
final String POST_AUTHORIZATION = "http://%s:%s/sdc2/rest/v1/consumers";
- final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = "http://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
- final String POST_EXTERNAL_API_CREATE_RESOURCE = "http://%s:%s/asdc/v1/catalog/resources";
+ final String POST_EXTERNAL_API_CREATE_RESOURCE = "http://%s:%s/sdc/v1/catalog/resources";
- final String CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/asdc/v1/catalog/resources/%s/lifecycleState/%s";
- final String CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/asdc/v1/catalog/services/%s/lifecycleState/%s";
+ final String CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/sdc/v1/catalog/resources/%s/lifecycleState/%s";
+ final String CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/sdc/v1/catalog/services/%s/lifecycleState/%s";
// *****************************************************************************************************
final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s";
// "/sdc2/v1/services/<serviceName>/<0.1>/resources/{resourceName}/{resourceVersion}/artifacts/<opeartion_name>_aaa.hh"
final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
- final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL = "/asdc/v1/catalog/services/%s/%s/artifacts/%s";
- final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL = "/asdc/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
+ final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL = "/sdc/v1/catalog/services/%s/%s/artifacts/%s";
+ final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL = "/sdc/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
final String DOWNLOAD_SERVICE_ARTIFACT_FULL_URL = "http://%s:%s%s";
final String DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL = "http://%s:%s%s";
// **********************************************************************************
List<String> derivedFrom;
String vendorName;
String vendorRelease;
+ String resourceVendorModelNumber;
// Unsettable/unupdatable fields
this.derivedFrom = resource.getDerivedFrom();
this.vendorName = resource.getVendorName();
this.vendorRelease = resource.getVendorRelease();
+ this.resourceVendorModelNumber = resource.getResourceVendorModelNumber();
this.contactId = resource.getContactId();
this.icon = resource.getIcon();
this.toscaResourceName = resource.getToscaResourceName();
import org.openecomp.sdc.be.model.category.CategoryDefinition;
public class ServiceReqDetails extends ComponentReqDetails {
+
+ String serviceType;
+ String serviceRole;
public ServiceReqDetails(String serviceName, String category, ArrayList<String> tags, String description,
String contactId, String icon) {
this.description = description;
this.contactId = contactId;
this.icon = icon;
+ this.serviceType = "";
+ this.serviceRole = "";
projectCode = "12345";
CategoryDefinition categoryDefinition = new CategoryDefinition();
categoryDefinition.setName(category);
this.uniqueId = service.getUniqueId();
this.UUID = service.getUUID();
this.version = service.getVersion();
+ this.serviceType = service.getServiceType();
+ this.serviceRole = service.getServiceRole();
}
expectedResourceAuditJavaObject.setDesc("OK");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- String resource_url = String.format("/asdc/v1/catalog/resources/%s/artifacts/%s", resourceUUID, artifactUUID);
+ String resource_url = String.format("/sdc/v1/catalog/resources/%s/artifacts/%s", resourceUUID, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
expectedResourceAuditJavaObject.setDesc("OK");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceUUID, artifactUUID);
+ String resource_url = String.format("/sdc/v1/catalog/services/%s/artifacts/%s", resourceUUID, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
expectedResourceAuditJavaObject.setDesc("OK");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceUUID, componentNormalizedName, artifactUUID);
+ String resource_url = String.format("/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceUUID, componentNormalizedName, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
package org.openecomp.sdc.ci.tests.execute.category;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
-import org.apache.log4j.lf5.util.ResourceUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Rule;
import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.*;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.testng.AssertJUnit;
-import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
protected Config config = Config.instance();
protected String contentTypeHeaderData = "application/json";
protected String acceptHeaderDate = "application/json";
+ protected boolean isInitialized = false;
@Rule
public static TestName name = new TestName();
@BeforeMethod
public void setUp() throws Exception {
+ if (isInitialized)
+ return;
user = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
resourceDetails1 = buildResourceDetails(user, "TestResource1");
+ resourceDetails1.setResourceType(ResourceTypeEnum.VFCMT.name());
resourceDetails2 = buildResourceDetails(user, "TestResource2");
svcDetails1 = buildServiceDetails("TestService1");
+ // VFCMT
res1 = createResource(user, resourceDetails1);
AssertJUnit.assertEquals("create resorce failed", 201, res1.getErrorCode().intValue());
resourceDetails1.setUniqueId(ResponseParser.getUniqueIdFromResponse(res1));
+
resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res1));
+ // VFC
res2 = createResource(user, resourceDetails2);
AssertJUnit.assertEquals("create resorce failed", 201, res2.getErrorCode().intValue());
resourceDetails2.setUniqueId(ResponseParser.getUniqueIdFromResponse(res2));
resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res2));
+ // SERVICE
svc1 = createService(user, svcDetails1);
AssertJUnit.assertEquals("create resorce failed", 201, svc1.getErrorCode().intValue());
svcDetails1.setUniqueId(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getUniqueId());
svcDetails1.setVersion(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getVersion());
+ isInitialized = true;
}
- @AfterMethod
+ @AfterClass
public void tearDown() throws Exception {
deleteResource(resourceDetails1.getUniqueId(), user.getUserId());
deleteResource(resourceDetails2.getUniqueId(), user.getUserId());
}
+ @Test
+ public void getCatalogDataNoVFCMT() throws Exception {
+
+ List<String> excludeTyps = Arrays.asList(OriginTypeEnum.VFCMT.name());
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received except of resource1 which is VFCMT
+ AssertJUnit.assertFalse("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
+ @Test
+ public void getCatalogDataNoVFCandVFCMT() throws Exception {
+
+ List<String> excludeTyps = Arrays.asList(OriginTypeEnum.VFCMT.name(), OriginTypeEnum.VFC.name());
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received except of VFCMT & VFC
+ AssertJUnit.assertFalse("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertFalse("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
+ @Test
+ public void getCatalogDataNoServiceAndVFC() throws Exception {
+
+ List<String> excludeTyps = Arrays.asList(OriginTypeEnum.SERVICE.name(), OriginTypeEnum.VFC.name());
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received except of VFC & SERVICE
+ AssertJUnit.assertTrue("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertFalse("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertFalse("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception {
RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId);
protected RestResponse createService(User user, ServiceReqDetails svcDetails) throws Exception {
+ deleteService(svcDetails1.getUniqueId(), user);
Config config = Utils.getConfig();
Map<String, String> headersMap = getHeadersMap(user);
Map<String, String> headersMap = new HashMap<String, String>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+ headersMap.put("USER_ID", user.getUserId());
return headersMap;
}
}
public RestResponse deleteService(String serviceId, User user) throws Exception {
- HttpRequest httpRequest = new HttpRequest();
- String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(),
- serviceId);
-
- Map<String, String> headersMap = getHeadersMap(user);
- RestResponse res = httpRequest.httpSendDelete(url, headersMap);
- // System.out.println("Delete service was finished with response:
- // "+res.getErrorCode());
- return res;
+ RestResponse deleteServiceResponse = ResourceRestUtils.deleteResource(serviceId, user.getUserId());
+ return deleteServiceResponse;
}
public class NewObject {
AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
return restResponse;
//
// if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getComponentInstances().get(0).getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
//
// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
// } else {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
// }
//
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
return restResponse;
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
return restResponse;
//
// if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getComponentInstances().get(0).getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
//
// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
// } else {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
// }
//
--- /dev/null
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CommonRestUtils;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import org.openecomp.sdc.common.api.HealthCheckWrapper;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class HealthCheckAPI extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ private static final int STATUS_CODE_GET_SUCCESS = 200;
+
+ public HealthCheckAPI() {
+ super(name, HealthCheckAPI.class.getName());
+ }
+
+ @Test
+ public void checkAmdocsHealthCheckAPI() throws Exception {
+ RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
+ BaseRestUtils.checkSuccess(healthCheckInfoResponse);
+
+ Gson gson = new Gson();
+ HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
+ assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
+ HealthCheckInfo amdocsHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent() == HealthCheckInfo.HealthCheckComponent.ON_BOARDING).findFirst().orElse(null);
+ assertNotNull("Amdocs health check not exists in Health Check info", amdocsHC);
+ assertEquals("Amdocs health check is down", HealthCheckInfo.HealthCheckStatus.UP, amdocsHC.getHealthCheckStatus());
+ assertNotNull("Amdocs additionalInfo not exists in health check", amdocsHC.getComponentsInfo());
+ Map<HealthCheckComponent, HealthCheckStatus> amdocsHCComponents = amdocsHC.getComponentsInfo().stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
+ assertNotNull(amdocsHCComponents);
+ assertTrue("Amdocs health check ZU component is down or not exists", amdocsHCComponents.get(HealthCheckComponent.ZU) != null && amdocsHCComponents.get(HealthCheckComponent.ZU).equals(HealthCheckStatus.UP));
+ assertTrue("Amdocs health check BE component is down or not exists", amdocsHCComponents.get(HealthCheckComponent.BE) != null && amdocsHCComponents.get(HealthCheckComponent.BE).equals(HealthCheckStatus.UP));
+ assertTrue("Amdocs health check CAS component is down or not exists", amdocsHCComponents.get(HealthCheckComponent.CAS) != null && amdocsHCComponents.get(HealthCheckComponent.CAS).equals(HealthCheckStatus.UP));
+ }
+
+ @Test
+ public void checkCassandraHealthCheck() throws Exception {
+ RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
+ BaseRestUtils.checkSuccess(healthCheckInfoResponse);
+
+ Gson gson = new Gson();
+ HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
+ assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
+ HealthCheckInfo cassandraHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent() == HealthCheckInfo.HealthCheckComponent.CASSANDRA).findFirst().orElse(null);
+ assertNotNull("Cassandra health check not exists in Health Check info", cassandraHC);
+ assertEquals("Cassandra health check is down", HealthCheckInfo.HealthCheckStatus.UP, cassandraHC.getHealthCheckStatus());
+ }
+
+}
\ No newline at end of file
ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
ValidationUtils.convertToSystemName(resourceDetails.getName()), resourceDetails.getVersion(),
ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
- expectedDownloadResourceUrl = expectedDownloadResourceUrl.substring("/asdc/".length(),
+ expectedDownloadResourceUrl = expectedDownloadResourceUrl.substring("/sdc/".length(),
expectedDownloadResourceUrl.length());
expectedDownloadServiceUrl = String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
- expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/asdc/".length(),
+ expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/sdc/".length(),
expectedDownloadServiceUrl.length());
sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;
public void createResourceCsarBasicTest() throws Exception {
Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
resourceVF = (Resource) AtomicOperationUtils
.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
csarBasicValidation(resourceVF, downloadCSAR);
+
+ validateVFCsar(resourceVF, downloadCSAR, 1, 0, 0, 0, 0, 0, 0);
+
+
}
@Test(enabled = true)
Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceVF1, UserRoleEnum.DESIGNER, true, true);
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_ARTIFACT, resourceVF1, UserRoleEnum.DESIGNER, true, true);
public void createResourceCsarInclInformationalArtTest() throws Exception {
Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
-
+
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceVF1, UserRoleEnum.DESIGNER, false, true);
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceVF1, UserRoleEnum.DESIGNER, false, true);
validateVFCsar(resourceVF1, downloadCSAR, 1, 0, 0, 0, 1, 1, 0);
}
+ @Test(enabled = true)
+ public void createServiceCsarNotMandatoryMetadataFieldsTest() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ service.setServiceType("serviceTypeTest");
+ service.setServiceRole("serviceRoleTest");
+ ServiceRestUtils.updateService(new ServiceReqDetails(service), sdncModifierDetails);
+
+ Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
+ resourceVF1 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ resourceVF2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF1, service, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true);
+
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
+
+ csarBasicValidation(service, downloadCSAR);
+
+ validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 3, 0, 0);
+ }
+
+ @Test(enabled = true)
+ public void createResourceCsarNotMandatoryMetadataFieldsTest() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ resourceVF.setResourceVendorModelNumber("modelNumberTest");
+ ResourceRestUtils.updateResourceMetadata(new ResourceReqDetails(resourceVF), sdncModifierDetails, resourceVF.getUniqueId());
+
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
+
+ csarBasicValidation(resourceVF, downloadCSAR);
+
+ validateVFCsar(resourceVF, downloadCSAR, 1, 0, 0, 0, 0, 0, 0);
+
+
+ }
+
+
private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) {
try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR);
ZipInputStream zip = new ZipInputStream(ins);) {
while ((len = zip.read(buffer)) > 0) {
sb.append(new String(buffer, 0, len));
}
- assertTrue(nextEntry.getName().equals("csar.meta"));
-
+ assertTrue(nextEntry.getName().equals("csar.meta"));
readNextEntry(sb, len, buffer, zip);
nextEntry = zip.getNextEntry();
assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+ readNextEntry(sb, len, buffer, zip);
+
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
String UUID = (String) metadata.get("UUID");
assertNotNull(UUID);
- assertEquals("Validate component invariantUUID", component.getUUID(), UUID);
+ assertEquals("Validate component UUID", component.getUUID(), UUID);
String type = (String) metadata.get("type");
assertNotNull(type);
if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
assertEquals("Validate component type", component.getComponentType().getValue(), type);
+ String serviceType = (String) metadata.get("serviceType");
+ assertNotNull(serviceType);
+ assertEquals("Validate service type", ((Service )component).getServiceType(), serviceType);
+ String serviceRole = (String) metadata.get("serviceRole");
+ assertNotNull(serviceRole);
+ assertEquals("Validate service role", ((Service )component).getServiceRole(), serviceRole);
} else {
assertEquals("Validate component type", ((Resource) component).getResourceType(),
ResourceTypeEnum.valueOf(type));
+ String resourceVendorModelNumber = (String) metadata.get("resourceVendorModelNumber");
+ assertNotNull(resourceVendorModelNumber);
+ assertEquals("Validate resource vendor model number", ((Resource )component).getResourceVendorModelNumber(), resourceVendorModelNumber);
}
}
assertNotNull(vfModulesInRes);
assertNotNull(groups);
- assertEquals("Validate count of vf module instanses", vfModulesInRes.size(), groups.size());
+ assertEquals("Validate count of vf module instances", vfModulesInRes.size(), groups.size());
vfModulesInRes.forEach(modInRes -> {
validateVfModuleVsInstance(normalizedName, groups, modInRes);
--- /dev/null
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+/**
+ * Created by chaya on 6/15/2017.
+ */
+public class GetLeftPaletteTest extends ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(GetLeftPaletteTest.class.getName());
+ protected User designerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected ResourceReqDetails vlResourceDetails;
+ protected ResourceReqDetails cpResourceDetails;
+ protected ResourceReqDetails vfcResourceDetails;
+ protected ResourceReqDetails vfcmtResourceDetails;
+ protected ResourceReqDetails vfResourceDetails;
+
+
+ public static TestName name = new TestName();
+
+ public GetLeftPaletteTest() {
+ super(name, GetLeftPaletteTest.class.getName());
+ }
+
+ @BeforeClass
+ public void setUp() throws Exception {
+ // create VL
+ vlResourceDetails = createResource(vlResourceDetails, "vlRes", ResourceTypeEnum.VL);
+ checkInResource(vlResourceDetails);
+
+ // create CP
+ cpResourceDetails = createResource(cpResourceDetails, "cpRes", ResourceTypeEnum.CP);
+ checkInResource(cpResourceDetails);
+
+ // create VFC
+ vfcResourceDetails = createResource(vfcResourceDetails, "vfcRes", ResourceTypeEnum.VFC);
+ checkInResource(vfcResourceDetails);
+
+ // create VFCMT
+ vfcmtResourceDetails = createResource(vfcmtResourceDetails, "vfcmtRes", ResourceTypeEnum.VFCMT);
+ checkInResource(vfcmtResourceDetails);
+
+ // create VF
+ vfResourceDetails = createResource(vfResourceDetails, "vfRes", ResourceTypeEnum.VF);
+ checkInResource(vfResourceDetails);
+ }
+
+
+
+ @Test
+ public void testGetLeftPaletteForPNF() throws IOException {
+
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "PNF");
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ String json = getResourceLatestVersionResponse.getResponse();
+ JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
+
+ AssertJUnit.assertTrue("check vlResource is in response",
+ isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check cpResource is in response",
+ isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcResource is not in response",
+ isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfResource is not in response",
+ isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcmtResource is not in response",
+ isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
+
+ }
+
+ @Test
+ public void testGetLeftPaletteForVF() throws IOException {
+
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "VF");
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ String json = getResourceLatestVersionResponse.getResponse();
+ JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
+
+ AssertJUnit.assertTrue("check vlResource is in response",
+ isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check cpResource is in response",
+ isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check vfcResource is not in response",
+ isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfResource is not in response",
+ isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcmtResource is not in response",
+ isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
+
+ }
+
+ @Test
+ public void testGetLeftPaletteForService() throws IOException {
+
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "SERVICE");
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ String json = getResourceLatestVersionResponse.getResponse();
+ JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
+
+ AssertJUnit.assertTrue("check vlResource is in response",
+ isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check cpResource is in response",
+ isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcResource is not in response",
+ isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check vfResource is not in response",
+ isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcmtResource is not in response",
+ isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
+
+ }
+
+ private ResourceReqDetails createResource(ResourceReqDetails resDetails, String name, ResourceTypeEnum resType) throws Exception {
+ resDetails = new ResourceReqDetails(name, "desc",Arrays.asList(name), "Generic", Arrays.asList("tosca.nodes.Root"), "c", "1", "111", "myIcon", resType.name());
+ resDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getCategory(),
+ ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory());
+ RestResponse response = ResourceRestUtils.createResource(resDetails, designerDetails);
+ assertTrue("response code is not 200, returned :" + response.getErrorCode(),
+ response.getErrorCode() == 201);
+ resDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(response));
+ return resDetails;
+ }
+
+ private void checkInResource(ResourceReqDetails resDetails) throws IOException {
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resDetails, designerDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("check in operation failed", 200, checkInResponse.getErrorCode().intValue());
+
+ }
+
+ protected boolean isComponentInArray(String id, JSONArray component) {
+ for (int i = 0; i < component.size(); i++) {
+ JSONObject jobject = (JSONObject) component.get(i);
+ if (jobject.get("uniqueId").toString().equals(id.toLowerCase())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @AfterClass
+ public void tearDown() throws IOException {
+ ResourceRestUtils.deleteResource(vlResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(cpResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(vfcResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(vfcmtResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(vfResourceDetails.getUniqueId(), designerDetails.getUserId());
+ }
+}
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-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.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
createAtomicResource(resourceDetailsVFC_01);
createAtomicResource(resourceDetailsVFC_02);
createAtomicResource(resourceDetailsCP_01);
+ LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
createAtomicResource(resourceDetailsVL_01);
createAtomicResource(resourceDetailsVL_02);
createVF(resourceDetailsVF_01);
createVF(resourceDetailsVF_02);
+ createPNF(resourceDetailsPNF_01);
createService(serviceDetails_01);
certifyResource(resourceDetailsVFC_01);
certifyResource(resourceDetailsVFC_02);
return createVFInstance(containerDetails, compInstOriginDetails, modifier);
}
+ private RestResponse createCheckedinPNFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createCheckedinVFInstance(containerDetails, compInstOriginDetails, modifier);
+ }
+
private RestResponse createCheckedinAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN);
return createAtomicInstanceForService(containerDetails, compInstOriginDetails, modifier);
getComponentAndValidateRIs(serviceDetails_01, 2, 0);
}
+ @Test
+ public void createPNFInstanceSuccessfullyTest() throws Exception {
+ RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createPNFInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 1, 0);
+// createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+// ResourceRestUtils.checkCreateResponse(createVFInstResp);
+// getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
@Test
public void createVFAndAtomicInstanceTest() throws Exception {
RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
getComponentAndValidateRIs(serviceDetails_01, 4, 0);
}
+ @Test
+ public void createPNFAndAtomicInstanceTest() throws Exception {
+ RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createPNFInstResp);
+ RestResponse createVLInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVLInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+
+ }
+
+ private String createCpInstance() throws Exception {
+ // Create CP instance
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsPNF_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsPNF_01, 1, 0);
+ return ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+ }
+
+ @Test
+ public void createPNFAndAtomicInstanceAssociatedTest() throws Exception {
+ reqOwnerId = createCpInstance();
+ RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createPNFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createPNFInstResp);
+ RestResponse createVLInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVLInstResp);
+ capOwnerId = ResponseParser.getUniqueIdFromResponse(createVLInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVLInstResp);
+
+ String capType = "tosca.capabilities.network.Linkable";
+ String reqName = "link";
+
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, capList, reqList);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ capReqDef = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), CapReqDef.class);
+ List<RequirementDefinition> list = capReqDef.getRequirements().get(capType);
+// AssertJUnit.assertEquals("Check requirement", null, list);
+ getComponentAndValidateRIsOnly(serviceDetails_01, 2, 1);
+ }
+
@Test
public void deleteAtomicInstanceTest() throws Exception {
RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
//
public class DistributionUtils {
- final static String serviceDistributionSuffix = "/asdc/v1/catalog/services/";
+ final static String serviceDistributionSuffix = "/sdc/v1/catalog/services/";
public static ServiceDistributionStatus getLatestServiceDistributionObject(Service service) throws IOException, ParseException {
ServiceDistributionStatus serviceDistributionStatus = null;
}
private static String buildServiceDeploymentUrl(Service service, String artifactName, String artifactUUID) {
-// format "/asdc/v1/catalog/services/" + service.getSystemName() + "/" + service.getVersion() + "/artifacts/AAI-" + service.getName() + "-service-1.xml"
+// format "/sdc/v1/catalog/services/" + service.getSystemName() + "/" + service.getVersion() + "/artifacts/AAI-" + service.getName() + "-service-1.xml"
return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/artifacts/" + artifactName;
}
public static String buildResourceInstanceDeploymentUrl(Service service, String artifactName, String artifactUUID){
-// /asdc/v1/catalog/services/Servicefordistribution/1.0 /resourceInstances/nestedfrommarina2 /artifacts/FEAdd_On_Module_vProbeLauncher.yaml
+// /sdc/v1/catalog/services/Servicefordistribution/1.0 /resourceInstances/nestedfrommarina2 /artifacts/FEAdd_On_Module_vProbeLauncher.yaml
String resourceInstanceNormalizedName = getResourceInstanceNormalizeName(service, artifactName, artifactUUID );
return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/resourceInstances/" + resourceInstanceNormalizedName +"/artifacts/" + artifactName;
}
ExpectedExternalAudit expectedExternalAudit = new ExpectedExternalAudit();
expectedExternalAudit.setACTION(action.getName());
expectedExternalAudit.setCONSUMER_ID("ci");
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query));
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query));
expectedExternalAudit.setSTATUS("200");
expectedExternalAudit.setDESC("OK");
return expectedExternalAudit;
expectedResourceAuditJavaObject.setResourceName(resourceName);
expectedResourceAuditJavaObject.setResourceType("Resource");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- expectedResourceAuditJavaObject.setRESOURCE_URL("/asdc/v1/catalog/resources");
+ expectedResourceAuditJavaObject.setRESOURCE_URL("/sdc/v1/catalog/resources");
expectedResourceAuditJavaObject.setMODIFIER("");
expectedResourceAuditJavaObject.setPrevVersion("");
expectedResourceAuditJavaObject.setCurrVersion("0.1");
public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, String resourceInstanceName) {
ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditSuccess(assetType, action, artifactDefinition, componentUUID);
- expectedExternalArtifactAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
+ expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
return expectedExternalArtifactAudit;
}
String resourceInstanceName) {
ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditFailure(assetType, action, artifactDefinition, componentUUID, errorInfo, variables);
- expectedExternalArtifactAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
+ expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
return expectedExternalArtifactAudit;
}
static final String contentTypeHeaderData = "application/json";
static final String acceptHeaderDate = "application/json";
static final String basicAuthentication = "Basic Y2k6MTIzNDU2";
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
- static final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s";
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
- static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
+ static final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
+ static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
public static HttpResponse getComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException {
Config config = Utils.getConfig();
// assertNotNull("Expected artifact asset resourceInvariantUUID
// is null",
// resourceInstanceAssetStructure.getResourceInvariantUUID());
- // String expectedArtifactUrl = "/asdc/v1/catalog/" +
+ // String expectedArtifactUrl = "/sdc/v1/catalog/" +
// assetType.getValue() + "/" + componentUuid + "/artifacts/" +
// componentDeploymentArtifactValue.getArtifactUUID();
String expectedArtifactUrl = "";
package org.openecomp.sdc.ci.tests.utils.rest;
import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
return sendGet(url, userId);
}
+ public static RestResponse getCatalog(String userId, List<String> excludeList) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
+ StringBuilder sb = new StringBuilder();
+ sb.append(url).append("?");
+ Optional.ofNullable(excludeList).orElse(Collections.emptyList()).forEach(type -> sb.append("excludeTypes="+type+"&"));
+ return sendGet(sb.toString(), userId);
+ }
+
public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException {
Config config = Utils.getConfig();
--- /dev/null
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+
+public class CommonRestUtils extends BaseRestUtils {
+
+ private static Logger logger = LoggerFactory.getLogger(CommonRestUtils.class.getName());
+
+ public static RestResponse getHealthCheck() throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_HEALTH_CHECK_VIA_PROXY, config.getCatalogFeHost(), config.getCatalogFePort());
+
+ return sendGet(url, null);
+
+ }
+}
return sendGet(url, sdncModifierDetails.getUserId());
}
+ public static RestResponse getResourceLatestVersionListMetadata(User sdncModifierDetails, String internalComponentType) throws IOException {
+
+ Config config = Utils.getConfig();
+ StringBuilder sb = new StringBuilder();
+ String url = String.format(Urls.GET_RESOURCE_METADATA_lATEST_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+ sb.append(url);
+ if (internalComponentType != null && !internalComponentType.isEmpty()) {
+ sb.append("?internalComponentType="+internalComponentType);
+ }
+ return sendGet(sb.toString(), sdncModifierDetails.getUserId());
+
+ }
+
public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion)
throws IOException {
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>1.4</version>
+ </dependency>
+
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <version>${testng.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
<!-- testing end -->
</dependencies>
Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> reqInst = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), rel.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST,
NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
if (reqInst.isRight()) {
- log.debug("updateRelations : failed to fetch capabilty component instance for relation {}, error {}", rel.getUniqueId(), reqInst.right().value());
+ log.debug("updateRelations : failed to fetch capability component instance for relation {}, error {}", rel.getUniqueId(), reqInst.right().value());
return false;
}
ComponentInstanceData requirementInstanceData = reqInst.left().value().getLeft();
case CP:
originType = OriginTypeEnum.CP;
break;
+ case CVFC:
+ originType = OriginTypeEnum.CVFC;
+ break;
default:
log.debug("updateComponentInstanceType failed, no supported resource type {} for origin resource with id {}", resourceType, originId);
return false;
if (runMode.equals("fix") || runMode.equals("fix_only_services")) {
log.info("Mode {}. Start fix", runMode);
if (fix(vfLst, serviceList) == false) {
- log.info("Mode {}. Fix finished withh failure", runMode);
+ log.info("Mode {}. Fix finished with failure", runMode);
return false;
}
- log.info("Mode {}. Fix finished withh success", runMode);
+ log.info("Mode {}. Fix finished with success", runMode);
}
return true;
return new NodeTemplateMissingDataResolver<>();
}
+ @Bean(name = "migration1707MissingInfoFix")
+ public Migration1707MissingInfoFix migration1707MissingInfoFix() {
+ return new Migration1707MissingInfoFix();
+ }
+
}
--- /dev/null
+package org.openecomp.sdc.asdctool.impl.migration.v1707;
+
+import fj.data.Either;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.NodeTemplateMissingDataResolver;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+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.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.*;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+@org.springframework.stereotype.Component("migration1707MissingInfoFix")
+public class Migration1707MissingInfoFix {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Migration1707MissingInfoFix.class);
+
+ @Resource(name = "service-operation")
+ private IServiceOperation serviceOperation;
+
+ @Resource(name = "node-template-missing-data-resolver")
+ private NodeTemplateMissingDataResolver nodeTemplateMissingDataResolver;
+
+ @Resource(name = "tosca-operation-facade")
+ private ToscaOperationFacade toscaOperations;
+
+ @Resource(name = "titan-dao")
+ private TitanDao titanDao;
+
+
+ public boolean migrate(){
+ boolean res = updateVFs();
+ if(res)
+ res = updateServices();
+ return res;
+ }
+
+ private ComponentParametersView getFilter() {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreArtifacts(false);
+ filter.setIgnoreGroups(false);
+ filter.setIgnoreComponentInstancesInputs(false);
+ return filter;
+ }
+
+ // if new service has VF instances with no groups - try to fetch them from old graph
+ private boolean oldServiceModelRequired(Component newService) {
+ Predicate<ComponentInstance> vfInstanceWithNoGroups = p -> OriginTypeEnum.VF == p.getOriginType() && (null == p.getGroupInstances() || p.getGroupInstances().isEmpty());
+ return null != newService.getComponentInstances() && newService.getComponentInstances().stream()
+ .anyMatch(vfInstanceWithNoGroups);
+ }
+
+
+
+ private List<GraphVertex> fetchVertices(Map<GraphPropertyEnum, Object> hasProps){
+ Either<List<GraphVertex>, TitanOperationStatus> componentsByCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, JsonParseFlagEnum.ParseAll);
+ if (componentsByCriteria.isRight()) {
+ LOGGER.debug("couldn't fetch assets from sdctitan");
+ return null;
+ }
+ return componentsByCriteria.left().value();
+ }
+
+ private boolean updateVFs() {
+
+ boolean res = true;
+ Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
+
+ List<GraphVertex> resources = fetchVertices(hasProps);
+ if(null == resources)
+ return false;
+ ComponentParametersView filter = getFilter();
+ Map<String, ToscaElement> origCompMap = new HashMap<>();
+
+ for (GraphVertex gv : resources) {
+ boolean fixed = true;
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperations.getToscaElement(gv.getUniqueId(), filter);
+ if (toscaElement.isRight()) {
+ LOGGER.debug("Failed to fetch resource {} {}", gv.getUniqueId(), toscaElement.right().value());
+ return false;
+ }
+ Component resource = toscaElement.left().value();
+ Map<String, Boolean> updateMap = new HashMap<>();
+ nodeTemplateMissingDataResolver.updateVFComposition(resource, origCompMap, updateMap);
+ if(updateMap.get(JsonConstantKeysEnum.COMPOSITION.name())){
+ LOGGER.info("applying instance tosca name fix on VF {}", gv.getUniqueId());
+ fixed = toscaOperations.updateComponentInstanceMetadataOfTopologyTemplate(resource).isLeft();
+ }
+ if(updateMap.get(EdgeLabelEnum.GROUPS.name())) {
+ List<GroupDataDefinition> groups = new ArrayList<>(resource.getGroups());
+ LOGGER.info("applying groups vertex fix on VF {}", gv.getUniqueId());
+ fixed = fixed && toscaOperations.updateGroupsOnComponent(resource, ComponentTypeEnum.RESOURCE, groups).isLeft();
+ }
+
+ res = res && fixed;
+ titanDao.commit();
+ }
+ return res;
+ }
+
+ private Map<String, MapPropertiesDataDefinition> buildInstancesInputsMap(Component component){
+ Map<String, MapPropertiesDataDefinition> instanceInputsMap = new HashMap<>();
+ for (Map.Entry<String, List<ComponentInstanceInput>> entry : component.getComponentInstancesInputs().entrySet()) {
+ MapPropertiesDataDefinition inputsMap = new MapPropertiesDataDefinition();
+ inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+ instanceInputsMap.put(entry.getKey(), inputsMap);
+ }
+ return instanceInputsMap;
+ }
+
+
+
+ private Map<String, MapGroupsDataDefinition> buildGroupInstanceMap(Component component) {
+ Map<String, MapGroupsDataDefinition> instGroupsMap = new HashMap<>();
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ if (instance.getGroupInstances() != null) {
+ MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition();
+ groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(e -> new GroupInstanceDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+ instGroupsMap.put(instance.getUniqueId(), groupsMap);
+ }
+ }
+ return instGroupsMap;
+ }
+
+ private <T extends ToscaDataDefinition> boolean updateDataVertex(GraphVertex componentVertex, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel, Map<String, T> dataMap){
+ Either<GraphVertex, TitanOperationStatus> dataVertexEither = titanDao.getChildVertex(componentVertex, edgeLabel, JsonParseFlagEnum.ParseJson);
+ if (dataVertexEither.isRight()) {
+ if(TitanOperationStatus.NOT_FOUND != dataVertexEither.right().value())
+ return false;
+ return (nodeTemplateMissingDataResolver.topologyTemplateOperation.assosiateElementToData(componentVertex, vertexType, edgeLabel, dataMap)).isLeft();
+ }
+ GraphVertex dataVertex = dataVertexEither.left().value();
+ dataVertex.setJson(dataMap);
+ return (titanDao.updateVertex(dataVertex)).isLeft();
+
+ }
+
+
+ private boolean updateServices(){
+
+ boolean res = true;
+ Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+
+ List<GraphVertex> componentsByCriteria = fetchVertices(hasProps);
+ if(null == componentsByCriteria)
+ return false;
+
+ ComponentParametersView filter = getFilter();
+ Map<String, ToscaElement> origCompMap = new HashMap<>();
+
+ Predicate<ComponentInstance> containsGroupInstances = p -> null != p.getGroupInstances() && !p.getGroupInstances().isEmpty();
+
+ for (GraphVertex gv : componentsByCriteria) {
+
+ boolean fixed = true;
+ Either<org.openecomp.sdc.be.model.Service, StorageOperationStatus> toscaElement = toscaOperations.getToscaElement(gv.getUniqueId(), filter);
+ if (toscaElement.isRight()) {
+ LOGGER.debug("Failed to fetch service {} {}", gv.getUniqueId(), toscaElement.right().value());
+ return false;
+ }
+ Component service = toscaElement.left().value();
+ Component oldService = null;
+
+ if(oldServiceModelRequired(service)){
+ Either<Service, StorageOperationStatus> oldServiceEither = serviceOperation.getService(gv.getUniqueId(), filter, false);
+ if (oldServiceEither.isRight()){
+ LOGGER.debug("couldn't fetch service {} from old titan", gv.getUniqueId());
+ }else {
+ oldService = oldServiceEither.left().value();
+ oldService = oldService.getComponentInstances().stream().anyMatch(containsGroupInstances) ? oldService : null;
+ }
+ }
+
+ Map<String, Boolean> updateMap = new HashMap<>();
+ nodeTemplateMissingDataResolver.updateServiceComposition(service, origCompMap, oldService, updateMap);
+ if(updateMap.get(JsonConstantKeysEnum.COMPOSITION.name())) {
+ LOGGER.info("applying instance tosca name fix on service {}", gv.getUniqueId());
+ fixed = (toscaOperations.updateComponentInstanceMetadataOfTopologyTemplate(service)).isLeft();
+ }
+ if(updateMap.get(EdgeLabelEnum.INST_GROUPS.name())) {
+ Map<String, MapGroupsDataDefinition> groupsMap = buildGroupInstanceMap(service);
+ LOGGER.info("applying groups instances vertex fix on service {}", gv.getUniqueId());
+ fixed = fixed && updateDataVertex(gv, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, groupsMap);
+ }
+ if(updateMap.get(EdgeLabelEnum.INST_INPUTS.name())) {
+ Map<String, MapPropertiesDataDefinition> instInputs = buildInstancesInputsMap(service);
+ LOGGER.info("applying instances inputs vertex fix on service {}", gv.getUniqueId());
+ fixed = fixed && updateDataVertex(gv, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs);
+ }
+ res = res && fixed;
+ titanDao.commit();
+ }
+ return res;
+ }
+}
protected void setMissingTemplateInfo(List<T> components) {
Map<String, ToscaElement> origCompMap = new HashMap<>();
for (T component : components) {
- List<ComponentInstance> instances = component.getComponentInstances();
- if(null != instances) {
+ List<ComponentInstance> instances = component.getComponentInstances();
+ if(null != instances) {
for (ComponentInstance instance : instances) {
nodeTemplateMissingDataResolver.resolveNodeTemplateInfo(instance, origCompMap, component);
nodeTemplateMissingDataResolver.fixVFGroupInstances(component, instance);
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
-
-
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import fj.data.Either;
import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-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.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.*;
+import java.util.stream.Collectors;
import java.util.List;
import java.util.Map;
import java.util.Optional;
private ToscaElementLifecycleOperation lifecycleOperation;
@Resource(name = "topology-template-operation")
- private TopologyTemplateOperation topologyTemplateOperation;
+ public TopologyTemplateOperation topologyTemplateOperation;
public void resolveNodeTemplateInfo(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap, T component) {
lifecycleOperation.resolveToscaComponentName(vfInst, origCompMap);
if(OriginTypeEnum.VF == vfInst.getOriginType()) {
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(new HashMap<>());
- collectVFInstanceInputs(componentInstancesInputs, origCompMap, vfInst);
+ collectVFInstanceInputs(component, origCompMap, vfInst);
+ }
+ }
+
+
+
+
+ public void updateServiceComposition(Component component, Map<String, ToscaElement> origCompMap, Component oldModelService, Map<String, Boolean> updateMap){
+
+ boolean composition = false;
+ boolean instInputs = false;
+ boolean instGroups = false;
+ List<ComponentInstance> instances = component.getComponentInstances();
+ if(null != instances) {
+ for (ComponentInstance instance : instances) {
+ composition = composition || lifecycleOperation.resolveToscaComponentName(instance, origCompMap);
+ if(OriginTypeEnum.VF == instance.getOriginType()) {
+ instInputs = instInputs || collectVFInstanceInputs(component, origCompMap, instance);
+ instGroups = instGroups || resolveInstGroupsFromOldTitanGraphAndApplyFix(component, instance, oldModelService);
+ }
+ }
}
+ updateMap.put(JsonConstantKeysEnum.COMPOSITION.name(), composition);
+ updateMap.put(EdgeLabelEnum.INST_INPUTS.name(), instInputs);
+ updateMap.put(EdgeLabelEnum.INST_GROUPS.name(), instGroups);
+ }
+
+
+ public void updateVFComposition(Component component, Map<String, ToscaElement> origCompMap, Map<String, Boolean> updateMap) {
+
+ boolean composition = false;
+ boolean groups = fixVFGroups(component);
+ List<ComponentInstance> instances = component.getComponentInstances();
+ if(null != instances) {
+ for (ComponentInstance instance : instances) {
+ composition = composition || lifecycleOperation.resolveToscaComponentName(instance, origCompMap);
+ }
+ }
+ updateMap.put(JsonConstantKeysEnum.COMPOSITION.name(), composition);
+ updateMap.put(EdgeLabelEnum.GROUPS.name(), groups);
+ }
+
+
+
+ private boolean resolveInstGroupsFromOldTitanGraphAndApplyFix(Component component, ComponentInstance instance, Component oldService){
+
+ boolean res = false;
+ //info already exists, apply fix if needed
+ if(null != instance.getGroupInstances() && !instance.getGroupInstances().isEmpty()) {
+ res = fixVFGroupInstances(component, instance);
+ //get group instances from old model
+ }else if(null != oldService){
+ ComponentInstance origInstance = oldService.getComponentInstances().stream()
+ .filter(p -> instance.getUniqueId().equals(p.getUniqueId()))
+ .findAny().orElse(null);
+ if(null != origInstance && null != origInstance.getGroupInstances()) {
+ fixVFGroupInstances(oldService, origInstance);
+ instance.setGroupInstances(origInstance.getGroupInstances());
+ res = true;
+ }
+ }
+ return res;
}
- private void collectVFInstanceInputs(Map<String, List<ComponentInstanceInput>> instInputs, Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst) {
+ private boolean collectVFInstanceInputs(Component component, Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst) {
+ boolean res = false;
String ciUid = vfInst.getUniqueId();
String origCompUid = vfInst.getComponentUid();
+ if(null == component.getComponentInstancesInputs())
+ component.setComponentInstancesInputs(new HashMap<>());
+ Map<String, List<ComponentInstanceInput>> componentInstInputs = component.getComponentInstancesInputs();
Either<ToscaElement, StorageOperationStatus> origComp = fetchToscaElement(origCompMap, vfInst, origCompUid);
if(origComp.isRight())
- return;
+ return false;
Map<String, PropertyDataDefinition> origVFInputs = ((TopologyTemplate)origComp.left().value()).getInputs();
if (origVFInputs != null && !origVFInputs.isEmpty()) {
+ res = true;
Map<String, ComponentInstanceInput> collectedVFInputs = origVFInputs.values().stream()
.collect(Collectors.toMap(PropertyDataDefinition::getName, ComponentInstanceInput::new));
- List<ComponentInstanceInput> instInputList = instInputs.get(ciUid);
+
+ List<ComponentInstanceInput> instInputList = componentInstInputs.get(ciUid);
Map<String, ComponentInstanceInput> existingInstInputs = ToscaDataDefinition.listToMapByName(instInputList);
collectedVFInputs.putAll(existingInstInputs);
List<ComponentInstanceInput> mergedList = new ArrayList<>(collectedVFInputs.values());
- instInputs.put(ciUid, mergedList);
+ componentInstInputs.put(ciUid, mergedList);
}
+ return res;
}
private Either<ToscaElement, StorageOperationStatus> fetchToscaElement(Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst, String origCompUid) {
return artifactLabel;
}
- protected boolean fixVFGroups(Component component){
- boolean res = true;
-
+ public boolean fixVFGroups(Component component){
+ boolean res = false;
+
Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
List<GroupDefinition> groups = component.getGroups();
if (groups == null || groups.isEmpty()) {
- LOGGER.debug("No groups in component {} id {} ", component.getName(), component.getUniqueId());
+ LOGGER.debug("No groups in component {} id {} ", component.getName(), component.getUniqueId());
return res;
}
for (GroupDefinition group : groups) {
if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && deploymentArtifacts != null) {
if (isProblematicGroup(group, component.getName(), deploymentArtifacts)) {
- List<String> groupArtifacts = new ArrayList<String>(group.getArtifacts());
- group.getArtifacts().clear();
- group.getArtifactsUuid().clear();
+ res = true;
+ List<String> groupArtifacts = null == group.getArtifacts()? new ArrayList<>() : new ArrayList<>(group.getArtifacts());
+ group.setArtifacts(new ArrayList<>());
+ group.setArtifactsUuid(new ArrayList<>());
for (String artifactId : groupArtifacts) {
String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
LOGGER.debug("fix group: group name {} artifactId for fix {} artifactlabel {} ", group.getName(), artifactId, artifactlabel);
if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
group.getArtifactsUuid().add(correctArtifactUUID);
}
-
}
}
}
}
-
- }
-
+ }
return res;
}
- protected boolean fixVFGroupInstances(Component component, ComponentInstance instance){
- boolean res = true;
+ public boolean fixVFGroupInstances(Component component, ComponentInstance instance){
+ boolean res = false;
Map<String, ArtifactDefinition> deploymentArtifacts = instance.getDeploymentArtifacts();
List<GroupInstance> groupInstances = instance.getGroupInstances();
for (GroupInstance group : groupInstances) {
if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
if (isProblematicGroupInstance(group, instance.getName(), component.getName(), deploymentArtifacts)) {
-
- LOGGER.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", component.getUniqueId(), group.getName());
- List<String> groupArtifacts = Optional.ofNullable(group.getArtifacts()).orElse(new ArrayList<>());
-
+ res = true;
+ LOGGER.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", component.getUniqueId(), group.getName());
+ List<String> groupArtifacts = null == group.getArtifacts()? new ArrayList<>() : new ArrayList<>(group.getArtifacts());
group.setArtifacts(new ArrayList<>());
group.setArtifactsUuid(new ArrayList<>());
group.setGroupInstanceArtifacts(new ArrayList<>());
}
}
}
-
}
}
}
-
return res;
}
-
}
import org.openecomp.sdc.asdctool.impl.migration.v1610.TitanFixUtils;
import org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment;
import org.openecomp.sdc.asdctool.impl.migration.v1702.Migration1702;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707ArtifactUuidFix;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707Config;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.DistributionStatusUpdate;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707VnfFix;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.VfModulesPropertiesAdding;
+import org.openecomp.sdc.asdctool.impl.migration.v1707.*;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
private static final String SERVICE_MIGARTION_BEAN = "serviceMigrationBean";
private static enum MigrationOperationEnum {
- MIGRATION_1602_1604("migrate-1602-1604", SERVICE_MIGARTION_BEAN),
- ALIGN_DERIVED_FROM_1604("align-derived-from-1604", "derivedFromAlignment"),
- MIGRATE_1604_1607("migrate-1604-1607", SERVICE_MIGARTION_BEAN),
- ALIGN_VFC_NAMES_1604("align-vfc-names-1604", "vfcNamingAlignmentBean"),
- TEST_REMOVE_HEAT_PLACEHOLDERS("testremoveheatplaceholders", SERVICE_MIGARTION_BEAN),
- TEST_ADD_GROUP_UUIDS("testaddgroupuuids", SERVICE_MIGARTION_BEAN),
- ALIGN_GROUPS("align-groups", "groupsAlignment"),
- CLEAN_CSAR("clean-csar", "csarMigration"),
- POPULATE_COMPONENT_CACHE("populate-component-cache", "populateComponentCache"),
- FIX_PROPERTIES("fix-properties", "titanFixUtils"),
- ALIGN_TOSCA_ARTIFACTS("align-tosca-artifacts", "toscaArtifactsAlignment"),
+ MIGRATION_1602_1604("migrate-1602-1604", SERVICE_MIGARTION_BEAN),
+ ALIGN_DERIVED_FROM_1604("align-derived-from-1604", "derivedFromAlignment"),
+ MIGRATE_1604_1607("migrate-1604-1607", SERVICE_MIGARTION_BEAN),
+ ALIGN_VFC_NAMES_1604("align-vfc-names-1604", "vfcNamingAlignmentBean"),
+ TEST_REMOVE_HEAT_PLACEHOLDERS("testremoveheatplaceholders", SERVICE_MIGARTION_BEAN),
+ TEST_ADD_GROUP_UUIDS("testaddgroupuuids", SERVICE_MIGARTION_BEAN),
+ ALIGN_GROUPS("align-groups", "groupsAlignment"),
+ CLEAN_CSAR("clean-csar", "csarMigration"),
+ POPULATE_COMPONENT_CACHE("populate-component-cache", "populateComponentCache"),
+ FIX_PROPERTIES("fix-properties", "titanFixUtils"),
+ ALIGN_TOSCA_ARTIFACTS("align-tosca-artifacts", "toscaArtifactsAlignment"),
FIX_ICONS("fix-icons", "titanFixUtils"),
MIGRATION_1610_1702("migrate-1610-1702", "migration1702"),
MIGRATION_1702_1707("migrate-1702-1707", "migration1707"),
VFMODULES_PROPERTIES_ADDING("vfModules-properties-adding", "vfModulesPropertiesAdding"),
MIGRATION_1707_RELATIONS_FIX("fix-relations-after-migration-1707", "migration1707relationsFix"),
MIGRATION_1707_VNF_FIX("fix-vnf-after-migration-1707", "migration1707vnfFix"),
- MIGRATION_1707_UUID_FIX("fix-UUID-1707", "migration1707UuidFix");
+ MIGRATION_1707_UUID_FIX("fix-UUID-1707", "migration1707UuidFix"),
+ MIGRATION_1707_MISSING_INFO_FIX("fix-missing-info-1707", "migration1707MissingInfoFix");
// UPDATE_DATA_TYPES("update_data_types", "updateDataTypes");
private String value, beanName;
ToscaArtifactsAlignment toscaArtifactsAlignment = (ToscaArtifactsAlignment) context.getBean(operationEnum.getBeanName());
boolean isSuccessful = toscaArtifactsAlignment.alignToscaArtifacts();
if (isSuccessful) {
- log.info("Tosca Artifacts alignment was finished successfull");
+ log.info("Tosca Artifacts alignment was finished successfully");
System.exit(0);
} else {
log.info("Tosca Artifacts alignment has failed");
}
break;
case MIGRATION_1610_1702:
- log.info("Start ASDC migration from 1610 to 1702");
+ log.info("Start SDC migration from 1610 to 1702");
Migration1702 migration = (Migration1702) context.getBean(operationEnum.getBeanName());
isSuccessful = migration.migrate(appConfigDir);
if (isSuccessful) {
- log.info("ASDC migration from 1610 to 1702 was finished successful");
+ log.info("SDC migration from 1610 to 1702 was finished successful");
System.exit(0);
} else{
- log.info("ASDC migration from 1610 to 1702 has failed");
+ log.info("SDC migration from 1610 to 1702 has failed");
System.exit(2);
}
-
+
break;
case MIGRATION_1702_1707://this migration is currently not needed, but will be commented out for production env
- log.info("Start ASDC migration from 1702 to 1707");
+// log.info("Start SDC migration from 1702 to 1707");
Migration1707 migration1707 = (Migration1707) context.getBean(operationEnum.getBeanName());
isSuccessful = migration1707.migrate();
if (isSuccessful) {
}
String fixServices = args[3];
String runMode = args[4];
- log.info("Start fixing artifact UUID after 1707 migration with arguments run with configutation [{}] , for [{}] services", runMode, fixServices);
-
+ log.info("Start fixing artifact UUID after 1707 migration with arguments run with configuration [{}] , for [{}] services", runMode, fixServices);
+
Migration1707ArtifactUuidFix migrationFix = (Migration1707ArtifactUuidFix) context.getBean(operationEnum.getBeanName());
isSuccessful = migrationFix.migrate(fixServices, runMode);
if (isSuccessful) {
}
System.exit(0);
break;
+ case MIGRATION_1707_MISSING_INFO_FIX:
+
+ log.info("Start fixing missing group and instance info after 1707 migration");
+
+ Migration1707MissingInfoFix migration1707Fix = (Migration1707MissingInfoFix) context.getBean(operationEnum.getBeanName());
+ isSuccessful = migration1707Fix.migrate();
+ if (isSuccessful) {
+ log.info("Fixing groups and node templates missing info was finished successfully");
+ } else{
+ log.info("Fixing groups and node templates missing info has failed");
+ System.exit(2);
+ }
+ System.exit(0);
+ break;
default:
usageAndExit();
}
System.out.println("Usage: fix-relations-after-migration-1707 <configuration dir>");
System.out.println("Usage: fix-vnf-after-migration-1707 <configuration dir>");
System.out.println("Usage: fix-UUID-1707 <configuration dir> <all/distributed_only> <services/service_vf/fix/fix_only_services>");
+ System.out.println("Usage: fix-missing-info-1707 <configuration dir>");
}
}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.config;
+
+import org.openecomp.sdc.asdctool.migration.core.SdcMigrationTool;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
+import org.openecomp.sdc.asdctool.migration.resolver.SpringBeansMigrationResolver;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.dao.cassandra.MigrationTasksDao;
+import org.openecomp.sdc.be.dao.config.DAOSpringConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Configuration
+@Import(DAOSpringConfig.class)
+@ComponentScan({"org.openecomp.sdc.asdctool.migration.tasks",//migration tasks
+ "org.openecomp.sdc.be.model.operations.impl",
+ "org.openecomp.sdc.be.model.cache",
+ "org.openecomp.sdc.be.dao.titan",
+ "org.openecomp.sdc.be.dao.cassandra",
+ "org.openecomp.sdc.be.model.jsontitan.operations",
+ "org.openecomp.sdc.be.dao.jsongraph"})
+public class MigrationSpringConfig {
+
+ @Autowired(required=false)
+ private List<Migration> migrations = new ArrayList<>();
+
+ @Bean(name = "sdc-migration-tool")
+ public SdcMigrationTool sdcMigrationTool(MigrationResolver migrationResolver, SdcRepoService sdcRepoService) {
+ return new SdcMigrationTool(migrationResolver, sdcRepoService);
+ }
+
+ @Bean(name = "spring-migrations-resolver")
+ public SpringBeansMigrationResolver migrationResolver(SdcRepoService sdcRepoService) {
+ return new SpringBeansMigrationResolver(migrations, sdcRepoService);
+ }
+
+ @Bean(name = "sdc-repo-service")
+ public SdcRepoService sdcRepoService(MigrationTasksDao migrationTasksDao) {
+ return new SdcRepoService(migrationTasksDao);
+ }
+
+ @Bean(name = "sdc-migration-tasks-cassandra-dao")
+ public MigrationTasksDao migrationTasksDao() {
+ return new MigrationTasksDao();
+ }
+
+ @Bean(name = "cassandra-client")
+ public CassandraClient cassandraClient() {
+ return new CassandraClient();
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core;
+
+import java.math.BigInteger;
+
+public class DBVersion implements Comparable<DBVersion>{
+
+ private static final String VERSION_PARTS_SEPARATOR = "\\.";
+ private static final int MAJOR_PART_IDX = 0;
+ private static final int MINOR_PART_IDX = 1;
+ private BigInteger major;
+ private BigInteger minor;
+
+ /**
+ * The current db version. should be tested against real db to verify it is compatible to the db version
+ */
+ public static final DBVersion CURRENT_VERSION = new DBVersion(1710, 0);
+
+ private DBVersion(BigInteger major, BigInteger minor) {
+ this.major = major;
+ this.minor = minor;
+ }
+
+ private DBVersion(int major, int minor) {
+ this.major = BigInteger.valueOf(major);
+ this.minor = BigInteger.valueOf(minor);
+ }
+
+ public BigInteger getMajor() {
+ return major;
+ }
+
+ public BigInteger getMinor() {
+ return minor;
+ }
+
+ public static DBVersion from(BigInteger major, BigInteger minor) {
+ return new DBVersion(major, minor);
+ }
+
+ public static DBVersion fromString(String version) {
+ String[] split = version.split(VERSION_PARTS_SEPARATOR);
+ if (split.length != 2) {
+ throw new MigrationException("version must be of pattern: <major>.<minor>");
+ }
+ return new DBVersion(getVersionPart(split[MAJOR_PART_IDX]),
+ getVersionPart(split[MINOR_PART_IDX]));
+
+ }
+
+ private static BigInteger getVersionPart(String versionPart) {
+ try {
+ return new BigInteger(versionPart);
+ } catch (NumberFormatException e) {
+ throw new MigrationException(String.format("version part %s is non numeric", versionPart));
+ }
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s.%s", major, minor);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ DBVersion dbVersion = (DBVersion) o;
+
+ return major.equals(dbVersion.major) && minor.equals(dbVersion.minor);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = major.hashCode();
+ result = 31 * result + minor.hashCode();
+ return result;
+ }
+
+ @Override
+ public int compareTo(DBVersion o) {
+ if (o == null) {
+ return 1;
+ }
+ int majorsComparision = this.major.compareTo(o.major);
+ if (majorsComparision != 0) {
+ return majorsComparision;
+ }
+ int minorsComparision = this.minor.compareTo(o.minor);
+ if (minorsComparision != 0) {
+ return minorsComparision;
+ }
+ return 0;
+ }
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core;
+
+public class MigrationException extends RuntimeException {
+
+ public MigrationException(String message) {
+ super(message);
+ }
+
+ public MigrationException(String message, RuntimeException e) {
+ super(message, e);
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core;
+
+import org.openecomp.sdc.asdctool.migration.core.execution.MigrationExecutionResult;
+import org.openecomp.sdc.asdctool.migration.core.execution.MigrationExecutorImpl;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+public class SdcMigrationTool {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(SdcMigrationTool.class);
+
+ private MigrationResolver migrationsResolver;
+
+ private SdcRepoService sdcRepoService;
+
+ public SdcMigrationTool(MigrationResolver migrationsResolver, SdcRepoService sdcRepoService) {
+ this.migrationsResolver = migrationsResolver;
+ this.sdcRepoService = sdcRepoService;
+ }
+
+ public SdcMigrationTool() {
+ }
+
+ public boolean migrate(boolean enforceAll) {
+ LOGGER.info("starting migration process");
+ handleEnforceMigrationFlag(enforceAll);
+ List<Migration> migrations = migrationsResolver.resolveMigrations();
+ LOGGER.info("there are {} migrations task to execute", migrations.size());
+ for (Migration migration : migrations) {
+ try {
+ MigrationExecutionResult executionResult = new MigrationExecutorImpl().execute(migration);
+ if (migrationHasFailed(executionResult)) {
+ LOGGER.error("migration {} with version {} has failed. error msg: {}", migration.getClass().getName(), migration.getVersion().toString(), executionResult.getMsg());
+ return false;
+ }
+ sdcRepoService.createMigrationTask(executionResult.toMigrationTaskEntry());
+ } catch (RuntimeException e) {
+ LOGGER.error("migration {} with version {} has failed. error msg: {}", migration.getClass().getName(), migration.getVersion().toString(), e);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean migrationHasFailed(MigrationExecutionResult migrationResult) {
+ return migrationResult.getMigrationStatus().equals(MigrationResult.MigrationStatus.FAILED);
+ }
+
+ private void handleEnforceMigrationFlag(boolean enforceAll) {
+ if (enforceAll) {
+ LOGGER.info("enforcing migration for current version");
+ sdcRepoService.clearTasksForCurrentMajor();
+ }
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+
+import java.util.Date;
+
+public class MigrationExecutionResult {
+
+ private MigrationResult.MigrationStatus migrationStatus;
+ private String msg;
+ private double executionTime;
+ private DBVersion version;
+ private String taskName;
+
+ public MigrationTaskEntry toMigrationTaskEntry() {
+ MigrationTaskEntry migrationTaskEntry = new MigrationTaskEntry();
+ migrationTaskEntry.setMajorVersion(this.getVersion().getMajor().longValue());
+ migrationTaskEntry.setMinorVersion(this.getVersion().getMinor().longValue());
+ migrationTaskEntry.setTimestamp(new Date());
+ migrationTaskEntry.setTaskName(this.getTaskName());
+ migrationTaskEntry.setTaskStatus(this.getMigrationStatus().name());
+ migrationTaskEntry.setMessage(this.getMsg());
+ migrationTaskEntry.setExecutionTime(this.getExecutionTime());
+ return migrationTaskEntry;
+ }
+
+
+ public MigrationResult.MigrationStatus getMigrationStatus() {
+ return migrationStatus;
+ }
+
+ void setMigrationStatus(MigrationResult.MigrationStatus migrationStatus) {
+ this.migrationStatus = migrationStatus;
+ }
+
+ public String getMsg() {
+ return msg;
+ }
+
+ void setMsg(String msg) {
+ this.msg = msg;
+ }
+
+ double getExecutionTime() {
+ return executionTime;
+ }
+
+ void setExecutionTime(double executionTime) {
+ this.executionTime = executionTime;
+ }
+
+ public DBVersion getVersion() {
+ return version;
+ }
+
+ public void setVersion(DBVersion version) {
+ this.version = version;
+ }
+
+ String getTaskName() {
+ return taskName;
+ }
+
+ void setTaskName(String taskName) {
+ this.taskName = taskName;
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.MigrationException;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+
+public interface MigrationExecutor {
+
+ /**
+ * @param migration the migration to execute
+ * @return a {@link MigrationExecutionResult} with the relevant data on the current migration execution;
+ * @throws MigrationException in case there was an unexpected exception during migration
+ */
+ MigrationExecutionResult execute(Migration migration) throws MigrationException;
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.MigrationException;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.StopWatch;
+
+
+public class MigrationExecutorImpl implements MigrationExecutor {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(MigrationExecutorImpl.class);
+
+ @Override
+ public MigrationExecutionResult execute(Migration migration) throws MigrationException {
+ try {
+ LOGGER.info("starting migration {}. description: {}. version {}", migration.getClass().getName(), migration.description(), migration.getVersion().toString());
+ StopWatch stopWatch = new StopWatch();
+ stopWatch.start();
+ MigrationResult migrationResult = migration.migrate();
+ stopWatch.stop();
+ double executionTime = stopWatch.getTotalTimeSeconds();
+ return logAndCreateExecutionResult(migration, migrationResult, executionTime);
+ } catch (RuntimeException e) {
+ LOGGER.error("migration {} has failed!", migration.description(), e);
+ throw new MigrationException("migration %s failed!!!", e);
+
+ }
+ }
+
+ private MigrationExecutionResult logAndCreateExecutionResult(Migration migration, MigrationResult migrationResult, double executionTime) {
+ LOGGER.info("finished migration {}. with version {}. migration status: {}, migration message: {}, execution time: {}", migration.getClass().getName(), migration.getVersion().toString(), migrationResult.getMigrationStatus().name(), migrationResult.getMsg(), executionTime);
+ return createMigrationTask(migration, migrationResult, executionTime);
+ }
+
+ private MigrationExecutionResult createMigrationTask(Migration migration, MigrationResult migrationResult, double totalTimeSeconds) {
+ MigrationExecutionResult migrationExecutionResult = new MigrationExecutionResult();
+ migrationExecutionResult.setExecutionTime(totalTimeSeconds);
+ migrationExecutionResult.setMigrationStatus(migrationResult.getMigrationStatus());
+ migrationExecutionResult.setMsg(migrationResult.getMsg());
+ migrationExecutionResult.setTaskName(migration.getClass().getName());
+ migrationExecutionResult.setVersion(migration.getVersion());
+ return migrationExecutionResult;
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core.task;
+
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+
+public interface Migration {
+
+ String description();
+
+ DBVersion getVersion();
+
+ MigrationResult migrate();
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core.task;
+
+public class MigrationResult {
+
+ private String msg;
+ private MigrationStatus migrationStatus;
+
+ public String getMsg() {
+ return msg;
+ }
+
+ public void setMsg(String msg) {
+ this.msg = msg;
+ }
+
+ public MigrationStatus getMigrationStatus() {
+ return migrationStatus;
+ }
+
+ public void setMigrationStatus(MigrationStatus migrationStatus) {
+ this.migrationStatus = migrationStatus;
+ }
+
+ public enum MigrationStatus {
+ COMPLETED,
+ COMPLETED_WITH_ERRORS,
+ FAILED
+ }
+
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.main;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.openecomp.sdc.asdctool.migration.config.MigrationSpringConfig;
+import org.openecomp.sdc.asdctool.migration.core.SdcMigrationTool;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+public class MigrationMenu {
+
+ private final static Logger LOGGER = LoggerFactory.getLogger(MigrationMenu.class);
+
+ public static void main(String[] args) {
+ CommandLine commandLine = initCmdLineOptions(args);
+ String appConfigDir = commandLine.getOptionValue("c");
+ boolean enforceAll = commandLine.hasOption("e");
+ uploadConfiguration(appConfigDir);
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MigrationSpringConfig.class);
+ doMigrate(enforceAll, context);
+
+ }
+
+ private static void doMigrate(boolean enforceAll, AnnotationConfigApplicationContext context) {
+ SdcMigrationTool migrationTool = context.getBean(SdcMigrationTool.class);
+ boolean migrate = migrationTool.migrate(enforceAll);
+ if (migrate) {
+ LOGGER.info("migration completed successfully");
+ System.exit(0);
+ } else {
+ LOGGER.error("migration failed");
+ System.exit(1);
+ }
+ }
+
+ private static CommandLine initCmdLineOptions(String[] args) {
+ Options options = buildCmdLineOptions();
+ CommandLineParser parser = new DefaultParser();
+ try {
+ // parse the command line arguments
+ return parser.parse( options, args );
+ }
+ catch( ParseException exp ) {
+ // oops, something went wrong
+ System.err.println( "Parsing failed. Reason: " + exp.getMessage() );
+ usageAndExit(options);
+ }
+ return null;
+ }
+
+ private static void usageAndExit(Options options) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp( "yy", options );
+ System.exit(1);
+ }
+
+ private static Options buildCmdLineOptions() {
+ Option configPath = buildConfigPathOption();
+
+ Option enforceAll = buildEnforceAllOption();
+
+ Options options = new Options();
+ options.addOption(configPath);
+ options.addOption(enforceAll);
+ return options;
+ }
+
+ private static Option buildEnforceAllOption() {
+ return Option.builder("e")
+ .longOpt("enforceAll")
+ .desc("enforce running all migration steps for current version")
+ .build();
+ }
+
+ private static Option buildConfigPathOption() {
+ return Option.builder("c")
+ .longOpt("configFolderPath")
+ .required()
+ .hasArg()
+ .desc("path to sdc configuration folder - required")
+ .build();
+ }
+
+ private static void uploadConfiguration(String appConfigDir) {
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ }
+
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.resolver;
+
+
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+
+import java.util.List;
+
+public interface MigrationResolver {
+
+ /**
+ *
+ * @return a list of {@code T}
+ */
+ List<Migration> resolveMigrations();
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.resolver;
+
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class SpringBeansMigrationResolver implements MigrationResolver {
+
+ private List<Migration> migrations = new ArrayList<>();
+
+ private SdcRepoService sdcRepoService;
+
+ public SpringBeansMigrationResolver(List<Migration> migrations, SdcRepoService sdcRepoService) {
+ this.migrations = migrations;
+ this.sdcRepoService = sdcRepoService;
+ }
+
+ @Override
+ public List<Migration> resolveMigrations() {
+ migrations.sort(Comparator.comparing(Migration::getVersion));
+ return resolveNonExecutedMigrations();
+ }
+
+ //package private for testing
+ void setMigrations(List<Migration> migrations) {
+ this.migrations = migrations;
+ }
+
+ private List<Migration> resolveNonExecutedMigrations() {
+ DBVersion latestDBVersion = sdcRepoService.getLatestDBVersion();
+ return migrations.stream()
+ .filter(mig -> isMigrationVersionGreaterThanLatestVersion(latestDBVersion, mig))
+ .collect(Collectors.toList());
+ }
+
+ private boolean isMigrationVersionGreaterThanLatestVersion(DBVersion latestDBVersion, Migration mig) {
+ return mig.getVersion().compareTo(latestDBVersion) > 0;
+ }
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.service;
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.be.dao.cassandra.MigrationTasksDao;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+
+import java.math.BigInteger;
+
+public class SdcRepoService {
+
+ private MigrationTasksDao migrationTasksDao;
+
+ public SdcRepoService(MigrationTasksDao migrationTasksDao) {
+ this.migrationTasksDao = migrationTasksDao;
+ }
+
+ public DBVersion getLatestDBVersion() {
+ BigInteger currentMajorVersion = DBVersion.CURRENT_VERSION.getMajor();
+ BigInteger latestMinorVersion = migrationTasksDao.getLatestMinorVersion(currentMajorVersion);
+ return latestMinorVersion == null ? DBVersion.from(currentMajorVersion, BigInteger.valueOf(Integer.MIN_VALUE)) : DBVersion.from(currentMajorVersion, latestMinorVersion);
+ }
+
+ public void clearTasksForCurrentMajor() {
+ BigInteger currentMajorVersion = DBVersion.CURRENT_VERSION.getMajor();
+ migrationTasksDao.deleteAllTasksForVersion(currentMajorVersion);
+ }
+
+ public void createMigrationTask(MigrationTaskEntry migrationTaskEntry) {
+ migrationTasksDao.createMigrationTask(migrationTaskEntry);
+ }
+
+
+
+}
--- /dev/null
+//package org.openecomp.sdc.asdctool.migration.tasks.mig1710;//package org.openecomp.sdc.migration.tasks.mig1710;
+//
+//import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+//import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+//import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+//import org.springframework.stereotype.Component;
+//
+//@Component
+//public class ExampleMigration implements Migration {
+//
+// @Override
+// public String description() {
+// return "some description";
+// }
+//
+// @Override
+// public DBVersion getVersion() {
+// return DBVersion.fromString("1710.0");
+// }
+//
+// @Override
+// public MigrationResult migrate() {
+// MigrationResult migrationResult = new MigrationResult();
+// migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+// return migrationResult;
+// }
+//}
\ No newline at end of file
- { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
switchoverDetector:
<property scope="system" name="ECOMP-subcomponent-name" value="SDC-TOOL" />
<property name="default-log-pattern"
value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{uuid}|%X{serviceInstanceID}|%thread||${ECOMP-subcomponent-name}|%X{userId}|%level|%X{alarmSeverity}|%X{localAddr}|${beFqdn}|%X{remoteAddr}|%logger{35}|%X{timer}|ActivityType=<%M>, Desc=<%msg>%n" />
-
+
+
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <layout class="ch.qos.logback.classic.PatternLayout">
+ <encoder>
+ <pattern>${default-log-pattern}</pattern>
+ </encoder>
+ </layout>
+ </appender>
+
<appender name="DEBUG_ROLLING"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log</file>
<appender-ref ref="MALFORMED_DATA"/>
</logger>
+ <logger name="org.openecomp.sdc.asdctool.migration" level="INFO" >
+ <appender-ref ref="STDOUT"/>
+ </logger>
+
</configuration>
\ No newline at end of file
--- /dev/null
+#!/bin/bash
+
+##############################
+# Data Migration 1707
+##############################
+
+CURRENT_DIR=`pwd`
+BASEDIR=$(dirname $0)
+
+if [ ${BASEDIR:0:1} = "/" ]
+then
+ FULL_PATH=$BASEDIR
+else
+ FULL_PATH=$CURRENT_DIR/$BASEDIR
+fi
+
+source ${FULL_PATH}/baseOperation.sh
+
+mainClass="org.openecomp.sdc.asdctool.main.MigrationMenu"
+
+command="java $JVM_LOG_FILE -Xmx6000M -cp $JARS $mainClass fix-missing-info-1707 $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
--- /dev/null
+#!/bin/bash
+
+##############################
+# Data Migration
+##############################
+
+CURRENT_DIR=`pwd`
+BASEDIR=$(dirname $0)
+
+if [ ${BASEDIR:0:1} = "/" ]
+then
+ FULL_PATH=$BASEDIR
+else
+ FULL_PATH=$CURRENT_DIR/$BASEDIR
+fi
+
+source ${FULL_PATH}/baseOperation.sh
+
+mainClass="org.openecomp.sdc.asdctool.migration.main.MigrationMenu"
+
+command="java $JVM_LOG_FILE -Xmx6000M -cp $JARS $mainClass $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
+
--- /dev/null
+package org.openecomp.sdc.asdctool.migration;
+
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+
+public class DummyMigrationFactory {
+
+ public static Migration SUCCESSFUL_MIGRATION = new Migration() {
+ @Override
+ public String description() {
+ return "success mig";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ };
+
+ public static Migration FAILED_MIGRATION = new Migration() {
+ @Override
+ public String description() {
+ return "failed mig";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ };
+
+ public static Migration getMigration(String version, MigrationResult.MigrationStatus status) {
+ return new Migration() {
+ @Override
+ public String description() {
+ return "success mig";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString(version);
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(status);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+public class DBVersionTest {
+
+
+ @DataProvider(name = "invalidVersionStringsProvider")
+ private Object[][] invalidVersionStringsProvider() {
+ return new Object[][] {
+ {"1.1.1"},
+ {"1.a"},
+ {"a.1"},
+ {"1"}
+ };
+ }
+
+ @Test(dataProvider = "invalidVersionStringsProvider", expectedExceptions = MigrationException.class)
+ public void testFromString_invalidVersionString(String invalidVersion) {
+ DBVersion.fromString(invalidVersion);
+ }
+
+ @DataProvider(name = "validVersionStringsProvider")
+ private Object[][] validVersionStringsProvider() {
+ return new Object[][] {
+ {"1.1", "1.1"},
+ {"10100.0001", "10100.1"},
+ {"000.1", "0.1"},
+ {"01.00001000", "1.1000"},
+ };
+ }
+
+ @Test(dataProvider = "validVersionStringsProvider")
+ public void testFromString(String validString, String expectedVersionString) {
+ assertEquals(expectedVersionString, DBVersion.fromString(validString).toString());
+ }
+
+ @DataProvider(name = "versionComparisionProvider")
+ public static Object[][] versionComparisionProvider() {
+ return new Object[][] {
+ {"1.1", "001.00001", 0},
+ {"10.1", "0010.00001", 0},
+ {"1.1", "001.000010", -1},
+ {"1.1", "0010.00001", -1},
+ {"10.10", "0010.00001", 1},
+ {"1.1", "001.00", 1},
+ };
+ }
+
+ @Test(dataProvider = "versionComparisionProvider")
+ public void testVersionCompareTo2(String firstVersion, String otherVersion, int expectedComparisionResult) throws Exception {
+ assertEquals(DBVersion.fromString(firstVersion).compareTo(DBVersion.fromString(otherVersion)), expectedComparisionResult);
+ }
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.verification.Times;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class SdcMigrationToolTest {
+
+ @InjectMocks
+ private SdcMigrationTool testInstance = spy(SdcMigrationTool.class);
+
+ @Mock
+ private MigrationResolver migrationResolverMock;
+
+ @Mock
+ private SdcRepoService sdcRepoServiceMock;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testMigrate_noMigrations() throws Exception {
+ when(migrationResolverMock.resolveMigrations()).thenReturn(Collections.emptyList());
+ testInstance.migrate(false);
+ verify(sdcRepoServiceMock, new Times(0)).clearTasksForCurrentMajor();
+ verify(sdcRepoServiceMock, new Times(0)).createMigrationTask(Mockito.any());
+ }
+
+ @Test
+ public void testMigrate_enforceFlag_removeAllMigrationTasksForCurrentVersion() throws Exception {
+ when(migrationResolverMock.resolveMigrations()).thenReturn(Collections.emptyList());
+ testInstance.migrate(true);
+ verify(sdcRepoServiceMock, new Times(1)).clearTasksForCurrentMajor();
+ }
+
+ @Test
+ public void testMigrate_stopAfterFirstFailure() throws Exception {
+ when(migrationResolverMock.resolveMigrations()).thenReturn(Arrays.asList(new SuccessfulMigration(), new FailedMigration(), new SuccessfulMigration()));
+ testInstance.migrate(false);
+ verify(sdcRepoServiceMock, new Times(0)).clearTasksForCurrentMajor();
+ verify(sdcRepoServiceMock, new Times(1)).createMigrationTask(Mockito.any());
+
+ }
+
+ private class FailedMigration implements Migration {
+
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
+ return migrationResult;
+ }
+ }
+
+ private class SuccessfulMigration implements Migration {
+
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ return migrationResult;
+ }
+ }
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+public class MigrationExecutorImplTest {
+
+ @Test
+ public void testExecuteMigration() throws Exception {
+ MigrationExecutionResult execute = new MigrationExecutorImpl().execute(new DummyMigration());
+
+ }
+
+ private void assertMigrationTaskEntryByMigrationExecutionResult(MigrationExecutionResult executionResult, Migration migration, MigrationResult result) {
+ assertEquals(executionResult.getMsg(), result.getMsg());
+ assertEquals(executionResult.getMigrationStatus().name(), result.getMigrationStatus());
+ assertEquals(executionResult.getTaskName(), migration.getClass().getName());
+ assertEquals(executionResult.getVersion(), migration.getVersion());
+ assertNotNull(executionResult.getExecutionTime());
+ }
+
+ private class DummyMigration implements Migration {
+
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ }
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.resolver;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+public class SpringBeansMigrationResolverTest {
+
+ @InjectMocks
+ private SpringBeansMigrationResolver testInstance;
+
+ @Mock
+ private SdcRepoService sdcRepoServiceMock;
+
+ private List<Migration> migrations = Arrays.asList(createMigration("1710.1"), createMigration("1710.22"), createMigration("1707.12"), createMigration("1710.3"));
+
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ testInstance.setMigrations(migrations);
+ }
+
+ @Test
+ public void testResolveMigrations_getMigrationsWithVersionGreaterThanLatest() throws Exception {
+ when(sdcRepoServiceMock.getLatestDBVersion()).thenReturn(DBVersion.fromString("1710.2"));
+ List<Migration> resolvedMigrations = testInstance.resolveMigrations();
+ assertEquals(resolvedMigrations.size(), 2);
+ assertEquals(resolvedMigrations.get(0).getVersion(), DBVersion.fromString("1710.3"));
+ assertEquals(resolvedMigrations.get(1).getVersion(), DBVersion.fromString("1710.22"));
+ }
+
+ @Test
+ public void testResolveMigration_noLatestVersionForCurrentMajorVersion() throws Exception {
+ when(sdcRepoServiceMock.getLatestDBVersion()).thenReturn(DBVersion.fromString("1710.-1"));
+ List<Migration> resolvedMigrations = testInstance.resolveMigrations();
+ assertEquals(resolvedMigrations.size(), 3);
+ assertEquals(resolvedMigrations.get(0).getVersion(), DBVersion.fromString("1710.1"));
+ assertEquals(resolvedMigrations.get(1).getVersion(), DBVersion.fromString("1710.3"));
+ assertEquals(resolvedMigrations.get(2).getVersion(), DBVersion.fromString("1710.22"));
+ }
+
+ @Test
+ public void testResolveMigrations_emptyMigrationsList() throws Exception {
+ testInstance.setMigrations(Collections.emptyList());
+ when(sdcRepoServiceMock.getLatestDBVersion()).thenReturn(DBVersion.fromString("1710.-1"));
+ List<Migration> resolvedMigrations = testInstance.resolveMigrations();
+ assertTrue(resolvedMigrations.isEmpty());
+ }
+
+ private Migration createMigration(String version) {
+ return new Migration() {
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString(version);
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ return null;
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.scanner;
+
+import org.apache.commons.io.FileUtils;
+import org.openecomp.sdc.asdctool.migration.core.MigrationException;
+
+import java.io.File;
+import java.lang.reflect.Modifier;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * scan and instantiate classes of given type in the class path
+ */
+public class ClassScanner {
+
+
+ private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ public <T> List<T> getAllClassesOfType(String basePackage, Class<T> ofType) {
+ Collection<File> allClassesInPackage = getAllClassesInPackage(basePackage);
+ List<T> loadedClasses = new ArrayList<>();
+ for (File clazzFile : allClassesInPackage) {
+ Optional<T> instance = loadAndInstantiateClass(getClassReference(clazzFile), ofType);
+ instance.ifPresent(loadedClasses::add);
+ }
+ return loadedClasses;
+ }
+
+ private <T> Optional<T> loadAndInstantiateClass(String classReference, Class<T> ofType) {
+ try {
+ return instantiateClassOfType(classReference, ofType);
+ }catch (ClassNotFoundException e) {
+ //log
+ throw new MigrationException(String.format("could not find class %s of type %s. cause: %s", classReference, ofType.toGenericString(), e.getMessage()));
+ } catch (IllegalAccessException e1) {
+ //log
+ throw new MigrationException(String.format("could not instantiate class %s of type %s. class is not accessible. cause: %s", classReference, ofType.toGenericString(), e1.getMessage()));
+ } catch (InstantiationException e2) {
+ //log
+ throw new MigrationException(String.format("could not instantiate class %s of type %s. cause: %s", classReference, ofType.toGenericString(), e2.getMessage()));
+ }
+ }
+
+ private <T> Optional<T> instantiateClassOfType(String classReference, Class<T> ofType) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+ String className = classReference.replaceAll(".class$", "").replaceAll(".class", "");
+ Class<?> aClass = classLoader.loadClass(className);
+ if (ofType.isAssignableFrom(aClass) && isInstantiateAbleClass(aClass)){
+ return Optional.of((T) aClass.newInstance());
+ }
+ return Optional.empty();
+ }
+
+ private boolean isInstantiateAbleClass(Class<?> clazz) {
+ return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isEnum() && !clazz.isAnonymousClass() && !clazz.isInterface();
+ }
+
+ private Collection<File> getAllClassesInPackage(String fromPackage) {
+ String path = fromPackage.replace(".", "/");
+ URL resource = classLoader.getResource(path);
+ if (noMigrationTasks(resource)) {
+ return Collections.emptyList();
+ }
+ return FileUtils.listFiles(new File(resource.getFile()), new String[]{"class"}, true);
+ }
+
+ private boolean noMigrationTasks(URL resource) {
+ return resource == null;
+ }
+
+ private String getClassReference(File classFile) {
+ String asPackage = classFile.getPath().replace(File.separator, ".");
+ String classes = "classes.";
+ return asPackage.substring(asPackage.indexOf(classes) + classes.length());
+ }
+
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.service;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.verification.Times;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.be.dao.cassandra.MigrationTasksDao;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.math.BigInteger;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+public class SdcRepoServiceTest {
+
+ @InjectMocks
+ private SdcRepoService testInstance;
+
+ @Mock
+ private MigrationTasksDao migrationTasksDaoMock;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testGetLatestVersion_noMinorVersionForCurrentVersion() throws Exception {
+ when(migrationTasksDaoMock.getLatestMinorVersion(DBVersion.CURRENT_VERSION.getMajor())).thenReturn(null);
+ DBVersion latestDBVersion = testInstance.getLatestDBVersion();
+ assertEquals(latestDBVersion.getMajor(), DBVersion.CURRENT_VERSION.getMajor());
+ assertEquals(latestDBVersion.getMinor(), BigInteger.valueOf(Integer.MIN_VALUE));
+ }
+
+ @Test
+ public void testGetLatestVersion() throws Exception {
+ when(migrationTasksDaoMock.getLatestMinorVersion(DBVersion.CURRENT_VERSION.getMajor())).thenReturn(BigInteger.TEN);
+ DBVersion latestDBVersion = testInstance.getLatestDBVersion();
+ assertEquals(latestDBVersion.getMajor(), DBVersion.CURRENT_VERSION.getMajor());
+ assertEquals(latestDBVersion.getMinor(), BigInteger.TEN);
+ }
+
+ @Test
+ public void testCreateMigrationTask() throws Exception {
+ MigrationTaskEntry taskEntry = new MigrationTaskEntry();
+ testInstance.createMigrationTask(taskEntry);
+ verify(migrationTasksDaoMock, new Times(1)).createMigrationTask(taskEntry);
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.asdctool.migration.task;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.scanner.ClassScanner;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+
+public class MigrationTasksTest {
+
+ public static final String MIGRATIONS_BASE_PACKAGE = "org.openecomp.sdc.asdctool.migration.tasks";
+ private List<Migration> migrations;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ ClassScanner classScanner = new ClassScanner();
+ migrations = classScanner.getAllClassesOfType(MIGRATIONS_BASE_PACKAGE, Migration.class);
+ }
+
+ @Test
+ public void testNoTasksWithSameVersion() throws Exception {
+ Map<DBVersion, List<Migration>> migrationsByVersion = migrations.stream().collect(Collectors.groupingBy(Migration::getVersion));
+ migrationsByVersion.forEach((version, migrations) -> {
+ if (migrations.size() > 1) {
+ System.out.println(String.format("the following migration tasks have the same version %s. versions must be unique", version.toString()));
+ Assert.fail(String.format("migration tasks %s has same version %s. migration tasks versions must be unique.", getMigrationsNameAsString(migrations), version.toString()));
+ }
+ });
+ }
+
+ @Test
+ public void testNoTaskWithVersionGreaterThanCurrentVersion() throws Exception {
+ Set<Migration> migrationsWithVersionsGreaterThanCurrent = migrations.stream().filter(mig -> mig.getVersion().compareTo(DBVersion.CURRENT_VERSION) > 0)
+ .collect(Collectors.toSet());
+
+ if (!migrationsWithVersionsGreaterThanCurrent.isEmpty()) {
+ Assert.fail(String.format("migrations tasks %s have version which is greater than DBVersion.CURRENT_VERSION %s. did you forget to update current version?",
+ getMigrationsNameAsString(migrationsWithVersionsGreaterThanCurrent),
+ DBVersion.CURRENT_VERSION.toString()));
+ }
+ }
+
+ private String getMigrationsNameAsString(Collection<Migration> migrations) {
+ return StringUtils.join(migrations.stream().map(mig -> mig.getClass().getName()).collect(Collectors.toList()), ",");
+ }
+}
private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
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()));
+ needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
return needGenerate;
}
+ private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
+ return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
+ }
+
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) {
return Either.left(artifactResult.left().value());
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, 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;
// step 11
- Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
+ Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
if (payloadEither.isRight()) {
return Either.right(payloadEither.right().value());
}
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
- resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
+ resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
return resultOp;
} finally {
if (shouldLock) {
return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
}
- private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
+ private Either<byte[], ResponseFormat> validateInput(String componentId, 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);
if (validateMd5.isRight()) {
ResponseFormat responseFormat = validateMd5.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
// step 11
- Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
if (validateResult.isRight()) {
ResponseFormat responseFormat = validateResult.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(validateResult.right().value());
}
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);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
log.debug("Error during handle payload");
return Either.right(responseFormat);
}
Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
if (validateAndConvertHeatParamers.isRight()) {
ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
log.debug("Error during handle payload");
return Either.right(responseFormat);
}
return Either.left(true);
}
- private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
+ private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
+ Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
+ if (artifactById.isRight()) {
+ return Either.right(artifactById.right().value());
+ }
+ ArtifactDefinition currentArtifactInfo = artifactById.left().value();
+
+ ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
if (validateInformationalArtifactRes.isRight()) {
return Either.right(validateInformationalArtifactRes.right().value());
if (validateAndSetArtifactname.isRight()) {
return Either.right(validateAndSetArtifactname.right().value());
}
- Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId);
- if (artifactById.isRight()) {
- return Either.right(artifactById.right().value());
- }
- ArtifactDefinition currentArtifactInfo = artifactById.left().value();
if (operationName != null && interfaceName != null) {
operationName = operationName.toLowerCase();
interfaceName = interfaceName.toLowerCase();
}
- Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
+ Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
if (logicalNameStatus.isRight()) {
return Either.right(logicalNameStatus.right().value());
}
checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
}
- composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
+ composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
if (currentArtifactInfo != null) {
artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
}
boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
if (isDeploymentArtifact(artifactInfo)) {
- Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
+ Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
if (deploymentValidationResult.isRight()) {
return Either.right(deploymentValidationResult.right().value());
}
return Either.left(artifactInfo);
}
+ private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
+ if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
+ artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
+ artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
+ artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
+ }
+ }
+
private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
Either<ArtifactDefinition, ResponseFormat> result = null;
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("");
+ fetchedArtifact.setEsId(null);
+ fetchedArtifact.setArtifactName(null);
+ fetchedArtifact.setDescription(null);
+ fetchedArtifact.setApiUrl(null);
+ fetchedArtifact.setArtifactChecksum(null);
nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
- fetchedArtifact.setArtifactUUID("");
+ fetchedArtifact.setArtifactUUID(null);
long time = System.currentTimeMillis();
fetchedArtifact.setPayloadUpdateDate(time);
fetchedArtifact.setHeatParameters(null);
return Either.left(currentArtifactInfo);
}
- 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();
+ private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
+ ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
+ String artifactLabel = artifactInfo.getArtifactLabel();
if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("missing artifact logical name for component {}", componentId);
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)) {
+ if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
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, ComponentTypeEnum componentType) {
+ private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
boolean isUnique = true;
- if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
+ if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
+ artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
} else {
+ artifacts = artifactToscaOperation.getArtifacts(componentId);
}
- // 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)) {
}
}
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
if (allInterfacesOfResource.isLeft()) {
for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
for (Operation operation : interace.getOperationsMap().values()) {
* currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
*/
String currentHeatId = currHeatArtifact.getUniqueId();
-
+
String esArtifactId = currHeatArtifact.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
ESArtifactData esArtifactData = artifactfromES.left().value();
byte[] data = esArtifactData.getDataAsArray();
-
-
+
+
ArtifactDefinition updatedHeatArt = currHeatArtifact;
List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
esArtifactData.setId(updatedHeatArt.getEsId());
res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
-
+
if (res) {
log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
resultOp = Either.right(responseFormat);
// return resultOp;
}
-
+
insideEither = Either.left(updatedHeatArt);
}
}
updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
}
- if ( needToUpdateGroup && updateHeatEnvArtifact.isLeft() ){
+ if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
- if ( result != ActionStatus.OK ){
+ if (result != ActionStatus.OK) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
return Either.right(responseFormat);
}
}
+
+ if (updatedHeatEnvParams.isEmpty()) {
+ return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
+ }
resultOp = Either.left(insideEither);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
}
+ private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
+ return Either.right(responseFormat);
+ }
+
+
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());
Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
+ downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
}
if (errorWrapper.isEmpty()) {
result = Either.left(downloadedArtifact);
byte[] downloadedArtifact = null;
Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
- List<ArtifactDefinition> deploymentArtifacts = null;
+ List<ArtifactDefinition> artifactsList = null;
ArtifactDefinition deploymentArtifact = null;
if (artifacts != null && !artifacts.isEmpty()) {
- deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
+ artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
}
- if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
+ if (artifactsList == null || artifactsList.isEmpty()) {
log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
}
if (errorWrapper.isEmpty()) {
- deploymentArtifact = deploymentArtifacts.get(0);
+ deploymentArtifact = artifactsList.get(0);
downloadArtifactEither = downloadArtifact(deploymentArtifact);
if (downloadArtifactEither.isRight()) {
log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
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.IPropertyInputCommon;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
}
protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
- log.debug("validate property");
String type = null;
String innerType = null;
if (!propertyOperation.isPropertyTypeValid(property)) {
- log.info("Invalid type for property");
+ log.info("Invalid type for property {} type {}", property.getName(), property.getType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
return Either.right(responseFormat);
}
ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
innerType = propertyInnerTypeValid.getLeft();
if (!propertyInnerTypeValid.getRight().booleanValue()) {
- log.info("Invalid inner type for property");
+ log.info("Invalid inner type for property {} type {}", property.getName(), property.getType() );
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
return Either.right(responseFormat);
}
}
if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
- log.info("Invalid default value for property");
+ log.info("Invalid default value for property {} type {}", property.getName(), property.getType() );
ResponseFormat responseFormat;
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
return Arrays.asList(enumValues).contains(enumFound);
}
- protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(ComponentInstanceProperty property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
String propertyType = property.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
}
ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
+ log.trace("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));
--- /dev/null
+package org.openecomp.sdc.be.components.impl;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.annotation.PostConstruct;
+
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.Session;
+
+@Component("cassandra-health-check")
+public class CassandraHealthCheck {
+
+
+ private static Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class.getName());
+
+ private String localDataCenterName = null;
+
+ private Set<String> sdcKeyspaces = new HashSet<String>();
+
+ private int HC_FormulaNumber;
+
+ @PostConstruct
+ private void init() {
+
+ //Initialize local data center name - this field must be filled by DevOps
+ localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
+
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ log.error("localDataCenter Name in configuration.yaml is missing.");
+ return;
+ }
+
+ //Collect all SDC keyspaces
+ for (Table table : Table.values()) {
+ sdcKeyspaces.add(table.getTableDescription().getKeyspace());
+ }
+
+ String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
+ Properties prop = new Properties();
+ InputStream titanProp = null;
+ try {
+ //load a properties file
+ titanProp = new FileInputStream(titanCfgFile);
+ prop.load(titanProp);
+ //Add titan keyspace
+ String titanKeyspace = prop.getProperty("storage.cassandra.keyspace");
+ if (!GeneralUtility.isEmptyString(titanKeyspace)) {
+ sdcKeyspaces.add(titanKeyspace);
+ }
+ } catch (Exception e) {
+ log.error("Failed to open titen.properties file , url is : {}", titanCfgFile);
+ }
+
+ log.info("All sdc keyspaces are : {}", sdcKeyspaces);
+
+ //Calculate the Formula of Health Check
+ Cluster cluster = null;
+ try {
+
+ log.info("creating cluster for Cassandra Health Check.");
+ //Create cluster from nodes in cassandra configuration
+ cluster = SdcSchemaUtils.createCluster();
+ if (cluster == null) {
+ log.error("Failure create cassandra cluster.");
+ return;
+ }
+
+ Metadata metadata = cluster.getMetadata();
+
+ if (metadata == null) {
+ log.error("Failure get cassandra metadata.");
+ return;
+ }
+
+ log.info("Cluster Metadata: {}", metadata.toString());
+ List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
+ List<Integer> replactionFactorList = new ArrayList<Integer>();
+
+ //Collect the keyspaces Replication Factor of current localDataCenter
+ for (KeyspaceMetadata keyspace : keyspaces) {
+
+ if (sdcKeyspaces.contains(keyspace.getName())) {
+
+ log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
+ Map<String, String> replicationOptions = keyspace.getReplication();
+
+ //In 1 site with one data center
+ if (replicationOptions.containsKey("replication_factor")) {
+ replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
+ }
+ //In multiple sites with some data center
+ else if (replicationOptions.containsKey(localDataCenterName)) {
+ replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
+ }
+ }
+ }
+
+ if (replactionFactorList.size() == 0) {
+ log.error("Replication factor NOT found in all keyspaces");
+ return;
+ }
+
+ int maxReplicationFactor = Collections.max(replactionFactorList);
+ log.info("maxReplication Factor is: {}", maxReplicationFactor);
+
+ int localQuorum = maxReplicationFactor/2 + 1;
+ log.info("localQuorum is: {}", localQuorum);
+
+ HC_FormulaNumber = maxReplicationFactor - localQuorum;
+
+ log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
+
+
+ } catch (Exception e) {
+ log.error("create cassandra cluster failed with exception.", e);
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+
+ }
+
+ public boolean getCassandraStatus() {
+
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ log.error("localDataCenter Name in configuration.yaml is missing.");
+ return false;
+ }
+
+ Cluster cluster = null;
+ Session session = null;
+ try {
+ log.info("creating cluster for Cassandra for monitoring.");
+ cluster = SdcSchemaUtils.createCluster();
+ if (cluster == null) {
+ log.error("Failure create cassandra cluster.");
+ return false;
+ }
+ session = cluster.connect();
+ Metadata metadata = cluster.getMetadata();
+
+ if (metadata == null) {
+ log.error("Failure get cassandra metadata.");
+ return false;
+ }
+
+ log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
+
+ //Count the number of data center nodes that are down
+ Long downHostsNumber = metadata.getAllHosts().stream()
+ .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
+
+ log.info("The cassandra down nodes number is {}", downHostsNumber.toString());
+ return (HC_FormulaNumber >= downHostsNumber);
+
+ } catch (Exception e) {
+ log.error("create cassandra cluster failed with exception.", e);
+ return false;
+ } finally {
+ if (session != null) {
+ session.close();
+ }
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ }
+}
return Either.right(errorResponse);
}
- description = ValidationUtils.removeNoneUtf8Chars(description);
- description = ValidationUtils.normaliseWhitespace(description);
- description = ValidationUtils.stripOctets(description);
- description = ValidationUtils.removeHtmlTagsOnly(description);
-
+ description = cleanUpText(description);
Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type);
if (validatDescription.isRight()) {
ResponseFormat responseFormat = validatDescription.right().value();
}
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);
- }
- if (generateToscaRes.isRight()) {
- return generateToscaRes;
+ if(!isAbstractResource(component)){
+ 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);
+ if (generateToscaRes.isRight()) {
+ return generateToscaRes;
+ }
+ toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
+ }
}
- ArtifactDefinition toscaArtifact = generateToscaRes.left().value().left().value();
- component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
return generateToscaRes;
}
+ private boolean isAbstractResource(Component component) {
+ return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract();
+ }
+
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock,
boolean inTransaction, boolean fetchTemplatesFromDB) {
return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
}
}
- public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum audatingAction) {
+ public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) {
String descriptionUpdated = updatedComponent.getDescription();
String descriptionCurrent = currentComponent.getDescription();
if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
- Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, audatingAction);
+ Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction);
if (validateDescriptionResponse.isRight()) {
ResponseFormat errorRespons = validateDescriptionResponse.right().value();
return Either.right(errorRespons);
}
protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
-
- String genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
+ String genericTypeToscaName = null;
+ if(component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC){
+ genericTypeToscaName = ((Resource)component).getDerivedFrom().get(0);
+ } else {
+ genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
+ }
if(null == genericTypeToscaName)
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
}
return isMatchingType;
}
+
+ protected String cleanUpText(String text){
+ text = ValidationUtils.removeNoneUtf8Chars(text);
+ text = ValidationUtils.normaliseWhitespace(text);
+ text = ValidationUtils.stripOctets(text);
+ text = ValidationUtils.removeHtmlTagsOnly(text);
+ return text;
+ }
}
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.InputDefinition;
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.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
containerComponent = validateComponentExists.left().value();
}
- Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
- if (validateAllowedToContainCompInstances.isRight()) {
- return Either.right(validateAllowedToContainCompInstances.right().value());
+ if (ToscaUtils.isAtomicType(containerComponent)) {
+ log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
}
Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
}
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());
+ if (ToscaUtils.isAtomicType(containerComponent)) {
+ log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
}
Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
Optional<ComponentInstance> componentInstanceOptional = null;
Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
ComponentInstance oldComponentInstance = null;
+ boolean isNameChanged = false;
if (resultOp == null) {
componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
if (resultOp == null) {
oldComponentInstance = componentInstanceOptional.get();
String newInstanceName = componentInstance.getName();
+ if ( oldComponentInstance!=null && oldComponentInstance.getName() != null
+ && !oldComponentInstance.getName().equals( newInstanceName ) )
+ isNameChanged = true;
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);
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));
+ }else{
+ //region - Update instance Groups
+ if ( isNameChanged ){
+ Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId );
+ if ( result.isRight() )
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() );
+ }
+ //endregion
}
}
if (resultOp == null) {
}
return resultOp;
}
+ /**
+ * @param oldPrefix- The normalized old vf name
+ * @param newNormailzedPrefix- The normalized new vf name
+ * @param qualifiedGroupInstanceName- old Group Instance Name
+ **/
+ //modify group names
+ private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){
+ if (qualifiedGroupInstanceName == null){
+ log.info("CANNOT change group name ");
+ return null;
+ }
+ if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
+ return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
+ return qualifiedGroupInstanceName;
+ }
private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
oldComponentInstance.setName(newComponentInstance.getName());
oldComponentInstance.setModificationTime(System.currentTimeMillis());
oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ if ( oldComponentInstance.getGroupInstances() != null )
+ oldComponentInstance.getGroupInstances().forEach( group ->
+ group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) );
return oldComponentInstance;
}
resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
}
}
+ if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){
+ List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+ if(CollectionUtils.isNotEmpty(inputsToDelete)){
+ StorageOperationStatus deleteInputsRes =
+ toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
+ if(deleteInputsRes != StorageOperationStatus.OK){
+ log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
+ }
+ }
+ }
return resultOp;
}
}
}
- protected abstract Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent);
-
protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
package org.openecomp.sdc.be.components.impl;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
+import com.thinkaurelius.titan.core.TitanGraph;
+import fj.data.Either;
import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.LinkedList;
-import java.util.List;
-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.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.*;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-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;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-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;
+import org.openecomp.sdc.be.model.*;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.thinkaurelius.titan.core.TitanGraph;
-
-import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("elementsBusinessLogic")
public class ElementBusinessLogic extends BaseBusinessLogic {
return elementOperation.getDefaultHeatTimeout();
}
- public Either<Map<String, List<? extends Component>>, ResponseFormat> getCatalogComponents(String userId) {
+ public Either<Map<String, List<? extends Component>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
}
Map<String, List<? extends Component>> resMap = new HashMap<>();
- Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE, true);
+ Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE,excludeTypes, true);
if (resResources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE, true);
+ Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE,excludeTypes, true);
if (resServices.isLeft()) {
// Either<List<Product>, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false);
// if (resProducts.isLeft()) {
}
if (filters == null || filters.isEmpty()) {
- Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, false);
+ Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum,null, false);
if(componentsList.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value())));
}
log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
+
Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
if(componentsListByUuid.isRight()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching failed");
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), ComponentTypeEnum.SERVICE);
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue()+ " fetching failed");
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum);
return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
}
-
- log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + "Service fetching successful");
+
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful");
return Either.left(componentsListByUuid.left().value());
}
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction) {
+ public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
Either<GroupDefinition, ResponseFormat> result = null;
try {
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;
+ if ( shouldLock ){
+ 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)) {
} else {
titanDao.rollback();
}
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ if( shouldLock )
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
}
}
String nameUpdated = groupUpdate.getName();
String nameCurrent = currentGroup.getName();
if (!nameCurrent.equals(nameUpdated)) {
- Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName());
+ Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
if (validatNameResponse.isRight()) {
ResponseFormat errorRespons = validatNameResponse.right().value();
return Either.right(errorRespons);
* @param groupUpdateName
* @return
*/
- private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName) {
+ private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
try {
// Check if the group name is in old format.
if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
String[] split2 = groupUpdateName.split("\\.\\.");
String groupUpdateResourceName = split2[0];
String groupUpdateCounter = split2[2];
+ if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes]
+ if (!currentResourceName.equals(groupUpdateResourceName)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
+ }
- if (!currentResourceName.equals(groupUpdateResourceName)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
+ if (!currentCounter.equals(groupUpdateCounter)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
+ }
}
- if (!currentCounter.equals(groupUpdateCounter)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
- }
}
return Either.left(true);
package org.openecomp.sdc.be.components.impl;
+import java.io.IOException;
+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 javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
-import javax.servlet.ServletContext;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
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.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
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.reflect.TypeToken;
@Component("healthCheckBusinessLogic")
public class HealthCheckBusinessLogic {
private static Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT);
private static final String BE_HEALTH_CHECK_STR = "beHealthCheck";
+ private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s";
@Resource
private TitanGenericDao titanGenericDao;
@Resource
private DistributionEngineClusterHealth distributionEngineClusterHealth;
+ @Resource
+ private CassandraHealthCheck cassandraHealthCheck;
+
@Autowired
private SwitchoverDetector switchoverDetector;
private static Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName());
- private volatile List<HealthCheckInfo> lastBeHealthCheckInfos = null;
+ private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
- // private static volatile HealthCheckBusinessLogic instance;
- //
public HealthCheckBusinessLogic() {
}
@PostConstruct
public void init() {
- lastBeHealthCheckInfos = getBeHealthCheckInfos();
+ prevBeHealthCheckInfos = getBeHealthCheckInfos();
- log.debug("After initializing lastBeHealthCheckInfos: {}", lastBeHealthCheckInfos);
+ log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
healthCheckScheduledTask = new HealthCheckScheduledTask();
}
- //
- // public static HealthCheckBusinessLogic getInstance(){
- //// if (instance == null){
- //// instance = init();
- //// }
- // return instance;
- // }
-
- // private synchronized static HealthCheckBusinessLogic init() {
- // if (instance == null){
- // instance = new HealthCheckBusinessLogic();
- // }
- // return instance;
- // }
-
- private List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) {
-
- List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>();
-
- // BE
- getBeHealthCheck(servletContext, healthCheckInfos);
-
- // ES
- getEsHealthCheck(servletContext, healthCheckInfos);
-
- // Titan
- getTitanHealthCheck(servletContext, healthCheckInfos);
-
- // Distribution Engine
- getDistributionEngineCheck(servletContext, healthCheckInfos);
-
- return healthCheckInfos;
- }
-
- private List<HealthCheckInfo> getBeHealthCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
- String appVersion = ExternalConfiguration.getAppVersion();
- String description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.UP, appVersion, description));
- return healthCheckInfos;
- }
-
- public List<HealthCheckInfo> getTitanHealthCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
- // Titan health check and version
- TitanGenericDao titanStatusDao = (TitanGenericDao) getDao(servletContext, TitanGenericDao.class);
- String description;
- boolean isTitanUp;
-
- try {
- isTitanUp = titanStatusDao.isGraphOpen();
- } catch (Exception e) {
- description = "Titan error: " + e.getMessage();
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, description));
- return healthCheckInfos;
- }
- if (isTitanUp) {
- description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, description));
- } else {
- description = "Titan graph is down";
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, description));
- }
- return healthCheckInfos;
- }
-
- public List<HealthCheckInfo> getEsHealthCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
-
- // ES health check and version
- IEsHealthCheckDao esStatusDao = (IEsHealthCheckDao) getDao(servletContext, IEsHealthCheckDao.class);
- HealthCheckStatus healthCheckStatus;
- String description;
-
- try {
- healthCheckStatus = esStatusDao.getClusterHealthStatus();
- } catch (Exception e) {
- healthCheckStatus = HealthCheckStatus.DOWN;
- description = "ES cluster error: " + e.getMessage();
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
- return healthCheckInfos;
- }
- if (healthCheckStatus.equals(HealthCheckStatus.DOWN)) {
- description = "ES cluster is down";
- } else {
- description = "OK";
- }
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
- return healthCheckInfos;
- }
-
- public Object getDao(ServletContext servletContext, Class<?> clazz) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(servletContext);
-
- return webApplicationContext.getBean(clazz);
- }
-
- private void getDistributionEngineCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
-
- DistributionEngineClusterHealth deDao = (DistributionEngineClusterHealth) getDao(servletContext, DistributionEngineClusterHealth.class);
- HealthCheckInfo healthCheckInfo = deDao.getHealthCheckInfo();
+ public boolean isDistributionEngineUp() {
- healthCheckInfos.add(healthCheckInfo);
-
- }
-
- public boolean isDistributionEngineUp(ServletContext servletContext) {
-
- DistributionEngineClusterHealth deDao = (DistributionEngineClusterHealth) getDao(servletContext, DistributionEngineClusterHealth.class);
- HealthCheckInfo healthCheckInfo = deDao.getHealthCheckInfo();
+ HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) {
return false;
}
public List<HealthCheckInfo> getBeHealthCheckInfosStatus() {
- return lastBeHealthCheckInfos;
+ return prevBeHealthCheckInfos;
}
// BE
getBeHealthCheck(healthCheckInfos);
- // ES
- getEsHealthCheck(healthCheckInfos);
+ /*// ES
+ getEsHealthCheck(healthCheckInfos);*/
// Titan
getTitanHealthCheck(healthCheckInfos);
// Distribution Engine
getDistributionEngineCheck(healthCheckInfos);
+ //Cassandra
+ getCassandraHealthCheck(healthCheckInfos);
+
+ // Amdocs
+ getAmdocsHealthCheck(healthCheckInfos);
+
return healthCheckInfos;
}
return healthCheckInfos;
}
- public List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ //Removed from aggregate HC - TDP 293490
+/* private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
// ES health check and version
HealthCheckStatus healthCheckStatus;
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
return healthCheckInfos;
}
-
+*/
public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
// Titan health check and version
String description;
return healthCheckInfos;
}
+ private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+
+ String description;
+ boolean isCassandraUp;
+
+ try {
+ isCassandraUp = cassandraHealthCheck.getCassandraStatus();
+ } catch (Exception e) {
+ isCassandraUp = false;
+ description = "Cassandra error: " + e.getMessage();
+ }
+ if (isCassandraUp) {
+ description = "OK";
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.UP, null, description));
+ } else {
+ description = "Cassandra is down";
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.DOWN, null, description));
+ }
+ return healthCheckInfos;
+
+ }
+
private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) {
HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
}
+ private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ HealthCheckStatus healthCheckStatus;
+ String description;
+ Map<String, Object> amdocsHC = null;
+ String version = null;
+ List<HealthCheckInfo> componentsInfo = null;
+ CloseableHttpClient httpClient = getHttpClient();
+ String amdocsHealtchCheckUrl = buildHealthCheckUrl();
+ HttpGet httpGet = new HttpGet(amdocsHealtchCheckUrl);
+ CloseableHttpResponse beResponse;
+ int beStatus;
+ try {
+ beResponse = httpClient.execute(httpGet);
+ beStatus = beResponse.getStatusLine().getStatusCode();
+
+ HttpEntity entity = beResponse.getEntity();
+ String beJsonResponse = EntityUtils.toString(entity);
+ Gson gson = new Gson();
+ amdocsHC = gson.fromJson(beJsonResponse, Map.class);
+ version = amdocsHC.get("sdcVersion") != null ? amdocsHC.get("sdcVersion").toString() : null;
+ Object object = amdocsHC.get("componentsInfo");
+ Type listType = new TypeToken<List<HealthCheckInfo>>(){}.getType();
+ componentsInfo = gson.fromJson(object.toString(), listType);
+
+ if (beStatus != HttpStatus.SC_OK) {
+ healthCheckStatus = HealthCheckStatus.DOWN;
+ StringBuilder sb = new StringBuilder();
+ componentsInfo.forEach(x -> {
+ if (x.getHealthCheckStatus()==HealthCheckStatus.DOWN){
+ sb.append("Component "+x.getHealthCheckComponent().name()+" is Down,");
+ }
+ });
+ //Removing the last comma
+ description = sb.length()>0
+ ? sb.substring(0, sb.length()-1)
+ : "Onboarding is Down, specific reason unknown";//No Amdocs inner component returned DOWN, but the status of Amdocs HC is still DOWN.
+ } else {
+ healthCheckStatus = HealthCheckStatus.UP;
+ description = "OK";
+
+
+ }
+
+ } catch (Exception e) {
+ healthCheckStatus = HealthCheckStatus.DOWN;
+ description = "Onboarding unexpected response: " + e.getMessage();
+ } finally {
+ if (httpClient != null) {
+ try {
+ httpClient.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ON_BOARDING, healthCheckStatus, version, description, componentsInfo));
+ return healthCheckInfos;
+ }
+
+ private CloseableHttpClient getHttpClient() {
+ int timeout = 3000;
+ RequestConfig.Builder requestBuilder = RequestConfig.custom();
+ requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout);
+
+ HttpClientBuilder builder = HttpClientBuilder.create();
+ builder.setDefaultRequestConfig(requestBuilder.build());
+ return builder.build();
+ }
+
@PreDestroy
private void destroy() {
healthLogger.trace("Executing BE Health Check Task");
- List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos();
- boolean healthStatus = getAggregateBeStatus(beHealthCheckInfos);
+ List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
+ boolean healthStatus = getAggregateBeStatus(currentBeHealthCheckInfos);
+
+ boolean prevHealthStatus = getAggregateBeStatus(prevBeHealthCheckInfos);
- boolean lastHealthStatus = getAggregateBeStatus(lastBeHealthCheckInfos);
+ boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
- if (lastHealthStatus != healthStatus) {
+ if (prevHealthStatus != healthStatus || anyStatusChanged) {
log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
- lastBeHealthCheckInfos = beHealthCheckInfos;
+ prevBeHealthCheckInfos = currentBeHealthCheckInfos;
logAlarm(healthStatus);
+ }
- } else {
- // check if we need to update the status's list in case one of
- // the statuses was changed
- if (true == anyStatusChanged(beHealthCheckInfos, lastBeHealthCheckInfos)) {
- lastBeHealthCheckInfos = beHealthCheckInfos;
- }
+ }
- }
+ private boolean getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
+
+ boolean status = true;
+ for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
+ if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) {
+ status = false;
+ break;
+ }
+ }
+ return status;
}
}
- private void logAlarm(boolean lastHealthState) {
- if (lastHealthState == true) {
+ private void logAlarm(boolean prevHealthState) {
+ if (prevHealthState) {
BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR);
} else {
BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);
}
}
- private boolean getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
-
- boolean status = true;
-
- for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
- if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) {
- status = false;
- break;
- }
- }
- return status;
+ private void logAlarm(String componentChangedMsg) {
+ BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg);
}
+
public String getSiteMode() {
return switchoverDetector.getSiteMode();
}
- public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> lastBeHealthCheckInfos) {
+ public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
boolean result = false;
- if (beHealthCheckInfos != null && lastBeHealthCheckInfos != null) {
+ if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
Map<HealthCheckComponent, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
- Map<HealthCheckComponent, HealthCheckStatus> lastValues = lastBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
+ Map<HealthCheckComponent, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
- if (currentValues != null && lastValues != null) {
+ if (currentValues != null && prevValues != null) {
int currentSize = currentValues.size();
- int lastSize = lastValues.size();
+ int prevSize = prevValues.size();
+
+ if (currentSize != prevSize) {
+
+ result = true; //extra/missing component
+
+ Map<HealthCheckComponent, HealthCheckStatus> notPresent = null;
+ if (currentValues.keySet().containsAll(prevValues.keySet())) {
+ notPresent = new HashMap<>(currentValues);
+ notPresent.keySet().removeAll(prevValues.keySet());
+ } else {
+ notPresent = new HashMap<>(prevValues);
+ notPresent.keySet().removeAll(currentValues.keySet());
+ }
+
+ for (HealthCheckComponent component : notPresent.keySet()) {
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
+ }
+ // HealthCheckComponent changedComponent = notPresent.keySet().iterator().next();
- if (currentSize != lastSize) {
- result = true;
} else {
for (Entry<HealthCheckComponent, HealthCheckStatus> entry : currentValues.entrySet()) {
HealthCheckComponent key = entry.getKey();
HealthCheckStatus value = entry.getValue();
- if (false == lastValues.containsKey(key)) {
- result = true;
+ if (!prevValues.containsKey(key)) {
+ result = true; //component missing
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
break;
}
- HealthCheckStatus lastHealthCheckStatus = lastValues.get(key);
+ HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
- if (value != lastHealthCheckStatus) {
- result = true;
+ if (value != prevHealthCheckStatus) {
+ result = true; //component status changed
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
break;
}
}
}
- } else if (currentValues == null && lastValues == null) {
- result = false;
- } else {
- result = true;
}
- } else if (beHealthCheckInfos == null && lastBeHealthCheckInfos == null) {
+ } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
result = false;
} else {
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
result = true;
}
return result;
}
+
+ private String buildHealthCheckUrl() {
+
+ Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
+
+ String protocol = onboardingConfig.getProtocol();
+ String host = onboardingConfig.getHost();
+ Integer port = onboardingConfig.getPort();
+ String uri = onboardingConfig.getHealthCheckUri();
+
+ return protocol + "://" + host + ":" + port + uri;
+ }
}
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 CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
}
public enum ResultStatusEnum {
PARAMETERS("parameters"),
// Import Validations
TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"),
+ SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"),
// Attributes
ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input");
}
resList = result.left().value();
- /*int index = 0;
- for (Entry<String, List<InputDefinition>> entry : newInputsMap.entrySet()) {
-
- 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, inputsValueToCreateMap, allDataTypes.left().value(), resList, index, 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;
- }
-
- }
- }
-
- }*/
+
}
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());
- }
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
- for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
- String inputName = inputDefinition.getKey();
- inputDefinition.getValue().setName(inputName);
+ 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 = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
- if(mergeEither.isRight()){
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
- }
- inputs = mergeEither.left().value();
+ Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
+ if(preparedInputEither.isRight()){
+ return Either.right(preparedInputEither.right().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())));
+ }
+ if (resourceProperties != null) {
+ Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
+ Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
+ if(mergeEither.isRight()){
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
}
- result = Either.left(assotiateInputsEither.left().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())));
+ }
+ result = Either.left(assotiateInputsEither.left().value());
return result;
}
}
List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId);
- Map<String, List<ComponentInstanceInput>> insInputsMatToDelete = new HashMap<>();
-
+
if(inputsValue != null && !inputsValue.isEmpty()){
for(ComponentInstanceInput inputValue: inputsValue){
String compInstId = inputValue.getComponentInstanceId();
prepareValueBeforeDelete(compInstId, inputForDelete, inputValue, inputValue.getPath());
status = toscaOperationFacade.updateComponentInstanceInput(component, compInstId, inputValue);
- List<ComponentInstanceInput> inputList = null;
if(status != StorageOperationStatus.OK){
log.debug("Component id: {} update component instance property {} id: {} failed", componentId, inputValue.getUniqueId(), inputId);
deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
@Component("productComponentInstanceBusinessLogic")
public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
- @Override
- protected Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent) {
- return Either.left(true);
- }
@Override
protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
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.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import org.openecomp.sdc.be.model.ImportCsarInfo;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.NodeTypeInfo;
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.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
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.StorageOperationStatus;
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.InputsOperation;
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.servlets.RepresentationUtils;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
+import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
@Autowired
private InputsBusinessLogic inputsBusinessLogic;
- @javax.annotation.Resource
- private InputsOperation inputOperation;
-
- // @Autowired
- // private GroupOperation groupOperation;
-
- @Autowired
- private IHeatParametersOperation heatParametersOperation;
-
- // @Autowired
- // private IArtifactOperation artifactOperation;
-
@Autowired
private CompositionBusinessLogic compositionBusinessLogic;
* the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param
*
* @param getAbstract
- * @param userId
- * TODO
+ * @param userId TODO
* @return
*/
public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
}
Boolean isHighest = null;
switch (highestFilter) {
- case ALL:
- break;
- case HIGHEST_ONLY:
- isHighest = true;
- break;
- case NON_HIGHEST_ONLY:
- isHighest = false;
- break;
- default:
- break;
+ case ALL:
+ break;
+ case HIGHEST_ONLY:
+ isHighest = true;
+ break;
+ case NON_HIGHEST_ONLY:
+ isHighest = false;
+ break;
+ default:
+ break;
}
Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
}
private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
- String csarUUID) {
+ String csarUUID) {
// check state
if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
Either<Resource, ResponseFormat> result = null;
String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+ String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = null;
+ ImportCsarInfo importCsarInfo = new ImportCsarInfo(newRresource.getName(), user, csarUUID, csar.left().value());
+
try {
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate = null;
Resource preparedResource = null;
- Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user);
+ Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user, importCsarInfo.getCreatedNodesToscaResourceNames(), null, null);
if (uploadComponentInstanceInfoMap.isRight()) {
ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
componentsUtils.auditResource(responseFormat, user, newRresource, "", "", updateResource, null);
result = Either.right(responseFormat);
return result;
}
+ Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true, instances);
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true,
+ instances);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID);
result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
}
preparedResource = prepareForUpdate.left().value().left;
- String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
- parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContents, false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
if (parseNodeTypeInfoYamlEither.isRight()) {
ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null);
preparedResource = dataModelResponse.left().value();
}
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts,
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, importCsarInfo, createdArtifacts,
artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true);
if (createdCsarArtifactsEither.isRight()) {
}
- 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, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
+ private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user,
+ boolean inTransaction, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
try {
nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
- List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap);
- validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
+ Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap);
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) {
+ for (Entry<String, String> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) {
String currVfcToscaName = currVfcToscaNameEntry.getValue();
+ String currNamespace = currVfcToscaNameEntry.getKey();
log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
}
if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
List<ArtifactDefinition> currArtifacts = new ArrayList<>();
- for (String currNamespace : currVfcToscaNameEntry.getKey().getValue()) {
- if (extractedVfcsArtifacts.containsKey(currNamespace)) {
- handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
- }
+ if (extractedVfcsArtifacts.containsKey(currNamespace)) {
+ handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
}
curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
if (curNodeTypeArtifactsToHandleRes.isRight()) {
}
}
if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
- nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey().getKey(), curNodeTypeArtifactsToHandle);
+ nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
}
}
} catch (Exception 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;
* @return
*/
public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
- User user, boolean inTransaction) {
+ User user, boolean inTransaction) {
Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
Either<Resource, ResponseFormat> changeStateResponse;
}
@SuppressWarnings("unchecked")
- private List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractVfcToscaNames(Map<String, byte[]> csar, String yamlFileName, String vfResourceName, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
- 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);
- Map<String,String> nestedServiceTemplatesMap = new HashMap<>();
- for(UploadComponentInstanceInfo ci : uploadComponentInstanceInfoMap.values()){
- if(ci.getProperties() != null && ci.getProperties().containsKey("service_template_filter")){
- String tempName = CsarUtils.DEFINITIONS_PATH + ((Map<String, String>)ci.getProperties().get("service_template_filter").get(0).getValue()).get("substitute_service_template");
- putNodeTypesFromYaml(csar,tempName, nodeTypes);
- nestedServiceTemplatesMap.put(ci.getType(), tempName);
- }
+ private Map<String, String> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String yamlFileName, String vfResourceName, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
+ Map<String, String> vfcToscaNames = new HashMap<>();
+
+ Map<String, Object> nodes = extractAllNodes(nodeTypesInfo);
+ if (!nodes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ String toscaResourceName = buildNodeToscaResourceName(vfResourceName, nodeType.getKey());
+ vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
}
+ }
+ return vfcToscaNames;
+ }
- 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(), nestedServiceTemplatesMap);
- }
+ private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo) {
+ Map<String, Object> nodes = new HashMap<>();
+ for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(nodeTypeInfo.getMappedToscaTemplate(), ToscaTagNamesEnum.NODE_TYPES);
+ if (eitherNodeTypes.isLeft()) {
+ nodes.putAll(eitherNodeTypes.left().value());
}
}
- return vfcToscaNames;
+ return nodes;
}
@SuppressWarnings("unchecked")
}
}
- private void addVfcToscaNameFindSubstitutes(Map<String, byte[]> csar, String vfResourceName, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames, String nodeTypeFullName, Map<String, String> nestedServiceTemplatesMap) {
-
- String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName);
- String nodeTypeTemplateYamlName =null;
- if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){
- nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
- }
- List<String> relatedVfcsToscaNameSpaces = new ArrayList<>();
- relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName));
- if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) {
- addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces, nestedServiceTemplatesMap);
- }
- 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, String> nestedServiceTemplatesMap) {
Map<String, Object> nodeTypes = new HashMap<>();
}
toscaNameSpaces.add(toscaNameSpace);
- String nodeTypeTemplateYamlName =null;
- if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){
+ String nodeTypeTemplateYamlName = null;
+ if (nestedServiceTemplatesMap.containsKey(nodeTypeFullName)) {
nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
}
- if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) {
+ if (nodeTypeTemplateYamlName != null && csar.containsKey(nodeTypeTemplateYamlName)) {
addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces, nestedServiceTemplatesMap);
}
}
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<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, user, yamlFileContents, yamlFileName, csar.left().value(), csarUUID);
+
+ Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar.left().value(), resource);
+ ImportCsarInfo importCsarInfo = new ImportCsarInfo(resource.getName(), user, csarUUID, csar.left().value());
+ Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate, true, false, null);
if (createResourceFromYaml.isRight()) {
log.debug("Couldn't create resource from YAML");
return Either.right(createResourceFromYaml.right().value());
return Either.left(vfResource);
}
+ @SuppressWarnings("unchecked")
+ private Map<String, NodeTypeInfo> extractNodeTypesInfo(Map<String, byte[]> csar, String yamlFileContent) {
+ Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
+ List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
+ for (Map.Entry<String, byte[]> entry : csar.entrySet()) {
+ if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
+ if (!isGlobalSubstitute(entry.getKey())) {
+ String yamlFileContents = new String(entry.getValue());
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
+ Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
+ if (substitutionMappingsEither.isLeft()) {
+ Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
+ NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
+ nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
+ nodeTypeInfo.setTemplateFileName(entry.getKey());
+ nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
+ nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
+ }
+ }
+ } else {
+ globalSubstitutes.add(entry);
+ }
+ }
+ }
+ if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
+ for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
+ String yamlFileContents = new String(entry.getValue());
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
+ Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+ if (nodeTypesEither.isLeft()) {
+ Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
+ for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
+ Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
+ if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
+ List<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ nodeTypeInfo.setDerivedFrom(derivedFrom);
+ }
+ }
+ }
+ }
+ }
+ }
+ markNestedVfc(yamlFileContent, nodeTypesInfo);
+ return nodeTypesInfo;
+ }
+
+ private void markNestedVfc(String yamlFileContent, Map<String, NodeTypeInfo> nodeTypesInfo) {
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContent);
+ Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
+ if (nodeTemplatesEither.isLeft()) {
+ Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
+ for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
+ Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
+ if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (nodeTypesInfo.containsKey(type)) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
+ nodeTypeInfo.setNested(true);
+ }
+ }
+ }
+ }
+ }
+
+ private boolean isGlobalSubstitute(String fileName) {
+ return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
+ }
+
private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
if (csar.isRight()) {
StorageOperationStatus value = csar.right().value();
if (validateRes.isRight()) {
return Either.right(validateRes.right().value());
}
- // VF "derivedFrom" should be null (or ignored)
- if (!resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ // VF / PNF "derivedFrom" should be null (or ignored)
+ if (ToscaUtils.isAtomicType(resource)) {
Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
if (validateDerivedFromNotEmpty.isRight()) {
return Either.right(validateDerivedFromNotEmpty.right().value());
return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction);
}
-
- public Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, User user, String topologyTemplateYaml, String yamlName, Map<String, byte[]> csar, String csarUUID) {
+//resource, yamlFileContents, yamlFileName, nodeTypesInfo,importCsarInfo, nodeTypesArtifactsToCreate, true, false, null
+ private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeTypeName) {
List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
log.trace("************* createResourceFromYaml before parse yaml ");
- Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, user);
+ Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, importCsarInfo.getModifier(), importCsarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeTypeName);
if (parseResourceInfoFromYamlEither.isRight()) {
ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
log.trace("************* createResourceFromYaml after parse yaml ");
ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
log.trace("************* createResourceFromYaml before create ");
- Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, user, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, csarUUID, csar, createdArtifacts, topologyTemplateYaml);
+ Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
+ AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
+ nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeTypeName);
log.trace("************* createResourceFromYaml after create ");
if (createdResourceResponse.isRight()) {
ResponseFormat responseFormat = createdResourceResponse.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
}
- 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);
+ @SuppressWarnings("unchecked")
+ public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, Map<String, Object> mappedToscaTemplate, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo) {
Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
if (tosca_version.isRight()) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
return Either.right(responseFormat);
}
-
Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
-
Map<String, Resource> nodeTypesResources = new HashMap<>();
Either<Map<String, Resource>, ResponseFormat> result = Either.left(nodeTypesResources);
-
Map<String, Object> mapToConvert = new HashMap<String, Object>();
mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
-
+ Resource vfcCreated = null;
if (eitherNodeTypes.isLeft()) {
-
Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
-
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, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
- log.trace("************* finished to create node {}", nodeType.getKey());
- if (resourceCreated.isRight()) {
- return Either.right(resourceCreated.right().value());
- }
- Resource vfcCreated = resourceCreated.left().value().getLeft();
- nodeTypesResources.put(nodeType.getKey(), vfcCreated);
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
+ Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo, nodeType.getKey(), nodeTypesResources);
+ log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
+ if (handleNeatedVfcYaml.isRight()) {
+ return Either.right(handleNeatedVfcYaml.right().value());
+ }
+ vfcCreated = handleNeatedVfcYaml.left().value();
+ } else if(importCsarInfo.getCreatedNodesToscaResourceNames()!= null && !importCsarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
+ log.trace("************* Going to create node {}", nodeType.getKey());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, importCsarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true);
+ log.debug("************* Finished to create node {}", nodeType.getKey());
+
+ if (resourceCreated.isRight()) {
+ return Either.right(resourceCreated.right().value());
+ }
+ vfcCreated = resourceCreated.left().value().getLeft();
+ importCsarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
+ }
+ if (vfcCreated != null) {
+ nodeTypesResources.put(nodeType.getKey(), vfcCreated);
+ }
mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
+ }
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo,
+ String nodeType, Map<String, Resource> createdResourcesFromdNodeTypeMap) {
+
+ Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
+ String serviceTemplateFileFullName = nodeTypesInfo.get(nodeType).getTemplateFileName();
+ String serviceTemplateFileContent = new String(importCsarInfo.getCsar().get(serviceTemplateFileFullName));
+ Map<String, Object> nestedVfcJsonMap = nodeTypesInfo.get(nodeType).getMappedToscaTemplate();
+
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMapEither = createResourcesFromYamlNodeTypesList(serviceTemplateFileFullName, resource, serviceTemplateFileContent,
+ nestedVfcJsonMap, false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
+ log.debug("************* Finished to create all nodes from yaml {}", serviceTemplateFileFullName);
+ if (createdResourcesFromdNodeTypeMapEither.isRight()) {
+ log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMapEither.right().value());
+ return Either.right(createdResourcesFromdNodeTypeMapEither.right().value());
+ }
+ createdResourcesFromdNodeTypeMap.putAll(createdResourcesFromdNodeTypeMapEither.left().value());
+ if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
+ Resource complexVfc = new Resource();
+ fillComplexVfcMetadata(resource, importCsarInfo, complexVfc, nodeType, nodeTypesInfo, false);
+ if(!importCsarInfo.getCvfcToCreateQueue().contains(nodeType)){
+ importCsarInfo.getCvfcToCreateQueue().add(nodeType);
+ } else {
+ log.debug("CFVC LOOP DETECTED, VSP {}, CVFC {}", importCsarInfo.getVfResourceName(), complexVfc.getName());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, importCsarInfo.getVfResourceName(), complexVfc.getName()));
+ }
+ Either<Resource, ResponseFormat> validationRes = validateResourceBeforeCreate(complexVfc, importCsarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true);
+ if(validationRes.isRight()){
+ log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
+ return validationRes;
+ }
+ Map<String, NodeTypeInfo> newNodeTypesInfo = nodeTypesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
+ markNestedVfc(serviceTemplateFileContent, newNodeTypesInfo);
+ handleNestedVfcRes = createResourceFromYaml(complexVfc, serviceTemplateFileContent, serviceTemplateFileFullName,
+ newNodeTypesInfo, importCsarInfo, nodeTypesArtifactsToHandle, false, true, nodeType);
+ if (handleNestedVfcRes.isRight()) {
+ log.debug("Couldn't create resource from YAML");
+ return Either.right(handleNestedVfcRes.right().value());
}
+ importCsarInfo.getCreatedNodesToscaResourceNames().put(nodeType, handleNestedVfcRes.left().value().getToscaResourceName());
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ log.debug("Going to certify cvfc {}. ", handleNestedVfcRes.left().value().getName());
+ Either<Resource, ResponseFormat> certRes = propagateStateToCertified(importCsarInfo.getModifier(), handleNestedVfcRes.left().value(), lifecycleChangeInfo, true, false, true);
+ if (certRes.isRight()) {
+ log.debug("Couldn't certify resource {}. ", handleNestedVfcRes.left().value());
+ return certRes;
+ }
+ createdResourcesFromdNodeTypeMap.put(nodeType, certRes.left().value());
+ importCsarInfo.getCvfcToCreateQueue().remove();
}
- return result;
+ return handleNestedVfcRes;
}
private String getNodeTypeActualName(String fullName) {
}
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) {
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
if (resourceMetaData.isRight()) {
return Either.right(resourceMetaData.right().value());
}
+ String csarVfName = resourceVf.getSystemName();
+ String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarVfName);
+
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed);
+ }
+ private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, String csarVfName) {
// We need to create a Yaml from each node_types in order to create
// resource from each node type using import normative flow.
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
- Map<String, Object> singleVfc = new HashMap<>();
+ Map<String, Object> node = new HashMap<>();
+ node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue());
+ mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
+
+ return yaml.dumpAsMap(mapToConvert);
+ }
- String actualName = this.getNodeTypeActualName(nodeNameValue.getKey());
+ private String buildNestedToscaResourceName(String nodeResourceType, String csarVfName, String originToscaResourceName) {
+ String actualName = getNodeTypeActualName(originToscaResourceName);
if (!actualName.startsWith(Constants.ABSTRACT)) {
actualName = "." + Constants.ABSTRACT + actualName;
}
-
- // Setting tosca name
- String toscaResourceName = ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceMetaData.left().value().getResourceType().toLowerCase() + '.' + resourceVf.getSystemName() + actualName;
- singleVfc.put(toscaResourceName, nodeNameValue.getValue());
- mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), singleVfc);
-
- String singleVfcYaml = yaml.dumpAsMap(mapToConvert);
-
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + nodeResourceType.toLowerCase() + '.' + ValidationUtils.convertToSystemName(csarVfName) + actualName;
}
public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
}
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) {
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
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, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed);
}
private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) {
return Either.left(resourceMetaData);
}
- private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, User user, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, String csarUUID,
- Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml) {
+ private void fillComplexVfcMetadata(Resource resourceVf, ImportCsarInfo importCsarInfo, Resource cvfc, String nodeTypeName, Map<String, NodeTypeInfo> nodeTypesInfo, boolean shouldBeCertified) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeTypeName);
+ cvfc.setName(buildCvfcName(importCsarInfo.getVfResourceName(), nodeTypeName));
+ cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
+ cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
+ cvfc.setResourceType(ResourceTypeEnum.CVFC);
+ cvfc.setAbstract(true);
+ cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
+ cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
+ cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+ cvfc.setContactId(importCsarInfo.getModifier().getUserId());
+ cvfc.setCreatorUserId(importCsarInfo.getModifier().getUserId());
+ cvfc.setVendorName(resourceVf.getVendorName());
+ cvfc.setVendorRelease(resourceVf.getVendorRelease());
+ cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
+ cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), importCsarInfo.getVfResourceName(), nodeTypeName));
+ cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+
+ List<String> tags = new ArrayList<>();
+ tags.add(cvfc.getName());
+ cvfc.setTags(tags);
+
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+ SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+ category.addSubCategory(subCategory);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ cvfc.setCategories(categories);
+
+ 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;
+ }
+ cvfc.setVersion(version);
+ cvfc.setLifecycleState(state);
+ cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+ }
+
+ private String buildCvfcName(String resourceVfName, String nodeTypeName) {
+ String nameWithouNamespacePrefix = nodeTypeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ return resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
+ }
+
+ private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
+ List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
+ ImportCsarInfo importCsarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeTypeName) {
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();
- return Either.right(responseFormat);
- }
- log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ return Either.right(responseFormat);
+ }
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ }
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
result = false;
return genericResourceEither;
}
- Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, isNormative, inTransaction);
+ Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, importCsarInfo.getModifier(), isNormative, inTransaction);
log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, inTransaction);
+ Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, importCsarInfo.getModifier(), inputs, inTransaction);
if (createInputsOnResource.isRight()) {
result = false;
return createInputsOnResource;
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, nodeTypesNewCreatedArtifacts, createdVfcs);
+
+ createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
+ nodeTypesNewCreatedArtifacts, createdVfcs, nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
} else {
groups = parsedToscaYamlInfo.getGroups();
}
- Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, user, groups);
+ Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, importCsarInfo.getModifier(), groups);
if (createGroupsOnResource.isRight()) {
result = false;
return createGroupsOnResource;
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, 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();
+ if(resource.getResourceType() == ResourceTypeEnum.CVFC){
+ if(nodeTypesArtifactsToCreate.containsKey(nodeTypeName) && nodeTypesArtifactsToCreate.get(nodeTypeName) !=null && !nodeTypesArtifactsToCreate.get(nodeTypeName).isEmpty()){
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
+ handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeTypeName), nodeTypesNewCreatedArtifacts, importCsarInfo.getModifier(), true);
+ if(handleNodeTypeArtifactsRes.isRight()){
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
+ } else {
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, importCsarInfo, 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();
+ }
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", actionEnum, null);
ASDCKpiApi.countCreatedResourcesKPI();
return Either.left(resource);
} finally {
- if (!result) {
- log.warn("operation failed. do rollback");
- 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);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, resource.getName());
+ if (!inTransaction) {
+ if (!result) {
+ log.warn("operation failed. do rollback");
+ 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);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, resource.getName());
+ }
+ log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
}
- log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
- }
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ if (shouldLock) {
+ graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
}
-
- graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
-
}
-
}
private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
}
private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
- if (inputs != null && false == inputs.isEmpty()) {
+ List<InputDefinition> resourceProperties = resource.getInputs();
+ if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
- Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right().value());
+ Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
+ if (createInputs.isRight()) {
+ return Either.right(createInputs.right().value());
}
} else {
return Either.left(resource);
// 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)).
+ // 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)).
+ peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
// Collect results
- collect(Collectors.toList());
+ collect(Collectors.toList());
// Recursively call the method for all the filtered group members
for (String innerGroupName : currGroupFilteredMembers) {
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)).
+ // Filter In Only Group members
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
// Collect
- collect(Collectors.toSet());
+ 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, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs) {
+ private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
+ String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate) {
Either<Resource, ResponseFormat> result;
Either<Resource, ResponseFormat> createResourcesInstancesEither;
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource, uploadComponentInstanceInfoMap);
-
log.debug("************* Going to create all nodes {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts);
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
log.debug("************* Finished to create all nodes {}", yamlName);
if (createdResourcesFromdNodeTypeMap.isRight()) {
log.debug("failed to resources from node types status is {}", 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());
+ createResourcesInstancesEither = createResourceInstances(importCsarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
log.debug("************* Finished to create all resource instances {}", yamlName);
if (createResourcesInstancesEither.isRight()) {
}
resource = createResourcesInstancesEither.left().value();
log.debug("************* Going to create all relations {}", yamlName);
- createResourcesInstancesEither = createResourceInstancesRelations(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false);
+ createResourcesInstancesEither = createResourceInstancesRelations(importCsarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false);
log.debug("************* Finished to create all relations {}", yamlName);
}
log.debug("************* Going to create positions {}", yamlName);
- Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, user.getUserId());
+ Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, importCsarInfo.getModifier().getUserId());
log.debug("************* Finished to set positions {}", yamlName);
result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
return result;
}
- private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
+ private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, Resource resource) {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
- List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName(), uploadComponentInstanceInfoMap);
- 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);
- }
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+ for (Map.Entry<String, List<ArtifactDefinition>> currArts : extractedVfcsArtifacts.entrySet()) {
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> artifactsToCreate = new EnumMap<>(ArtifactOperationEnum.class);
+ artifactsToCreate.put(ArtifactOperationEnum.Create, currArts.getValue());
+ nodeTypesArtifactsToHandle.put(currArts.getKey(), artifactsToCreate);
}
return nodeTypesArtifactsToHandle;
}
}
- 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) {
+ @SuppressWarnings("unchecked")
+ private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo) {
Map<String, Resource> createdResourcesFromdNodeTypeMap = new HashMap<>();
Either<Map<String, Resource>, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap);
+ for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
+ if (nodeTypeEntry.getValue().isNested()) {
- 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, nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts);
- if (createdNodeTypesFromGlobalTypesTemplateEither.isRight()) {
- ResponseFormat responseFormat = createdNodeTypesFromGlobalTypesTemplateEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
+ Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo, nodeTypeEntry.getKey(), createdResourcesFromdNodeTypeMap);
+ log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
+ if (createResourceFromYaml.isRight()) {
+ return Either.right(createResourceFromYaml.right().value());
+ }
}
- createdResourcesFromdNodeTypeMap.putAll(createdNodeTypesFromGlobalTypesTemplateEither.left().value());
}
-
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
if (createdNodeTypeFromMainTemplateEither.isRight()) {
ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
return result;
}
- private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
- boolean inTransaction) {
+ private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, ImportCsarInfo importCsarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
+ boolean inTransaction) {
- if (csar != null) {
+ if (importCsarInfo.getCsar() != null) {
String vendorLicenseModelId = null;
String vfLicenseModelId = null;
}
// 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,
+ createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, 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,
+ createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, 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);
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(importCsarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
if (eitherCreateResult.isRight()) {
return Either.right(eitherCreateResult.right().value());
}
- Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csar, csarUUID, componentsUtils);
+ Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(importCsarInfo.getCsar(), importCsarInfo.getCsarUUID(), 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.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
- createArtifactsFromCsar = createResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+ createArtifactsFromCsar = createResourceArtifactsFromCsar(importCsarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
else
- createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+ createArtifactsFromCsar = updateResourceArtifactsFromCsar(importCsarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
if (createArtifactsFromCsar.isRight()) {
log.debug("Couldn't create artifacts from artifacts.meta");
return Either.right(createArtifactsFromCsar.right().value());
* 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,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, importCsarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
resource, null, null, shouldLock, inTransaction);
if (handleDelete.isRight()) {
log.debug("Couldn't delete artifact {}", artifactId);
return Either.left(resource);
}
- 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) {
+ private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, ImportCsarInfo importCsarInfo, 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(artifactPath)) {
- artifactFileBytes = csar.get(artifactPath);
+ if (importCsarInfo.getCsar().containsKey(artifactPath)) {
+ artifactFileBytes = importCsarInfo.getCsar().get(artifactPath);
}
Either<Boolean, ResponseFormat> result = Either.left(true);
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,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, importCsarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
null, shouldLock, inTransaction);
if (handleDelete.isRight()) {
result = Either.right(handleDelete.right().value());
}
if (artifactFileBytes != null) {
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);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), 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);
+ BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + importCsarInfo.getCsarUUID(), ErrorSeverity.WARNING);
return Either.right(eitherNonMetaArtifacts.right().value());
}
}
return Either.left(uploadArtifactToService.left().value());
}
- public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
- boolean shouldLock, boolean inTransaction) {
+ public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
+ boolean shouldLock, boolean inTransaction) {
- Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
+ Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, importCsarInfo.getModifier());
if (parseResourceInfoFromYamlEither.isRight()) {
ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
}
}
}
- return createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
+ return createResourceArtifacts(importCsarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
}
// find master in group
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);
+ Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, importCsarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
if (deletedArtifactsEither.isRight()) {
log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
////////////// dissociate, associate or create
////////////// artifacts////////////////////////////
- Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarUUID, csar, resource, user, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
- mergedgroup, deletedArtifacts);
+ Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(importCsarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
+ mergedgroup, deletedArtifacts);
if (assDissotiateEither.isRight()) {
log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
}
groups = resource.getGroups();
- List<GroupDefinition> groupToUpdate = new ArrayList<>();
+
// update vfModule names
Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
if (groups != null && !groups.isEmpty()) {
;
for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
- GroupDefinition group = null;
- Optional<GroupDefinition> opGr = groups.stream().filter(p -> p.getUniqueId().equals(updatedGroupDef.getUniqueId())).findAny();
- if (opGr.isPresent()) {
- group = opGr.get();
- groupToUpdate.add(group);
- }
- if (group != null) {
- Map<String, String> members = new HashMap<String, String>();
- Set<String> artifactsGroup = new HashSet<String>();
- artifactsGroup.addAll(group.getArtifacts());
- associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
- if (!members.isEmpty()) {
- group.setMembers(members);
- }
+ if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
+ updatedGroupDef.getMembers().clear();
}
+ Map<String, String> members = new HashMap<String, String>();
+ Set<String> artifactsGroup = new HashSet<String>();
+ artifactsGroup.addAll(updatedGroupDef.getArtifacts());
+ associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
+ if (!members.isEmpty()) {
+ updatedGroupDef.setMembers(members);
+
+ }
+
}
- /*
- * 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 (validateGroupNamesRes.isRight()) {
return Either.right(validateGroupNamesRes.right().value());
}
- Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
+ Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(importCsarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
}
private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
- Map<String, List<ArtifactDefinition>> groupToDelete) {
+ Map<String, List<ArtifactDefinition>> groupToDelete) {
List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
String resourceId = resource.getUniqueId();
if (!artifactsToDelete.isEmpty()) {
* deletedArtifacts.add(removeArifactFromGraph.left().value());
*/
- }
-
- else {
+ } 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.left(deletedArtifacts);
}
- private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
- boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
+ private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
+ boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
Either<Resource, ResponseFormat> resEither = Either.left(resource);
List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
-
List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
-
+
for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
String prevUUID = artifact.getKey().getArtifactUUID();
String prevId = artifact.getKey().getUniqueId();
- Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifact.getKey(), artifact.getValue(), updatedArtifacts,
+ Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(importCsarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
if (updateArtifactEither.isRight()) {
log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
return resEither;
}
ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
- if ( !prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId()) ){
+ if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
groupToUpdate.getArtifacts().remove(prevId);
groupToUpdate.getArtifactsUuid().remove(prevUUID);
groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
Set<String> arifactsUids = new HashSet<String>();
+ Set<String> arifactsUuids = new HashSet<String>();
for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
// to
// find
for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
arifactsUids.add(createdArtifact.getUniqueId());
+ arifactsUuids.add(createdArtifact.getUniqueId());
isCreate = false;
String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
if (!heatEnvId.isEmpty()) {
for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
arifactsUids.add(createdNewArtifact.getUniqueId());
+ arifactsUuids.add(createdNewArtifact.getUniqueId());
isCreate = false;
String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
if (!heatEnvId.isEmpty()) {
}
if (isCreate) {
- Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(importCsarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
if (createArtifactEither.isRight()) {
resEither = Either.right(createArtifactEither.right().value());
return resEither;
}
ArtifactDefinition createdArtifact = createArtifactEither.left().value();
arifactsUids.add(createdArtifact.getUniqueId());
+ arifactsUuids.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);
+ resource.getName(), importCsarInfo.getModifier(), resource, null);
if (createHeatEnvPlaceHolder.isRight()) {
return Either.right(createHeatEnvPlaceHolder.right().value());
}
if (arifactsUids.size() > 0) {
List<String> artifactsToAssociate = new ArrayList<String>();
artifactsToAssociate.addAll(arifactsUids);
- GroupDefinition assotiateGroup = new GroupDefinition();
- assotiateGroup.setUniqueId(associateEntry.getKey().getUniqueId());
- assotiateGroup.setArtifacts(artifactsToAssociate);
- associateArtifactGroup.add(assotiateGroup);
-
+ GroupDefinition assotiateGroup = associateEntry.getKey();
+ assotiateGroup.getArtifacts().addAll(arifactsUids);
+ assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
}
}
}
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, List<ArtifactDefinition> createdDeplymentArtifacts) {
+ 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();
for (ArtifactDefinition artToDelete : listToDelete) {
findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
}
- if(artifactsToDelete != null && !artifactsToDelete.isEmpty()){
+ if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
GroupDefinition group = groupListEntry.getKey();
- for(ArtifactDefinition artifactDefinition: artifactsToDelete){
+ for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
group.getArtifacts().remove(artifactDefinition.getUniqueId());
-
+
}
if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
-
+
}
}
-
+
}
-
+
for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
return mergedgroup;
}
- private Set<String> findArtifactsNotInGroupToDelete(List<GroupDefinition> groups, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) {
- Set<String> artifactNotInGroupSet = new HashSet<String>();
- for (ArtifactDefinition artifact : createdDeplymentArtifactsAfterDelete) {
- boolean needToDelete = true;
- if (artifact.getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL) || artifact.getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
- continue;
- if (groups != null) {
- for (GroupDefinition group : groups) {
- List<String> groupArtifactIds = group.getArtifacts();
- if (groupArtifactIds == null || groupArtifactIds.isEmpty()) {
- continue;
- }
- for (String groupArtifactid : groupArtifactIds) {
- if (groupArtifactid.equalsIgnoreCase(artifact.getUniqueId()))
- needToDelete = false;
-
- }
-
- }
- }
- if (needToDelete)
- artifactNotInGroupSet.add(artifact.getUniqueId());
- }
- return artifactNotInGroupSet;
- }
-
private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
- List<ArtifactDefinition> createdDeplymentArtifacts) {
+ List<ArtifactDefinition> createdDeplymentArtifacts) {
boolean isNeedToDeleteArtifact = true;
String artifactType = artifact.getArtifactType();
ArtifactDefinition generatedFromArt = null;
}
}
- public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
- boolean shouldLock, boolean inTransaction) {
+ public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
+ boolean shouldLock, boolean inTransaction) {
log.debug("parseResourceArtifactsInfoFromFile start");
- Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
+ Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, importCsarInfo.getModifier());
if (parseResourceInfoFromYamlEither.isRight()) {
ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
log.debug("parseResourceArtifactsInfoFromFile end");
log.debug("createResourceArtifacts start");
- Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
+ Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(importCsarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
if (respStatus.isRight()) {
return respStatus;
}
}
- private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList,
- List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
+ List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
List<GroupDefinition> createdGroups = resource.getGroups();
List<GroupDefinition> heatGroups = null;
Set<String> artifactsGroup = new HashSet<String>();
Set<String> artifactsUUIDGroup = new HashSet<String>();
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(importCsarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
prop.setName(Constants.IS_BASE);
prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
properties.add(prop);
-
+
List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
createdArtifacts.addAll(createdNewArtifacts);
createdArtifacts.addAll(artifactsFromResource);
}
resource = component.left().value();
- Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, needToAdd);
+ Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, importCsarInfo.getModifier(), 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, Set<String> artifactsUUIDGroup,
- ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, 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 = "";
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(importCsarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
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);
+ resource.getName(), importCsarInfo.getModifier(), resource, null);
if (createHeatEnvPlaceHolder.isRight()) {
return Either.right(createHeatEnvPlaceHolder.right().value());
}
List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
if (relatedArtifacts != null) {
for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(importCsarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
return resStatus;
}
- private Either<Resource, ResponseFormat> createResourceArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
- List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createResourceArtifacts(ImportCsarInfo importCsarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
+ List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
if (groupTemplateList != null) {
- resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
+ resStatus = createGroupDeploymentArtifactsFromCsar(importCsarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
}
- private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
- ArtifactOperationInfo artifactOperation) {
+ private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(ImportCsarInfo importCsarInfo, Resource resource, 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()
+ importCsarInfo.getCsar().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
// collect to List
.collect(Collectors.toList());
+ Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
+ if (responseFormatEither.isRight()) {
+ return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
+ }
+
+
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);
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, importCsarInfo.getModifier());
if (findVfCsarArtifactsToHandleRes.isRight()) {
resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
// 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(),
+ .map(e -> createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, 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()).
+ map(e -> e.right().value()).
// Check if an error occurred
- findAny();
+ findAny();
// Error found on artifact Creation
if (optionalCreateInDBError.isPresent()) {
resStatus = Either.right(optionalCreateInDBError.get());
return resStatus;
}
+ private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
+ Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
+ for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
+ if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
+ return Either.right(nonMetaArtifactInfo.getArtifactName());
+ }
+ }
+ return Either.left(true);
+ }
+
+
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
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) {
+ private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
+ int labelCounter, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
List<GroupDefinition> createdGroups = resource.getGroups();
List<GroupDefinition> heatGroups = null;
Set<String> artifactsUUIDGroup = new HashSet<String>();
log.debug("createDeploymentArtifactsFromCsar start");
- resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(importCsarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
log.debug("createDeploymentArtifactsFromCsar end");
if (resStatus.isRight())
return resStatus;
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), user, ComponentTypeEnum.RESOURCE, needToCreate);
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), importCsarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
}
}
- 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) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(ImportCsarInfo importCsarInfo, String artifactPath, Resource resource, 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 = "";
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(importCsarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
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);
+ resource.getName(), importCsarInfo.getModifier(), resource, null);
if (createHeatEnvPlaceHolder.isRight()) {
return Either.right(createHeatEnvPlaceHolder.right().value());
}
List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
if (relatedArtifacts != null) {
for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(importCsarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
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) {
+ private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(ImportCsarInfo importCsarInfo, Resource resource, 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);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), artifactPath + artifactFileName, 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),
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
shoudLock, inTransaction);
if (uploadArtifactToService.isRight())
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
if (currentInfo.getHeatParameters() != null) {
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, importCsarInfo, artifactTemplateInfo, currentInfo, false);
if (updateEnvEither.isRight()) {
log.debug("failed to update parameters to artifact {}", artifactFileName);
return Either.right(updateEnvEither.right().value());
}
- 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);
-
- }
-
- private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
+ private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
Either<ArtifactDefinition, ResponseFormat> resStatus = null;
String artifactFileName = artifactTemplateInfo.getFileName();
}
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), 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(), 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),
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
shouldLock, inTransaction);
if (uploadArtifactToService.isRight()) {
}
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, true);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, importCsarInfo, artifactTemplateInfo, currentInfo, true);
if (updateEnvEither.isRight()) {
log.debug("failed to update parameters to artifact {}", artifactFileName);
resStatus = Either.right(updateEnvEither.right().value());
}
- private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
+ private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, ImportCsarInfo importCsarInfo, 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, CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
componentsUtils);
if (artifactparamsStatus.isRight()) {
resStatus = Either.right(artifactparamsStatus.right().value());
}
private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
- List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
+ List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
Map<String, Object> json = new HashMap<String, Object>();
if (artifactId != null && !artifactId.isEmpty())
Map<String, Resource> originCompMap = new HashMap<>();
List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+
for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
ComponentInstance currentCompInstance = null;
} 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.getCapabilities() != null && !originResource.getCapabilities().isEmpty()) {
+ Map<String, List<CapabilityDefinition>> originCapabilities ;
+ if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate()) && resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ originCapabilities = new HashMap<>();
+ originResource.getCapabilities().entrySet().stream().forEach(e ->{
+ List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l)).collect(Collectors.toList());
+ originCapabilities.put(e.getKey(), list);
+ });
+ for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
+ capabilities.stream().filter(c -> uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate().containsKey(c.getName())).forEach(c -> c.setName(uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate().get(c.getName())));
+ }
+ }else{
+ originCapabilities = originResource.getCapabilities();
+ }
+ instCapabilties.put(currentCompInstance, originCapabilities);
+ }
+ if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) {
+ Map<String, List<RequirementDefinition>> originRequirements;
+ if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getRequirementsNamesToUpdate()) && resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ originRequirements = new HashMap<>();
+ originResource.getRequirements().entrySet().stream().forEach(e ->{
+ List<RequirementDefinition> list = e.getValue().stream().map(l -> new RequirementDefinition(l)).collect(Collectors.toList());
+ originRequirements.put(e.getKey(), list);
+ });
+ for (List<RequirementDefinition> requirements : originRequirements.values()) {
+ requirements.stream().filter(r -> uploadComponentInstanceInfo.getRequirementsNamesToUpdate().containsKey(r.getName())).forEach(r -> r.setName(uploadComponentInstanceInfo.getRequirementsNamesToUpdate().get(r.getName())));
+ }
+ }else{
+ originRequirements = originResource.getRequirements();
+ }
+ instRequirements.put(currentCompInstance, originRequirements);
+ }
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);
+ if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
+ if (addPropertiesValueToRiRes.getStatus() != 200) {
+ return Either.right(addPropertiesValueToRiRes);
+ }
+ } else {
+ // TO DO
+ ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
+ if (addInputValueToRiRes.getStatus() != 200) {
+ return Either.right(addInputValueToRiRes);
+ }
}
-
}
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
return Either.right(responseFormat);
}
-
+ if (instInputs != null && !instInputs.isEmpty()) {
+ Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ if (addInputToInst.isRight()) {
+ log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.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);
UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
- ComponentInstance currentCompInstance = null;
+ 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();
+
+ Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
+
+ if (regMap != null) {
+ 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();
+ 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("The component instance with name {} not found on 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);
+ } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
+ return responseFormat;
+ }
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
+ Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+ if (propMap != null && propMap.size() > 0) {
+ Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
+
+ int index = 0;
+ List<InputDefinition> listFromMap = originResource.getInputs();
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ log.debug("failed to find properties ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ return responseFormat;
+ }
+ for (InputDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
+ }
+ }
+ List<ComponentInstanceInput> 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;
+ }
+ InputDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceInput 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 ComponentInstanceInput(curPropertyDef, value, null);
- for (ComponentInstance compInstance : componentInstancesList) {
+ Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
+ if (validatevalueEiter.isRight()) {
+ return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
+ }
- if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
- currentCompInstance = compInstance;
- break;
- }
+ // 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);
+ }
- 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();
+ 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);
- 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;
+ 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 {} ", getInputIndex.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
+ }
}
+ property.setGetInputValues(getInputValues);
}
-
- 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;
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+ // add rest of properties
+ if (!currPropertiesMap.isEmpty()) {
+ for (InputDefinition value : currPropertiesMap.values()) {
+ instPropList.add(new ComponentInstanceInput(value));
}
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
- reqAndRelationshipPairList.add(reqAndRelationshipPair);
- regCapRelDef.setRelationships(reqAndRelationshipPairList);
- relations.add(regCapRelDef);
-
}
-
+ instInputs.put(currentCompInstance.getUniqueId(), instPropList);
}
- 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<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
if (propMap != null && propMap.size() > 0) {
return cap;
}
- private RequirementAndRelationshipPair getReqRelPair(CapabilityDefinition cap) {
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setCapabilityUid(cap.getUniqueId());
- relationPair.setCapability(cap.getName());
- relationPair.setCapabilityOwnerId(cap.getOwnerId());
- return relationPair;
- }
-
private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
CapabilityDefinition aviableCapForRel = null;
Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
}
@SuppressWarnings("unchecked")
- public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) {
+ public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeTypeName) {
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
+ Map<String, Object> mappedToscaTemplate;
+ if(nodeTypesInfo != null && nodeTypeName != null && nodeTypesInfo.containsKey(nodeTypeName)){
+ mappedToscaTemplate = nodeTypesInfo.get(nodeTypeName).getMappedToscaTemplate();
+ }
+ else {
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
+ }
Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
if (toscaElementEither.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
return Either.right(responseFormat);
}
- Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource);
+ Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
if (uploadResInstancesEither.isRight()) {
ResponseFormat responseFormat = uploadResInstancesEither.right().value();
return Either.right(responseFormat);
}
private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
- Map<String, Resource> nodeTypeNamespaceMap) {
+ Map<String, Resource> nodeTypeNamespaceMap) {
Either<Resource, ResponseFormat> eitherResource = null;
log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
return Either.right(responseFormat);
}
- ResourceTypeEnum resourceTypeEnum = refResource.getResourceType();
- if (resourceTypeEnum == ResourceTypeEnum.VF) {
- log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", resourceTypeEnum);
+
+ if (!ToscaUtils.isAtomicType(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
return Either.right(responseFormat);
}
return Either.left(refResource);
}
- private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
+ private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
+ Map<String, Object> substitutionMappings = null;
Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
+ Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
+ if (eitherSubstitutionMappings.isLeft()) {
+ substitutionMappings = eitherSubstitutionMappings.left().value();
+ }
if (eitherNodesTemlates.isLeft()) {
Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
while (nodesNameValue.hasNext()) {
Entry<String, Object> nodeNameValue = nodesNameValue.next();
- Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue.getValue());
+ Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
if (eitherNode.isRight()) {
log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
return Either.right(eitherNode.right().value());
} else {
UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
- uploadComponentInstanceInfo.setName(nodeNameValue.getKey());
moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
}
return result;
}
- private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Object nodeTemplateJson) {
+ @SuppressWarnings("unchecked")
+ private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
-
+ nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
try {
- if (nodeTemplateJson instanceof String) {
- String nodeTemplateJsonString = (String) nodeTemplateJson;
+ if (nodeTemplateJsonEntry.getValue() instanceof String) {
+ String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
nodeTemplateInfo.setType(nodeTemplateJsonString);
- } else if (nodeTemplateJson instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJson;
+ } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
+ Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
// Type
if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- nodeTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
+ String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
+ toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
+ }
+ nodeTemplateInfo.setType(toscaResourceType);
}
if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
nodeTemplateInfo.setProperties(regResponse.left().value());
}
}
+ if (substitutionMappings != null) {
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
+ Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
+ if (getCapNamesToUpdateRes.isRight())
+ return Either.right(getCapNamesToUpdateRes.right().value());
+ if (getCapNamesToUpdateRes.left().value().size() > 0) {
+ nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
+ }
+ }
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
+ Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
+ if (getReqNamesToUpdateRes.isRight())
+ return Either.right(getReqNamesToUpdateRes.right().value());
+ if (getReqNamesToUpdateRes.left().value().size() > 0) {
+ nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
+ }
+ }
+ }
} else {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability");
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
log.debug("error when creating capability, message:{}", e.getMessage(), e);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
return result;
}
+ private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
+ Either<Map<String, String>, ResponseFormat> response;
+ try {
+ Map<String, String> namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
+ response = Either.left(namesToUpdate);
+ } catch (Exception e) {
+ log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return response;
+ }
+
private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
Object propValue = jsonPropObj.getValue();
if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
log.debug("valueContainsToken value is {}", propValue);
boolean result = false;
if (propValue != null) {
- log.debug("valueContainspattern value is {}", propValue.getClass());
+ log.trace("valueContainspattern value is {}", propValue.getClass());
Matcher matcher = pattern.matcher(propValue.toString());
result = matcher.find();
}
return result;
}
- public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
+
Either<Resource, ResponseFormat> result = null;
-
- // resource updated with checkout. certify the resource
- if (resource.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
- result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
- return result;
- }
try {
- result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
- if (result.isLeft()) {
+ if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed){
+ result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ if(result.isRight()){
+ return result;
+ }
resource = result.left().value();
- result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
}
- if (result.isLeft()) {
- resource = result.left().value();
- result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
+ result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
+ return result;
}
- return result;
+ return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
+ } catch (Exception e) {
+ log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
if (inTransaction == false) {
log.debug("operation failed. do rollback");
}
}
+ private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
+ if (result.isLeft()) {
+ result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
+ }
+ if (result.isLeft()) {
+ result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ }
+
/*
* /**
*
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);
// 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);
return result;
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
log.debug("operation failed. do rollback");
titanDao.rollback();
newResource.setVendorRelease(oldResource.getVendorRelease());
}
+ if (newResource.getResourceVendorModelNumber() == null) {
+ newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
+ }
+
if (newResource.getContactId() == null) {
newResource.setContactId(oldResource.getContactId());
}
resource.setCreatorUserId(user.getUserId());
resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
resource.setContactId(resource.getContactId().toLowerCase());
- if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
- resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VF.name(), resource.getSystemName()));
+ if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name(), resource.getSystemName()));
}
// Generate invariant UUID - must be here and not in operation since it
// should stay constant during clone
+ // TODO
String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
resource.setInvariantUUID(invariantUUID);
Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInterfaceMissingError, "Create Resource - validateLifecycleTypesCreate", intType);
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateLifecycleTypesCreate");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
}
if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
log.debug("validate capability Types Exist - requirements section");
for (String type : resource.getRequirements().keySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type) , actionEnum, eitherResult, type, inTransaction);
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
return eitherResult;
}
- //@param typeObject- the object to which the validation is done
- private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects , AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
- boolean inTransaction) {
+ // @param typeObject- the object to which the validation is done
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
+ boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", type);
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, 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: {}", type, eitherCapTypeFound.right().value().name());
- ResponseFormat errorResponse =null;
- if (type!=null)
+ ResponseFormat errorResponse = null;
+ if (type != null)
errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
else
- errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects );
+ errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
eitherResult = Either.right(errorResponse);
componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
}
}
private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
- Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
+ 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);
Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
if (respStatus.isLeft()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
+ auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
ASDCKpiApi.countCreatedResourcesKPI();
} else
componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
}
}
+ private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
+ }
+
private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
// validate resource name uniqueness
log.debug("validate resource name");
resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resource.setVersion(INITIAL_VERSION);
resource.setHighestVersion(true);
- resource.setAbstract(false);
+ if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
+ resource.setAbstract(false);
}
Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
resource.setDeploymentArtifacts(artifactMap);
}
+ @SuppressWarnings("unchecked")
private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
if (artifactMap == null) {
}
String resourceUniqueId = resource.getUniqueId();
List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+ List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
List<CategoryDefinition> categories = resource.getCategories();
boolean isCreateArtifact = true;
}
}
+ }
+ if (isCreateArtifact && exludeResourceType != null) {
+ String resourceType = resource.getResourceType().name();
+ for (String type : exludeResourceType) {
+ if (type.equalsIgnoreCase(resourceType)) {
+ isCreateArtifact = false;
+ break;
+ }
+ }
+
}
if (informationalResourceArtifacts != null && isCreateArtifact) {
/**
* updateResourceMetadata
*
- * @param user
- * - modifier data (userId)
- * @param inTransaction
- * TODO
- * @param resourceIdToUpdate
- * - the resource identifier
+ * @param user - modifier data (userId)
+ * @param inTransaction TODO
+ * @param resourceIdToUpdate - the resource identifier
* @param newResource
- *
* @return Either<Resource, responseFormat>
*/
public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
// lock resource
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
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);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
// list
// This code is not called from import resources, because of root
// VF "derivedFrom" should be null (or ignored)
- if (!currentResource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ if (ToscaUtils.isAtomicType(currentResource)) {
Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
if (derivedFromNotEmptyEither.isRight()) {
log.debug("for updated resource {}, derived from field is empty", newResource.getName());
}
}
+ private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
+ if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
+ if (log.isInfoEnabled())
+ log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
+ return Either.right(false);
+ }
+ List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
+ for ( GroupDefinition group : list) {
+ if ( group!=null && group.isSamePrefix( replacePattern ) ){
+ String prefix = group.getName().substring( 0, replacePattern.length() );
+ String newGroupName = group.getName().replaceFirst(prefix , with);
+ group.setName(newGroupName);
+ //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
+ //group.setUniqueId(newUid);
+ }
+ }
+ return Either.left(list);
+ }
+
+ private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
+ if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional
+ String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ return !oldName.equals(futureName);
+ }
+ return false;
+ }
+
private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
+ //region -> Update groups name for newResource
+ if ( isComponentNameChanged( currentResource , newResource) ){
+ String replacePattern = Optional.ofNullable( //get currentResource name from metadata
+ Optional.ofNullable( Optional.ofNullable( currentResource )
+ .orElse(null).getComponentMetadataDefinition() )
+ .orElse(null).getMetadataDataDefinition() )
+ .orElse(null).getName();
+ String with = Optional.ofNullable( //get newResource name from metadata
+ Optional.ofNullable( Optional.ofNullable( newResource )
+ .orElse(null).getComponentMetadataDefinition() )
+ .orElse(null).getMetadataDataDefinition() )
+ .orElse(null).getName();
+ if ( with != null && replacePattern != null ){
+ Either result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups());
+ if (result.isLeft())
+ newResource.setGroups( (List<GroupDefinition>)result.left().value() );
+ }
+ }
+ //endregion
Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
if (validateResourceFields.isRight()) {
}
log.debug("send resource {} to dao for update", newResource.getUniqueId());
+ if (newResource!=null && newResource.getGroups()!=null){
+ for ( GroupDefinition group : newResource.getGroups() ){
+ if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
+ groupBusinessLogic.validateAndUpdateGroupMetadata(
+ newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
+ user,
+ ComponentTypeEnum.RESOURCE_INSTANCE,
+ group,
+ true ,
+ false) ;
+ }
+ }
Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
if (dataModelResponse.isRight()) {
/**
* validateResourceFieldsBeforeCreate
*
- * @param user
- * - modifier data (userId)
- * @param dataModel
- * - IResourceOperation for resource crud
- * @param resource
- * - Resource object to validate
+ * @param user - modifier data (userId)
+ * @param dataModel - IResourceOperation for resource crud
+ * @param resource - Resource object to validate
* @return Either<Boolean, ErrorResponse>
*/
private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
return eitherValidation;
}
- // validate vendor name & release
+ // validate vendor name & release & model number
log.debug("validate vendor name");
eitherValidation = validateVendorName(user, resource, actionEnum);
if (eitherValidation.isRight()) {
return eitherValidation;
}
+ log.debug("validate resource vendor model number");
+ eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
// validate contact info
/*
* log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
// validate template (derived from)
log.debug("validate derived from");
- if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
resource.setDerivedFrom(null);
}
eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
/**
* validateResourceFieldsBeforeUpdate
*
- * @param currentResource
- * - Resource object to validate
+ * @param currentResource - Resource object to validate
* @return Either<Boolean, ErrorResponse>
*/
private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
return eitherValidation;
}
+ log.debug("validate resource vendor model number before update");
+ eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+
log.debug("validate vendor release before update");
eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
if (eitherValidation.isRight()) {
return Either.left(true);
}
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
+ String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
+ String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
+ if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
+ Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
+ if (validateResourceVendorModelNumber.isRight()) {
+ ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
if (validateCategoryName.isRight()) {
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
return Either.right(responseFormat);
- }
-
- else if (!dataModelResponse.left().value()) {
+ } 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);
return Either.right(responseFormat);
}
if (subcategories.size() > 1) {
- log.debug("Must be only one sub ategory for resource");
+ log.debug("Must be only one sub category for resource");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
return Either.right(responseFormat);
}
}
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
+ String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
+ Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
+ if (validateResourceVendorModelNumber.isRight()) {
+ ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ }
+ return validateResourceVendorModelNumber;
+
+ }
+
+
private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
if (vendorName != null) {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
}
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
+ if (resourceVendorModelNumber.equals("")) {
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
+ log.info("resource vendor model number exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+ // resource vendor model number is currently validated as vendor name
+ if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
+ log.info("resource vendor model number is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+
/*
* 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,
if (inputs.isRight()) {
String message = "Failed when creating inputs: for resource:" + resource.getName();
BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
- Map<String, InputDefinition> resultMap = new HashMap();
+ Map<String, InputDefinition> resultMap = new HashMap<>();
return Either.left(resultMap);
}
}
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
- Resource resource, User user) {
+ Resource resource, User user) {
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
}
return toscaResourceName;
}
+
+ private String buildNodeToscaResourceName(String vfResourceName, String nodeTypeFullName) {
+ String toscaResourceName;
+ String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
+
+ if (actualName.startsWith(Constants.ABSTRACT)) {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + actualName;
+ } else {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceType.toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + actualName;
+ }
+ return toscaResourceName;
+ }
public ICacheMangerOperation getCacheManagerOperation() {
return 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()) {
- if(resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
log.debug("Failed to found resource with id {} ", resourceId);
Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
}
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);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false);
}
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
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);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false);
}
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, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
Resource resource = new Resource();
ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
String latestCertifiedResourceId = null;
try {
- boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty() ? true : false;
+ boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
setConstantMetaData(resource, shouldBeCertified);
setMetaDataFromJson(resourceMetaData, resource);
}
}
latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
- changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock);
+ changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
if (changeStateResponse.isRight()) {
response = Either.right(changeStateResponse.right().value());
} else {
}
- private Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) {
+ Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) {
@SuppressWarnings("unchecked")
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml);
Map<String, Object> toscaJson = toscaJsonAll;
// Checks if exist and builds the node_types map
- if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName())) {
+ if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) {
toscaJson = new HashMap<String, Object>();
toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
}
capabilityDefinition.setProperties(capabilityProperties);
}
}
- } else {
+ } else if (!(capabilityJson instanceof List)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
return componentsFieldsValidation;
}
- // validate service name uniqueness
log.debug("validate service name uniqueness");
Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
if (serviceNameUniquenessValidation.isRight()) {
return serviceNameUniquenessValidation;
}
- // validate category
log.debug("validate category");
Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
if (categoryValidation.isRight()) {
}
// validate project name (ProjectCode) - mandatory in service
-
log.debug("validate projectName");
Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
if (projectCodeValidation.isRight()) {
return projectCodeValidation;
}
+
+ log.debug("validate service type");
+ Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum);
+ if (serviceTypeValidation.isRight()) {
+ return serviceTypeValidation;
+ }
+
+ log.debug("validate service role");
+ Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum);
+ if (serviceRoleValidation.isRight()) {
+ return serviceRoleValidation;
+ }
return Either.left(true);
if (!uuidCurrent.equals(uuidUpdated)) {
log.info("update srvice: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
}
+
+ response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
String currentInvariantUuid = currentService.getInvariantUUID();
String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) {
String serviceNameUpdated = serviceUpdate.getName();
String serviceNameCurrent = currentService.getName();
if (!serviceNameCurrent.equals(serviceNameUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, audatingAction);
+ Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction);
if (validatServiceNameResponse.isRight()) {
ResponseFormat errorRespons = validatServiceNameResponse.right().value();
return Either.right(errorRespons);
}
- Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, audatingAction);
+ Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction);
if (serviceNameUniquenessValidation.isRight()) {
return serviceNameUniquenessValidation;
}
}
return Either.left(true);
}
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedServiceType = updatedService.getServiceType();
+ String currentServiceType = currentService.getServiceType();
+ if (!currentServiceType.equals(updatedServiceType)) {
+ Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction);
+ if (validateServiceType.isRight()) {
+ ResponseFormat errorResponse = validateServiceType.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setServiceType(updatedServiceType);
+ }
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ String serviceType = ((Service)component).getServiceType();
+ if (serviceType != null){
+ serviceType = cleanUpText(serviceType);
+ Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType);
+ if (validateServiceType.isRight()) {
+ ResponseFormat responseFormat = validateServiceType.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ } else {
+ return Either.left(false);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) {
+ if (serviceType.equals("")){
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateServiceTypeLength(serviceType)) {
+ log.info("service type exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(serviceType)) {
+ log.info("service type is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedServiceRole = updatedService.getServiceRole();
+ String currentServiceRole = currentService.getServiceRole();
+ if (!currentServiceRole.equals(updatedServiceRole)) {
+ Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction);
+ if (validateServiceRole.isRight()) {
+ ResponseFormat errorResponse = validateServiceRole.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setServiceRole(updatedServiceRole);
+ }
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ String serviceRole = ((Service)component).getServiceRole();
+ if (serviceRole != null){
+ serviceRole = cleanUpText(serviceRole);
+
+ Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole);
+ if (validateServiceRole.isRight()) {
+ ResponseFormat responseFormat = validateServiceRole.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ } else {
+ return Either.left(false);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) {
+ if (serviceRole.equals("")){
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateServiceRoleLength(serviceRole)) {
+ log.info("service role exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(serviceRole)) {
+ log.info("service role is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
// DE194021
ServletContext servletContext = request.getSession().getServletContext();
- boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE
+ boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE
if (!isDistributionEngineUp) {
BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
log.debug("Distribution Engine is DOWN");
@Component("serviceComponentInstanceBusinessLogic")
public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
- @Override
- protected Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent) {
- return Either.left(true);
- }
@Override
protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
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.tosca.ToscaUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static Logger log = LoggerFactory.getLogger(VFComponentInstanceBusinessLogic.class.getName());
- @Override
- protected Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent) {
- Resource resource = (Resource) containerComponent;
- ResourceTypeEnum resourceType = resource.getResourceType();
- if (ResourceTypeEnum.VF != resourceType) {
- log.debug("Cannot attach resource instances to container resource of type {}", resourceType);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, resourceType.getValue()));
- }
- return Either.left(true);
- }
-
@Override
protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
return NodeTypeEnum.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.datamodel.ToscaElementTypeEnum;
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.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.tosca.ToscaRepresentation;
+import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
ResponseFormat responseFormat;
Either<? extends Component, ResponseFormat> result = null;
try{
- if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
+ if (component.getToscaType().equals(ToscaElementTypeEnum.TopologyTemplate.getValue())) {
Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
if (statusCert.isRight()) {
// occurrences in the future
Map<String, List<String>> reqName2Ids = new HashMap<>();
Map<String, List<String>> capName2Ids = new HashMap<>();
- parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids);
+// Either<Boolean, ResponseFormat> parseRelationsForReqCapVerificationRes = parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids);
+// if(parseRelationsForReqCapVerificationRes.isRight()){
+// return parseRelationsForReqCapVerificationRes;
+// }
Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert();
Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert();
for (ComponentInstance compInst : componentInstances) {
import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
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.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.ICacheMangerOperation;
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.CapabilityOperation;
-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;
String resourceCurrVersion = component.getVersion();
LifecycleStateEnum resourceCurrState = component.getLifecycleState();
- log.info("lock component {}", componentId);
// lock resource
if (inTransaction == false && needLock) {
+ log.info("lock component {}", componentId);
Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component);
if (eitherLockResource.isRight()) {
errorResponse = eitherLockResource.right().value();
log.error("lock component {} failed", componentId);
return Either.right(errorResponse);
}
+ log.info("after lock component {}", componentId);
}
- log.info("after lock component {}", componentId);
try {
Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum);
if (commentValidationResult.isRight()) {
return Either.left(latestComponent);
}
+ public Either<Resource, ResponseFormat> forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ Either<Resource, ResponseFormat> result = null;
+ Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null;
+ if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){
+ log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction().name());
+ result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+ // lock resource
+ if(result == null && !inTransaction && needLock){
+ log.info("lock component {}", resource.getUniqueId());
+ Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(resource.getComponentType(), resource);
+ if (eitherLockResource.isRight()) {
+ log.error("lock component {} failed", resource.getUniqueId());
+ result = Either.right(eitherLockResource.right().value());
+ }
+ log.info("after lock component {}", resource.getUniqueId());
+ }
+ try{
+ if(result == null){
+ certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId());
+ if (certifyResourceRes.isRight()) {
+ StorageOperationStatus status = certifyResourceRes.right().value();
+ log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status);
+ result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource));
+ }
+ }
+ if(result == null){
+ result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value()));
+ }
+ } finally {
+ log.info("unlock component {}", resource.getUniqueId());
+ if (!inTransaction) {
+ if(result.isLeft()){
+ titanDao.commit();
+ } else{
+ titanDao.rollback();
+ }
+ if(needLock){
+ NodeTypeEnum nodeType = resource.getComponentType().getNodeType();
+ log.info("During change state, another component {} has been created/updated", resource.getUniqueId());
+ graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType);
+ }
+ }
+ }
+ return result;
+ }
+
}
Response response = null;
ResponseFormat responseFormat = null;
String query = request.getQueryString();
- String requestURI = request.getRequestURI();
+ String requestURI = request.getRequestURI().endsWith("/")?
+ removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
log.debug("Start handle request of {}", url);
-
+
AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
}
if (resourceType != null) {
ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
- if( resourceTypeEnum == null ){
+ 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 response;
}
}
+
+
+ private String removeDuplicateSlashSeparator(String requestUri) {
+ return requestUri.substring(0, requestUri.length()-1);
+ }
+
+
}
@ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
@ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
@ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
@ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
@ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
@ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
@ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
@ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
@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)
+ @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements 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) {
package org.openecomp.sdc.be.servlets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.inject.Singleton;
-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.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
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.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.info.ArtifactTypesInfo;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Category;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.PropertyScope;
-import org.openecomp.sdc.be.model.Tag;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
+import javax.inject.Singleton;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.*;
@Path("/v1/")
@ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"),
@ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) {
Response res = null;
try {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("Start handle request of {}", url);
- Either<Map<String, List<? extends Component>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId);
+ Either<Map<String, List<? extends Component>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes);
if (catalogData.isRight()) {
log.debug("failed to get catalog data");
// Update GroupDefinition
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic
- .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true);
+ .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true);
if (actionResponse.isRight()) {
log.debug("failed to update GroupDefinition");
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
+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.api.Constants;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
"([\\w\\_\\-\\.\\s]+)(/)" +
// Artifact Type
"([\\w\\_\\-\\.\\s]+)(/)" +
- // Artifact File Name
- "([\\w\\_\\-\\.\\s]+)";
- public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
+ // Artifact Any File Name
+ ".+";
+ public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
+ public static final String SERVICE_TEMPLATE_PATH_PATTERN = Constants.SERVICE_TEMPLATES_CONTAINING_FOLDER +
+ // Service Template File Name
+ "([\\w\\_\\-\\.\\s]+)";
+
+ public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
public CsarUtils() {
if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
dependencies = dependenciesRes.left().value().getDependencies();
}
- //UID <cassandraId,filename,component>
- Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
+ //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) {
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();
- generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
- }
+ //fill innerComponentsCache
+ fileName = d.getLeft();
+ addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
+ addInnerComponentsToCache(innerComponentsCache, childComponent);
- //add inner components to CSAR
-
+ byte[] content = entryData.left().value();
+ generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
+ }
+
+ //add inner components to CSAR
for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
}
- private void insertInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
Component childComponent) {
List<ComponentInstance> instances = childComponent.getComponentInstances();
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));
+ addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
}
//if not atomic - insert inner components as well
if(!ToscaUtils.isAtomicType(componentRI)) {
- insertInnerComponentsToCache(componentCache, componentRI);
+ addInnerComponentsToCache(componentCache, componentRI);
}
}
});
}
}
+
+ private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ String id, String fileName, Component component) {
+
+ ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
+ if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
+ componentCache.put(component.getInvariantUUID(),
+ new ImmutableTriple<String, String, Component>(id, fileName, component));
+
+ if(cachedComponent != null) {
+ //overwriting component with newer version
+ log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
+ }
+ }
+ }
private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
try {
eschema.setDescription(schema.getProperty().getDescription());
prop.setEntry_schema(eschema);
}
- log.debug("try to convert property {} from type {} with default value {}", property.getName(), property.getType(), property.getDefaultValue());
+ log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue());
prop.setDefaultp(convertToToscaObject(property.getType(), property.getName(), property.getDefaultValue(), innerType, dataTypes));
prop.setType(property.getType());
prop.setDescription(property.getDescription());
}
public Object convertToToscaObject(String propertyType, String propertyName, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- log.debug("try to convert propertyType {} , value {}, innerType {}", propertyType, value, innerType);
+ log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
if (value == null) {
value = getDataTypeDefaultValue(propertyName, dataTypes.get(propertyType));
if(StringUtils.isEmpty(value)){
return null;
}
- }
-
- ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
- ToscaValueConverter innerConverter = null;
- Boolean isScalar = true;
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- if (type == null) {
- log.debug("isn't prederfined type, get from all data types");
- DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- if (innerType == null) {
- innerType = propertyType;
- }
-
- if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
- log.debug("This is scalar type. get suitable converter for type {}", type);
- innerConverter = type.getValueConverter();
- } else {
- isScalar = false;
- }
- } else {
- ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
- if (typeIfScalar == null) {
- isScalar = false;
- }
- innerConverter = type.getValueConverter();
- if (ToscaPropertyType.STRING.equals(type) && value.startsWith("/")) {
- return innerConverter.convertToToscaValue(value, innerType, dataTypes);
- }
}
- JsonElement jsonElement = null;
try {
+ ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
+ ToscaValueConverter innerConverter = null;
+ Boolean isScalar = true;
+
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ if (type == null) {
+ log.trace("isn't prederfined type, get from all data types");
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ if (innerType == null) {
+ innerType = propertyType;
+ }
+
+ if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
+ log.trace("This is scalar type. get suitable converter for type {}", type);
+ innerConverter = type.getValueConverter();
+ } else {
+ isScalar = false;
+ }
+ } else {
+ ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
+ if (typeIfScalar == null) {
+ isScalar = false;
+ }
+
+ innerConverter = type.getValueConverter();
+ if (ToscaPropertyType.STRING.equals(type) && value.startsWith("/")) {
+ return innerConverter.convertToToscaValue(value, innerType, dataTypes);
+ }
+ }
+ JsonElement jsonElement = null;
+
StringReader reader = new StringReader(value);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
}
if (jsonElement.isJsonPrimitive() && isScalar) {
- log.debug("It's well defined type. convert it");
+ log.trace("It's well defined type. convert it");
ToscaValueConverter converter = type.getValueConverter();
return converter.convertToToscaValue(value, innerType, dataTypes);
} else {
- log.debug("It's data type or inputs in primitive type. convert as map");
+ log.trace("It's data type or inputs in primitive type. convert as map");
Object convertedValue;
if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) {
convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
return convertedValue;
}
- } catch (JsonSyntaxException e) {
+ } catch (Exception e) {
log.debug("convertToToscaValue failed to parse json value :", e);
return null;
}
toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
toscaMetadata.setResourceVendor(resource.getVendorName());
toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
-
+ toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
break;
case SERVICE:
+ Service service = (Service) component;
toscaMetadata.setType(component.getComponentType().getValue());
+ toscaMetadata.setServiceType(service.getServiceType());
+ toscaMetadata.setServiceRole(service.getServiceRole());
if (!isInstance) {
// DE268546
toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
toscaMetadata = new VfModuleToscaMetadata();
Map<String, Object> properties = fillGroupProperties(props.get());
-
- properties.put(VF_MODULE_DESC_KEY, description.get());
+ if(!properties.containsKey(VF_MODULE_DESC_KEY) || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))){
+ properties.put(VF_MODULE_DESC_KEY, description.get());
+ }
toscaGroup.setProperties(properties);
}
toscaMetadata.setName(groupName.get());
private String subcategory;
private String resourceVendor;
private String resourceVendorRelease;
+ private String resourceVendorModelNumber;
+ private String serviceType;
+ private String serviceRole;
private Boolean serviceEcompNaming;
private Boolean ecompGeneratedNaming;
private String namingPolicy;
public void setResourceVendorRelease(String resourceVendorRelease) {
this.resourceVendorRelease = resourceVendorRelease;
}
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
public Boolean isEcompGeneratedNaming() {
return ecompGeneratedNaming;
package org.openecomp.sdc.common.transaction.mngr;
-import org.openecomp.sdc.common.transaction.api.RollbackHandler;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
-import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
-
import fj.P;
import fj.data.Either;
import fj.data.HashMap;
import fj.data.List;
+import org.openecomp.sdc.common.transaction.api.RollbackHandler;
+import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
+import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
+import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
+
public class RollbackManager {
private final HashMap<DBTypeEnum, RollbackHandler> rollbackHandlersMap;
private final Integer transactionId;
- private final String userId;
+ private final String userId;
private final String actionType;
RollbackManager(Integer transactionId, String userId, String actionType, Iterable<RollbackHandler> rollbackHandlers) {
// by convention left is failure; in SDC right is failure
return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap();
}
-
}
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
minToscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
uebHealthCheckReconnectIntervalInSeconds: 15
uebHealthCheckReadTimeout: 4
-
# Protocols
protocols:
- http
cassandraConfig:
cassandraHosts: ['localhost']
- localDataCenter:
+ localDataCenter: datacenter1
reconnectTimeout : 30000
authenticate: false
username: koko
- { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
#Application-specific settings of ES
elasticSearch:
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
host: localhost
port: 8080
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
switchoverDetector:
gBeFqdn: AIO-BE.ecomp.idns.cip.com
genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
+ CVFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
+ PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
code: 204,
message: "No Content"
}
-#--------POL4050-----------------------------
+#--------POL4050-----------------------------
NOT_ALLOWED: {
code: 405,
message: "Error: Method not allowed.",
messageId: "POL4050"
}
-#--------POL5000-----------------------------
+#--------POL5000-----------------------------
GENERAL_ERROR: {
code: 500,
message: "Error: Internal Server Error. Please try again later.",
messageId: "POL5000"
}
-#---------POL5001------------------------------
+#---------POL5001------------------------------
MISSING_X_ECOMP_INSTANCE_ID: {
code: 400 ,
message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.",
messageId: "POL5001"
}
-#---------POL5002------------------------------
+#---------POL5002------------------------------
AUTH_REQUIRED: {
code: 401 ,
message: "Error: Authentication is required to use the API.",
messageId: "POL5002"
}
-#---------POL5003------------------------------
+#---------POL5003------------------------------
AUTH_FAILED: {
code: 403 ,
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
-#---------POL5004------------------------------
+#---------POL5004------------------------------
MISSING_USER_ID: {
code: 400 ,
message: "Error: Missing 'USER_ID' HTTP header.",
messageId: "POL5004"
}
-#---------SVC4000-----------------------------
+#---------SVC4000-----------------------------
INVALID_CONTENT: {
code: 400,
message: "Error: Invalid content.",
messageId: "SVC4000"
}
-#---------SVC4002-----------------------------
+#---------SVC4002-----------------------------
MISSING_INFORMATION: {
code: 403,
message: "Error: Missing information.",
messageId: "SVC4002"
}
-#---------SVC4003------------------------------
-# %1 - Users's ID
+#---------SVC4003------------------------------
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
messageId: "SVC4003"
}
-#---------SVC4004-----------------------------
-# %1 - Users's email address
+#---------SVC4004-----------------------------
+# %1 - Users's email address
INVALID_EMAIL_ADDRESS: {
code: 400,
message: "Error: Invalid email address '%1'.",
messageId: "SVC4004"
}
-#---------SVC4005------------------------------
+#---------SVC4005------------------------------
# %1 - role
INVALID_ROLE: {
code: 400,
message: "Error: Invalid role '%1'.",
messageId: "SVC4005"
}
-#---------SVC4006------------------------------
-# %1 - Users's USER_ID
+#---------SVC4006------------------------------
+# %1 - Users's USER_ID
USER_ALREADY_EXIST: {
code: 409,
message: "Error: User with '%1' ID already exists.",
messageId: "SVC4006"
}
-#---------SVC4007------------------------------
+#---------SVC4007------------------------------
DELETE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator can only be deleted by another administrator.",
messageId: "SVC4007"
}
-#---------SVC4008-----------------------------
-# %1 - Users's userId
+#---------SVC4008-----------------------------
+# %1 - Users's userId
INVALID_USER_ID: {
code: 400,
message: "Error: Invalid userId '%1'.",
messageId: "SVC4008"
}
-#---------SVC4049------------------------------
+#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
message: "Error: Invalid Content. Missing %1 contact.",
messageId: "SVC4049"
- }
-#---------SVC4050-----------------------------
+ }
+#---------SVC4050-----------------------------
# %1 - Service/Resource/Additional parameter
# %2 - service/resource/label name
COMPONENT_NAME_ALREADY_EXIST: {
message: "Error: %1 with name '%2' already exists.",
messageId: "SVC4050"
}
-#---------SVC4051------------------------------
-# %1 - resource/service
+#---------SVC4051------------------------------
+# %1 - resource/service
COMPONENT_MISSING_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Missing %1 category.",
messageId: "SVC4051"
}
-#---------SVC4052------------------------------
+#---------SVC4052------------------------------
COMPONENT_MISSING_TAGS: {
code: 400,
message: "Error: Invalid Content. At least one tag has to be specified.",
messageId: "SVC4052"
}
-#---------SVC4053------------------------------
+#---------SVC4053------------------------------
# %1 - service/resource
COMPONENT_MISSING_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. Missing %1 description.",
messageId: "SVC4053"
}
-#---------SVC4054------------------------------
+#---------SVC4054------------------------------
# %1 - resource/service
COMPONENT_INVALID_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 category.",
messageId: "SVC4054"
}
-#---------SVC4055------------------------------
+#---------SVC4055------------------------------
MISSING_VENDOR_NAME: {
code: 400,
message: "Error: Invalid Content. Missing vendor name.",
messageId: "SVC4055"
}
-#---------SVC4056------------------------------
+#---------SVC4056------------------------------
MISSING_VENDOR_RELEASE: {
code: 400,
message: "Error: Invalid Content. Missing vendor release.",
messageId: "SVC4056"
}
-#---------SVC4057------------------------------
+#---------SVC4057------------------------------
MISSING_DERIVED_FROM_TEMPLATE: {
code: 400,
message: "Error: Invalid Content. Missing derived from template specification.",
messageId: "SVC4057"
}
-#---------SVC4058------------------------------
+#---------SVC4058------------------------------
# %1 - service/resource
COMPONENT_MISSING_ICON: {
code: 400,
message: "Error: Invalid Content. Missing %1 icon.",
messageId: "SVC4058"
}
-#---------SVC4059------------------------------
+#---------SVC4059------------------------------
# %1 - service/resource
COMPONENT_INVALID_ICON: {
code: 400,
message: "Error: Invalid Content. Invalid %1 icon.",
messageId: "SVC4059"
}
-#---------SVC4060------------------------------
+#---------SVC4060------------------------------
PARENT_RESOURCE_NOT_FOUND: {
code: 400,
message: "Error: Invalid Content. Derived from resource template was not found.",
messageId: "SVC4060"
}
-#---------SVC4061------------------------------
+#---------SVC4061------------------------------
MULTIPLE_PARENT_RESOURCE_FOUND: {
code: 400,
message: "Error: Invalid Content. Multiple derived from resource template is not allowed.",
messageId: "SVC4061"
}
-#---------SVC4062------------------------------
+#---------SVC4062------------------------------
# %1 - service/resource
MISSING_COMPONENT_NAME: {
code: 400,
message: "Error: Invalid Content. Missing %1 name.",
messageId: "SVC4062"
}
-#---------SVC4063------------------------------
+#---------SVC4063------------------------------
#%1 - resource/service name
RESOURCE_NOT_FOUND: {
code: 404,
messageId: "SVC4063"
}
-#---------SVC4064------------------------------
+#---------SVC4064------------------------------
# %1 - Service/Resource/Property
COMPONENT_INVALID_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. %1 description contains non-english characters.",
messageId: "SVC4064"
}
-#---------SVC4065------------------------------
+#---------SVC4065------------------------------
# %1 - Service/Resource/Property
-# %2 - max resource/service name length
+# %2 - max resource/service name length
COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 description exceeds limit of %2 characters.",
messageId: "SVC4065"
}
-#---------SVC4066------------------------------
-# %1 - max length
+#---------SVC4066------------------------------
+# %1 - max length
COMPONENT_TAGS_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.",
messageId: "SVC4066"
}
#---------SVC4067------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor name exceeds limit of %1 characters.",
messageId: "SVC4067"
}
#---------SVC4068------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_RELEASE_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.",
messageId: "SVC4068"
}
-#---------SVC4069------------------------------
+#---------SVC4069------------------------------
# %1 - Service/Resource/Product
COMPONENT_INVALID_CONTACT: {
code: 400,
message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
-#---------SVC4070------------------------------
+#---------SVC4070------------------------------
# %1 - Service/Resource
INVALID_COMPONENT_NAME: {
code: 400,
messageId: "SVC4070"
}
-#---------SVC4071------------------------------
+#---------SVC4071------------------------------
INVALID_VENDOR_NAME: {
code: 400,
message: 'Error: Invalid Content. Vendor name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4071"
}
-#---------SVC4072------------------------------
+#---------SVC4072------------------------------
INVALID_VENDOR_RELEASE: {
code: 400,
message: 'Error: Invalid Content. Vendor release is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4072"
}
-#---------SVC4073------------------------------
+#---------SVC4073------------------------------
# %1 - Service/Resource
-# %2 - max resource/service name
+# %2 - max resource/service name
COMPONENT_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 name exceeds limit of %2 characters.",
messageId: "SVC4073"
}
-#---------SVC4080------------------------------
+#---------SVC4080------------------------------
# %1 - resource/service name
# %2Â - resource/service
# %3 - First name of last modifier
message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).",
messageId: "SVC4080"
}
-#---------SVC4081-----------------------------
+#---------SVC4081-----------------------------
# %1 - resource/service name
# %2Â - resource/service
# %3 - First name of last modifier
messageId: "SVC4081"
}
-#-----------SVC4082---------------------------
+#-----------SVC4082---------------------------
# %1 - resource/service name
# %2Â - resource/service
# %3 - First name of last modifier
}
#-----------SVC4102---------------------------
-# %1Â -Â capability type name
+# %1Â -Â capability type name
CAPABILITY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Capability Type with name '%1' already exists.",
messageId: "SVC4114"
}
#-----------SVC4115---------------------------
-# %1Â -Â capability type name
+# %1Â -Â capability type name
MISSING_CAPABILITY_TYPE: {
code: 400,
message: "Error: Invalid Content. Missing Capability Type '%1'.",
message: "Error: Artifact '%1' already exists.",
messageId: "SVC4125"
}
-#---------SVC4126------------------------------
+#---------SVC4126------------------------------
# %1Â - resource/service/product/...
# %2Â - field (tag, vendor name...)
INVALID_FIELD_FORMAT: {
#-----------SVC4131---------------------------
# %1-resource/service
# %2-srtifact/artifacts
-# %3-semicolomn separated list of artifact
+# %3-semicolomn separated list of artifact
COMPONENT_MISSING_MANDATORY_ARTIFACTS: {
code: 403,
message: "Error: Missing mandatory informational %1 %2: [%3].",
message: "Error: Invalid Content. Missing interface life-cycle type.",
messageId: "SVC4134"
}
-#---------SVC4135------------------------------
+#---------SVC4135------------------------------
SERVICE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service category cannot be changed once the service is certified.",
messageId: "SVC4135"
}
-#---------SVC4136------------------------------
-# %1 - distribution environment name
+#---------SVC4136------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: {
code: 500,
message: "Error: Requested distribution environment '%1' is not available.",
messageId: "SVC4136"
}
-#---------SVC4137------------------------------
-# %1 - distribution environment name
+#---------SVC4137------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_FOUND: {
code: 400,
message: "Error: Requested distribution environment '%1' was not found.",
messageId: "SVC4137"
}
-#---------SVC4138------------------------------
+#---------SVC4138------------------------------
DISTRIBUTION_ENVIRONMENT_INVALID: {
code: 400,
message: "Error: Invalid distribution environment.",
messageId: "SVC4138"
}
-#---------SVC4139------------------------------
+#---------SVC4139------------------------------
# %1 - service name
DISTRIBUTION_ARTIFACT_NOT_FOUND: {
code: 409,
message: "Error: Service '%1' cannot be distributed due to missing deployment artifacts.",
messageId: "SVC4139"
}
-#---------SVC4200------------------------------
+#---------SVC4200------------------------------
# %1 - Service/Resource
-# %2 - max icon name length
+# %2 - max icon name length
COMPONENT_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 icon name exceeds limit of %2 characters.",
messageId: "SVC4200"
}
-#---------SVC4300------------------------------
+#---------SVC4300------------------------------
RESTRICTED_ACCESS: {
code: 403,
message: "Error: Restricted access.",
messageId: "SVC4300"
}
-#---------SVC4301------------------------------
+#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
code: 409,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
-#---------SVC4500------------------------------
+#---------SVC4500------------------------------
MISSING_BODY: {
code: 400 ,
message: "Error: Missing request body.",
message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." ,
messageId: "SVC4501"
}
-#---------SVC4502------------------------------
+#---------SVC4502------------------------------
DISTRIBUTION_ENV_DOES_NOT_EXIST: {
code: 400 ,
message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." ,
messageId: "SVC4503"
}
-#---------SVC4504------------------------------
+#---------SVC4504------------------------------
# %1 - Service/Resource
# %2 - service/resource version
COMPONENT_VERSION_NOT_FOUND: {
}
#-----------SVC4505---------------------------
#%1-artifact name
-
+
ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Artifact '%1' was not found.",
messageId: "SVC4505"
}
-#---------SVC4506------------------------------
+#---------SVC4506------------------------------
MISSING_ENV_NAME: {
code: 400 ,
message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.",
messageId: "SVC4506"
}
-#---------SVC4507------------------------------
+#---------SVC4507------------------------------
COMPONENT_INVALID_TAGS_NO_COMP_NAME: {
code: 400,
message: "Error: Invalid Content. One of the tags should be the component name.",
messageId: "SVC4507"
}
-
-#---------SVC4508------------------------------
+
+#---------SVC4508------------------------------
SERVICE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service name cannot be changed once the service is certified.",
messageId: "SVC4508"
}
-#---------SVC4509------------------------------
+#---------SVC4509------------------------------
SERVICE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the service is certified.",
messageId: "SVC4509"
}
-#---------SVC4510------------------------------
+#---------SVC4510------------------------------
# %1 - icon name max length
SERVICE_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Icon name exceeds limit of %1 characters.",
messageId: "SVC4510"
}
-#---------SVC4511------------------------------
+#---------SVC4511------------------------------
DISTRIBUTION_REQUESTED_NOT_FOUND: {
code: 404,
message: "Error: Requested distribution was not found.",
messageId: "SVC4511"
}
-#---------SVC4512------------------------------
+#---------SVC4512------------------------------
# %1 - Distribution ID
DISTRIBUTION_REQUESTED_FAILED: {
code: 403,
message: "Error: Requested distribution '%1' failed.",
messageId: "SVC4512"
}
-#---------SVC4513------------------------------
+#---------SVC4513------------------------------
RESOURCE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource category cannot be changed once the resource is certified.",
messageId: "SVC4513"
}
-#---------SVC4514------------------------------
+#---------SVC4514------------------------------
RESOURCE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource name cannot be changed once the resource is certified.",
messageId: "SVC4514"
}
-#---------SVC4515------------------------------
+#---------SVC4515------------------------------
RESOURCE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the resource is certified.",
messageId: "SVC4515"
}
-#---------SVC4516------------------------------
+#---------SVC4516------------------------------
RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Vendor name cannot be changed once the resource is certified.",
messageId: "SVC4516"
}
-#---------SVC4517------------------------------
+#---------SVC4517------------------------------
RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Derived from resource template cannot be changed once the resource is certified.",
messageId: "SVC4517"
}
-#---------SVC4518------------------------------
-# %1 - max length
+#---------SVC4518------------------------------
+# %1 - max length
COMPONENT_SINGLE_TAG_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.",
messageId: "SVC4518"
}
-#---------SVC4519------------------------------
+#---------SVC4519------------------------------
INVALID_DEFAULT_VALUE: {
code: 400,
message: "Error: mismatch in data-type occurred for property %1. data type is %2 and default value found is %3.",
messageId: "SVC4519"
}
-#---------SVC4520------------------------------
-# %1 - service or resource
+#---------SVC4520------------------------------
+# %1 - service or resource
ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: {
code: 409,
message: "Error: Maximal number of additional %1 parameters was reached.",
message: "Error: Invalid Content. The Additional information label and value cannot be empty.",
messageId: "SVC4521"
}
-#---------SVC4522------------------------------
+#---------SVC4522------------------------------
# %1 - label/value
# %2 - Maximal length of %1
ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: {
message: "Error: Requested additional information was not found.",
messageId: "SVC4524"
}
-#---------SVC4525------------------------------
+#---------SVC4525------------------------------
ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: {
code: 400,
message: 'Error: Invalid Content. Additional information contains non-english characters.',
messageId: "SVC4525"
}
-#---------SVC4526------------------------------
+#---------SVC4526------------------------------
RESOURCE_INSTANCE_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' resource instance was not found.",
messageId: "SVC4526"
}
-#---------SVC4527------------------------------
+#---------SVC4527------------------------------
ASDC_VERSION_NOT_FOUND: {
code: 500,
message: 'Error: ASDC version cannot be displayed.',
messageId: "SVC4527"
}
-#---------SVC4528------------------------------
+#---------SVC4528------------------------------
# %1-artifact url/artifact label/artifact description/VNF Service Indicator
MISSING_DATA: {
code: 400,
message: "Error: Invalid content. Missing %1.",
messageId: "SVC4528"
}
-#---------SVC4529------------------------------
+#---------SVC4529------------------------------
# %1-artifact url/artifact label/artifact description/artifact name
# %2 - Maximal length of %1
EXCEEDS_LIMIT: {
message: "Error: Invalid Content. %1 exceeds limit of %2 characters.",
messageId: "SVC4529"
}
-#---------SVC4530------------------------------
+#---------SVC4530------------------------------
ARTIFACT_INVALID_TIMEOUT: {
code: 400,
message: "Error: Invalid Content. Artifact Timeout should be set to valid positive non-zero number of minutes.",
messageId: "SVC4530"
}
-#---------SVC4531------------------------------
+#---------SVC4531------------------------------
SERVICE_IS_VNF_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: VNF Indicator cannot be updated for certified service.",
messageId: "SVC4531"
}
- #---------SVC4532------------------------------
+ #---------SVC4532------------------------------
RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE: {
code: 404,
message: "Error: Requested '%1' resource instance was not found on the service '%2.",
messageId: "SVC4532"
}
- #---------SVC4533------------------------------
- # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
+ #---------SVC4533------------------------------
+ # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
WRONG_ARTIFACT_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for %1 artifact type.",
messageId: "SVC4533"
}
-#---------SVC4534------------------------------
-# %1 - "HEAT"/"HEAT_ENV"
+#---------SVC4534------------------------------
+# %1 - "HEAT"/"HEAT_ENV"
INVALID_YAML: {
code: 400,
message: "Error: Uploaded YAML file for %1 artifact is invalid.",
messageId: "SVC4534"
}
-#---------SVC4535------------------------------
-# %1 - "HEAT"
+#---------SVC4535------------------------------
+# %1 - "HEAT"
INVALID_DEPLOYMENT_ARTIFACT_HEAT: {
code: 400,
message: "Error: Invalid %1 artifact.",
messageId: "SVC4535"
}
-#---------SVC4536------------------------------
+#---------SVC4536------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
+# %2 - resource/service name
+# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG
DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: {
code: 400,
messageId: "SVC4536"
}
-#---------SVC4537------------------------------
+#---------SVC4537------------------------------
MISSING_HEAT: {
code: 400,
message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.",
messageId: "SVC4537"
}
-#---------SVC4538------------------------------
+#---------SVC4538------------------------------
MISMATCH_HEAT_VS_HEAT_ENV: {
code: 400,
message: "Error: Invalid artifact content. Parameter's set in HEAT_ENV '%1' artifact doesn't match the parameters in HEAT '%2' artifact.",
messageId: "SVC4538"
}
-#---------SVC4539------------------------------
+#---------SVC4539------------------------------
INVALID_RESOURCE_PAYLOAD: {
code: 400,
message: "Error: Invalid resource payload.",
messageId: "SVC4539"
}
-#---------SVC4540------------------------------
+#---------SVC4540------------------------------
INVALID_TOSCA_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for TOSCA template.",
messageId: "SVC4540"
}
-#---------SVC4541------------------------------
+#---------SVC4541------------------------------
INVALID_YAML_FILE: {
code: 400,
message: "Error: Invalid YAML file.",
messageId: "SVC4541"
}
-#---------SVC4542------------------------------
+#---------SVC4542------------------------------
INVALID_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Invalid TOSCA template.",
messageId: "SVC4542"
}
-#---------SVC4543------------------------------
+#---------SVC4543------------------------------
NOT_RESOURCE_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Imported Service TOSCA template.",
messageId: "SVC4543"
}
-#---------SVC4544------------------------------
+#---------SVC4544------------------------------
NOT_SINGLE_RESOURCE: {
code: 400,
message: "Error: Imported TOSCA template should contain one resource definition.",
messageId: "SVC4544"
}
-#---------SVC4545------------------------------
+#---------SVC4545------------------------------
INVALID_RESOURCE_NAMESPACE: {
code: 400,
message: "Error: Invalid resource namespace.",
messageId: "SVC4545"
}
-#---------SVC4546------------------------------
+#---------SVC4546------------------------------
RESOURCE_ALREADY_EXISTS: {
code: 400,
message: "Error: Imported resource already exists in ASDC Catalog.",
messageId: "SVC4546"
}
-#---------SVC4549------------------------------
+#---------SVC4549------------------------------
INVALID_RESOURCE_CHECKSUM: {
code: 400,
message: "Error: Invalid resource checksum.",
messageId: "SVC4549"
}
-#---------SVC4550------------------------------
+#---------SVC4550------------------------------
#%1Â -Â Consumer salt
INVALID_LENGTH: {
code: 400,
message: "Error: Invalid %1 length.",
messageId: "SVC4550"
}
- #---------SVC4551------------------------------
+ #---------SVC4551------------------------------
#%1Â -Â ECOMP User name
ECOMP_USER_NOT_FOUND: {
code: 404,
messageId: "SVC4552"
}
#---------SVC4553-----------------------------
- #%1Â -Â Consumer name / Consumer password/ Consumer salt
+ #%1Â -Â Consumer name / Consumer password/ Consumer salt
INVALID_CONTENT_PARAM: {
code: 400,
message: "Error: %1 is invalid.",
messageId: "SVC4553"
}
- #---------SVC4554------------------------------
+ #---------SVC4554------------------------------
# %1 - "Resource"/"Service"
COMPONENT_ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.",
messageId: "SVC4554"
}
-#---------SVC4555------------------------------
+#---------SVC4555------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_LENGTH: {
message: "Error: Invalid %1 %2 name length.",
messageId: "SVC4555"
}
-#---------SVC4556------------------------------
+#---------SVC4556------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_FORMAT: {
message: "Error: Invalid %1 %2 name format.",
messageId: "SVC4556"
}
-#---------SVC4557------------------------------
+#---------SVC4557------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category name"
COMPONENT_CATEGORY_ALREADY_EXISTS: {
code: 403,
message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use one of available validated resource versions.",
messageId: "SVC4560"
- }
+ }
#---------SVC4561------------------------------
# %1 - "resource"/"product"
# %2 - "category"
message: "Error: %1 grouping '%2' already exists under '%3' sub-category.",
messageId: "SVC4563"
}
-#---------SVC4564------------------------------
+#---------SVC4564------------------------------
# %1 - product name
PRODUCT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' product was not found.",
messageId: "SVC4564"
}
-#---------SVC4565------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4565------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
# %3 - parameter name
INVALID_HEAT_PARAMETER_VALUE: {
code: 400,
message: "Error: Invalid %1 artifact. Invalid %2 value set for '%3' parameter.",
messageId: "SVC4565"
}
-#---------SVC4566------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4566------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
INVALID_HEAT_PARAMETER_TYPE: {
code: 400,
message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.",
messageId: "SVC4566"
}
-#---------SVC4567------------------------------
-# %1 - "YANG_XML"
+#---------SVC4567------------------------------
+# %1 - "YANG_XML"
INVALID_XML: {
code: 400,
message: "Error: Uploaded XML file for %1 artifact is invalid.",
messageId: "SVC4567"
}
-#---------SVC4567------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4567------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: User cannot be deleted. User '%1' has %2 projects.",
messageId: "SVC4567"
}
-#---------SVC4568------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4568------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: Role cannot be changed. User '%1' has %2 projects.",
messageId: "SVC4568"
}
-#---------SVC4570------------------------------
+#---------SVC4570------------------------------
UPDATE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator is not allowed to change his/her role.",
messageId: "SVC4570"
}
-#---------SVC4571------------------------------
+#---------SVC4571------------------------------
SERVICE_CANNOT_CONTAIN_SUBCATEGORY: {
code: 400,
message: "Error: Sub category cannot be defined for service",
messageId: "SVC4571"
}
-#---------SVC4572------------------------------
+#---------SVC4572------------------------------
# %1 - "Resource"/"Service"
COMPONENT_TOO_MUCH_CATEGORIES: {
code: 400,
message: "Error: %1 must have only 1 category",
messageId: "SVC4572"
}
-#---------SVC4574------------------------------
+#---------SVC4574------------------------------
RESOURCE_TOO_MUCH_SUBCATEGORIES: {
code: 400,
message: "Error: Resource must have only 1 sub category",
messageId: "SVC4574"
}
-#---------SVC4575------------------------------
+#---------SVC4575------------------------------
COMPONENT_MISSING_SUBCATEGORY: {
code: 400,
message: "Error: Missing sub category",
messageId: "SVC4575"
}
- #---------SVC4576------------------------------
+ #---------SVC4576------------------------------
# %1 - "component type"
UNSUPPORTED_ERROR: {
code: 400,
message: "Error : Requested component type %1 is unsupported.",
messageId: "SVC4576"
}
- #---------SVC4577------------------------------
+ #---------SVC4577------------------------------
# %1 - "resource type"
RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: {
code: 409,
message: "Error : Resource of type %1 cannot contain resource instances.",
messageId: "SVC4577"
}
-#---------SVC4578------------------------------
+#---------SVC4578------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "artifact name"
+# %2 - resource/service name
+# %3 - "artifact name"
DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS: {
code: 400,
message: "Error: %1 '%2' already has a deployment artifact named '%3'.",
messageId: "SVC4578"
}
-#---------SVC4579------------------------------
+#---------SVC4579------------------------------
# %1 - "Category"/"Sub-Category"/"Group"
# %2 - category/sub-category/grouping name.
INVALID_GROUP_ASSOCIATION: {
message: "Error: Invalid group association. %1 '%2' was not found.",
messageId: "SVC4579"
}
-#---------SVC4580------------------------------
+#---------SVC4580------------------------------
EMPTY_PRODUCT_CONTACTS_LIST: {
code: 400,
message: "Error: Invalid content. At least one Product Contact has to be specified.",
messageId: "SVC4580"
}
-#---------SVC4581------------------------------
+#---------SVC4581------------------------------
# %1 - UserId
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
messageId: "SVC4581"
}
-#---------SVC4582------------------------------
+#---------SVC4582------------------------------
# %1 - Product
# %2 - "abbreviated"/"full"
MISSING_ONE_OF_COMPONENT_NAMES: {
code: 400,
message: "Error: Invalid content. Missing %1 %2 name.",
messageId: "SVC4582"
- }
+ }
#---------SVC4583------------------------------
# %1 - "Icon"
# %2 - "resource"/"service"/"product"
messageId: "SVC4583"
}
#---------SVC4584------------------------------
-# %1 - service/VF name
+# %1 - service/VF name
# %2 - "service" /"VF"
# %3 - resource instance origin type
-# %4 - resource instance name
+# %4 - resource instance name
# %5 - requirement/capability
# %6 - requirement/capability name
# %7 - "fulfilled" (for req)/"consumed (for cap)"
message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.",
messageId: "SVC4584"
}
-#---------SVC4585------------------------------
+#---------SVC4585------------------------------
INVALID_OCCURRENCES: {
code: 400,
message: "Error: Invalid occurrences format.",
messageId: "SVC4585"
}
-#---------SVC4586------------------------------
-#---------SVC4586------------------------------
+#---------SVC4586------------------------------
+#---------SVC4586------------------------------
INVALID_SERVICE_API_URL: {
code: 400,
message: 'Error: Invalid Service API URL. Please check whether your URL has a valid domain extension and does not contain the following characters - #?&@%+;,=$<>~^`\[]{}|"*!',
messageId: "SVC4586"
}
-#---------SVC4587------------------------------
-# %1 - Data type name
+#---------SVC4587------------------------------
+# %1 - Data type name
DATA_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Data type %1 already exists.',
messageId: "SVC4587"
}
-#---------SVC4588------------------------------
-# %1 - Data type name
+#---------SVC4588------------------------------
+# %1 - Data type name
DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: {
code: 400,
message: 'Error: Invalid Data type %1. Data type must have either a valid derived from declaration or at least one valid property',
messageId: "SVC4588"
}
-#---------SVC4589------------------------------
-# %1 - Data type name
+#---------SVC4589------------------------------
+# %1 - Data type name
DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: {
code: 400,
message: "Error: Invalid Data type %1. 'properties' parameter cannot be empty if provided.",
messageId: "SVC4589"
}
-#---------SVC4590------------------------------
-# %1 - Property type name
+#---------SVC4590------------------------------
+# %1 - Property type name
# %2 - Property name
INVALID_PROPERTY_TYPE: {
code: 400,
message: "Error: Invalid Property type %1 in property %2.",
messageId: "SVC4590"
}
-#---------SVC4591------------------------------
+#---------SVC4591------------------------------
# %1 - Property inner type
-# %2 - Property name
+# %2 - Property name
INVALID_PROPERTY_INNER_TYPE: {
code: 400,
message: "Error: Invalid property inner type %1, in property %2",
messageId: "SVC4591"
}
-#---------SVC4592------------------------------
+#---------SVC4592------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
COMPONENT_INSTANCE_NOT_FOUND: {
message: "Error: Requested '%1' %2 was not found.",
messageId: "SVC4592"
}
-#---------SVC4593------------------------------
+#---------SVC4593------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
# %3 - "resource/"service"/"product"
-# %4 - container name
+# %4 - container name
COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: {
code: 404,
message: "Error: Requested '%1' %2 was not found on the %3 '%4'.",
#---------SVC4595------------------------------
#%1 - requirement / capability
#%2 - requirement name
-#%3 - parent containing the requirement
+#%3 - parent containing the requirement
IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED: {
code: 400,
message: "Error: Imported TOSCA template contains %1 '%2' that is already defined by derived template %3.",
messageId: "SVC4595"
}
-#---------SVC4596------------------------------
+#---------SVC4596------------------------------
# %1 - Data type name
DATA_TYPE_DERIVED_IS_MISSING: {
code: 400,
message: "Error: Invalid Content. The ancestor data type %1 cannot be found in the system.",
messageId: "SVC4596"
}
-#---------SVC4597------------------------------
+#---------SVC4597------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: {
message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.",
messageId: "SVC4597"
}
-#---------SVC4598------------------------------
+#---------SVC4598------------------------------
# %1 - Data type name
DATA_TYPE_DUPLICATE_PROPERTY: {
code: 400,
message: "Error: Invalid Content. The data type %1 contains duplicate property.",
messageId: "SVC4598"
}
-#---------SVC4599------------------------------
+#---------SVC4599------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: {
message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.",
messageId: "SVC4599"
}
-#---------SVC4600------------------------------
+#---------SVC4600------------------------------
# %1 - Data type name
DATA_TYPE_CANNOT_HAVE_PROPERTIES: {
code: 400,
message: "Error: Invalid Content. The data type %1 cannot have properties since it is of type scalar",
messageId: "SVC4600"
}
-#---------SVC4601------------------------------
+#---------SVC4601------------------------------
NOT_TOPOLOGY_TOSCA_TEMPLATE: {
code: 400,
message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.",
message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL",
messageId: "SVC4602"
}
-#---------SVC4603------------------------------
+#---------SVC4603------------------------------
# %1Â -Â component type
# %2 - component name
# %3Â - state
message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.",
messageId: "SVC4603"
}
-#---------SVC4604------------------------------
+#---------SVC4604------------------------------
# %1Â -Â csar file name
CSAR_INVALID: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. 'TOSCA-Metadata/Tosca.meta' file must be provided.",
messageId: "SVC4604"
}
-#---------SVC4605------------------------------
+#---------SVC4605------------------------------
# %1Â -Â csar file name
CSAR_INVALID_FORMAT: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. Invalid 'TOSCA-Metadata/Tosca.meta' file format.",
messageId: "SVC4605"
}
-#---------SVC4606------------------------------
+#---------SVC4606------------------------------
# %1Â -Â property name
# %2Â - property type
# %3 - property innerType
message: "Error: Invalid default value of property %1. Data type is %2 with inner type %3 and default value found is %4.",
messageId: "SVC4606"
}
-#---------SVC4607------------------------------
+#---------SVC4607------------------------------
# %1Â -Â csar file name
CSAR_NOT_FOUND: {
code: 400,
message: "Error: TOSCA CSAR '%1' is not found.",
messageId: "SVC4607"
}
-#---------SVC4608------------------------------
+#---------SVC4608------------------------------
# %1Â -Â artifact name
# %2Â - component type
# %3 - actual component type
messageId: "SVC4608"
}
-#---------SVC4609------------------------------
-# %1 - "INVALID_JSON"
+#---------SVC4609------------------------------
+# %1 - "INVALID_JSON"
INVALID_JSON: {
code: 400,
message: "Error: Uploaded JSON file for %1 artifact is invalid.",
messageId: "SVC4609"
}
-#---------SVC4610------------------------------
+#---------SVC4610------------------------------
# %1Â -Â csar file name
# %2Â -Â missing file name
YAML_NOT_FOUND_IN_CSAR: {
message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.",
messageId: "SVC4610"
}
-#---------SVC4611------------------------------
+#---------SVC4611------------------------------
# %1 - group name
GROUP_MEMBER_EMPTY: {
code: 400,
message: "Error: Invalid Content. Group %1 member list was provided but does not have values",
messageId: "SVC4611"
}
-#---------SVC4612------------------------------
-# %1 - group name
+#---------SVC4612------------------------------
+# %1 - group name
GROUP_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Group type %1 already exists.',
messageId: "SVC4612"
}
-#---------SVC4613------------------------------
+#---------SVC4613------------------------------
# %1Â -Â group name
# %2Â - VF name(component name)
# %3 - actual component type [VF]
code: 409,
message: "Error: Group with name '%1' already exists in %2 %3.",
messageId: "SVC4613"
- }
-#---------SVC4614------------------------------
+ }
+#---------SVC4614------------------------------
# %1Â -Â group type
GROUP_TYPE_IS_INVALID: {
code: 400,
message: "Error: Invalid content. Group type %1 does not exist",
messageId: "SVC4614"
}
-#---------SVC4615------------------------------
+#---------SVC4615------------------------------
# %1Â -Â group name
GROUP_MISSING_GROUP_TYPE: {
code: 400,
code: 400,
message: "Error: Member '%1' listed in group '%2' is not part of '%3' %4.",
messageId: "SVC4616"
- }
+ }
#---------SVC4617------------------------------
# %1 - member name
# %2 - group name
message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.",
messageId: "SVC4617"
}
-#---------SVC4618------------------------------
+#---------SVC4618------------------------------
# %1Â -Â missing file name
# %2Â -Â csar file name
ARTIFACT_NOT_FOUND_IN_CSAR: {
message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided",
messageId: "SVC4618"
}
-#---------SVC4619------------------------------
+#---------SVC4619------------------------------
# %1Â - artifact name
# %2Â -Â artifact type
# %3 - existing artifact type
message: "Error: artifact %1 in type %2 already exists in type %3.",
messageId: "SVC4619"
}
-#---------SVC4620------------------------------
+#---------SVC4620------------------------------
FAILED_RETRIVE_ARTIFACTS_TYPES: {
code: 400,
message: "Error: Failed to retrieve list of suported artifact types.",
messageId: "SVC4620"
}
-#---------SVC4621------------------------------
+#---------SVC4621------------------------------
# %1Â - artifact name
-# %2Â - master
+# %2Â - master
ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: {
code: 400,
message: "Error: artifact %1 already exists in master %2 .",
messageId: "SVC4621"
}
-#---------SVC4622------------------------------
+#---------SVC4622------------------------------
# %1Â - artifact name
-# %2Â - artifact type
+# %2Â - artifact type
# %3Â - master name
# %4 - master type
ARTIFACT_NOT_VALID_IN_MASTER: {
message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.",
messageId: "SVC4622"
}
-#---------SVC4623------------------------------
+#---------SVC4623------------------------------
# %1Â - artifact name
-# %2Â - artifact type
+# %2Â - artifact type
# %3Â - env name
# %4 - existing env
ARTIFACT_NOT_VALID_ENV: {
message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4",
messageId: "SVC4623"
}
-#---------SVC4624------------------------------
+#---------SVC4624------------------------------
# %1Â -Â groups names
# %2 - VF name
# %3 - component type [VF ]
message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.",
messageId: "SVC4624"
}
-#---------SVC4625------------------------------
+#---------SVC4625------------------------------
# %1Â -Â groups name
GROUP_ARTIFACT_ALREADY_ASSOCIATED: {
code: 400,
message: "Error: Invalid Content. Artifact already associated to group '%1'.",
messageId: "SVC4625"
}
-#---------SVC4626------------------------------
+#---------SVC4626------------------------------
# %1Â -Â groups name
GROUP_ARTIFACT_ALREADY_DISSOCIATED: {
code: 400,
message: "Error: property %1 listed in group %2 is not exist in group type %3.",
messageId: "SVC4627"
}
-#---------SVC4628------------------------------
+#---------SVC4628------------------------------
# %1 - csarUUID
# %2 - VF name
VSP_ALREADY_EXISTS: {
message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.",
messageId: "SVC4628"
}
-#---------SVC4629------------------------------
+#---------SVC4629------------------------------
# %1 - VF name
MISSING_CSAR_UUID: {
code: 400,
message: "Error: The Csar UUID or payload name is missing for VF %1.",
messageId: "SVC4629"
}
-#---------SVC4630------------------------------
+#---------SVC4630------------------------------
# %1 - VF name
# %2 - new csarUUID
# %3 - old csarUUID
message: "Error: Resource %1 cannot be updated using CsarUUID %2 since the resource is linked to a different VSP with csarUUID %3.",
messageId: "SVC4630"
}
-#---------SVC4631------------------------------
-# %1 - policy name
+#---------SVC4631------------------------------
+# %1 - policy name
POLICY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Policy type %1 already exists.",
code: 404,
message: "Error: Requested '%1' attribute was not found.",
messageId: "SVC4637"
- }
+ }
#-----------SVC4638---------------------------
#%1 - attribute name
ATTRIBUTE_ALREADY_EXIST: {
message: "Error: Invalid Content. VF Module name '%1' contains invalid characters",
messageId: "SVC4646"
}
-
+
#---------SVC4647------------------------------
# %1 - "modifiedName"
INVALID_VF_MODULE_NAME_MODIFICATION: {
message: "Error: Once resource is certified, derived_from can be changed only to a sibling",
messageId: "SVC4651"
}
-#---------SVC4652------------------------------
+#---------SVC4652------------------------------
# %1 - resource/service
COMPONENT_INVALID_SUBCATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 sub category.",
messageId: "SVC4652"
}
-#---------SVC4653------------------------------
-# %1 - group instance uniqueId
+#---------SVC4653------------------------------
+# %1 - group instance uniqueId
# %2 - service uniqueId
GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE: {
code: 404,
message: "Error: Requested group instance %1 was not found on component %2.",
messageId: "SVC4653"
}
-#---------SVC4654------------------------------
-# %1 - group property name
+#---------SVC4654------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: {
message: "Error: Value of %1 must be not higher than %2, and not lower than %3.",
messageId: "SVC4654"
}
-#---------SVC4655------------------------------
-# %1 - group property name
+#---------SVC4655------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: {
message: "Error: Value of %1 must be between %2 and %3.",
messageId: "SVC4655"
}
-#---------SVC4656------------------------------
-# %1 - group property name
+#---------SVC4656------------------------------
+# %1 - group property name
# %2 - lower/higher
# %3 - valid max/min value
INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER: {
code: 400,
message: "Error: Value of %1 must be %2 or equals to %3.",
messageId: "SVC4656"
- }
+ }
#---------SVC4657------------------------------
# %1 - certificationRequest / startTesting
RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID: {
# %1 – asset type [service / resource ]
# %2 – main asset uuid
# %3 – not found asset type [service / resource]
-# %4 – not found asset name
+# %4 – not found asset name
ASSET_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
message: "Error: CSAR packaging failed for %1 %2. %3 %4 was not found",
#---------SVC4659------------------------------
# %1 – asset type [service / resource ]
# %2 – main asset uuid
-# %3 – Artifact name
+# %3 – Artifact name
# %4 – Artifact uuid
ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
messageId: "SVC4660"
}
#---------SVC4661------------------------------
-# %1 - version
-# %2 - conformance level
+# %1 - assetType
+# %2 - matching generic node type name
TOSCA_SCHEMA_FILES_NOT_FOUND: {
code: 400,
message: "Error: CSAR packaging failed. TOSCA schema files for SDC-Version: %1 and Conformance-Level %2 were not found",
messageId: "SVC4661"
}
-#---------SVC4662------------------------------
+#---------SVC4662------------------------------
# %1 - file name
# %2 - parser error
TOSCA_PARSE_ERROR: {
code: 400,
message: "Error: Invalid TOSCA template in file %1. %2",
messageId: "SVC4662"
+ }
+#---------SVC4663------------------------------
+# %1 - max length
+ RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Resource vendor model number exceeds limit of %1 characters.",
+ messageId: "SVC4663"
+ }
+#---------SVC4664------------------------------
+ INVALID_RESOURCE_VENDOR_MODEL_NUMBER: {
+ code: 400,
+ message: 'Error: Invalid Content. Resource vendor model number is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4664"
+ }
+#---------SVC4665------------------------------
+# %1 - max length
+ SERVICE_TYPE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service type exceeds limit of %1 characters.",
+ messageId: "SVC4665"
+ }
+#---------SVC4666------------------------------
+ INVALID_SERVICE_TYPE: {
+ code: 400,
+ message: 'Error: Invalid Content. Serivce type is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4666"
+ }
+#---------SVC4667------------------------------
+# %1 - max length
+ SERVICE_ROLE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service role exceeds limit of %1 characters.",
+ messageId: "SVC4667"
+ }
+#---------SVC4668------------------------------
+ INVALID_SERVICE_ROLE: {
+ code: 400,
+ message: 'Error: Invalid Content. Service role is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4668"
+ }
+
+#---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ }
+#---------SVC4670------------------------------
+ ARTIFACT_NAME_INVALID: {
+ code: 400,
+ message: "Error: Artifact name is invalid.",
+ messageId: "SVC4670"
+ }
+#---------SVC4671------------------------------
+# %1 - VSP name
+# %2 - VFC name
+ CFVC_LOOP_DETECTED: {
+ code: 400,
+ message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2',
+ messageId: "SVC4671"
}
\ No newline at end of file
type: string
required: false
+# NFoD
+org.openecomp.datatypes.flavors.ComputeFlavor:
+ derived_from: tosca.datatypes.Root
+ properties:
+ num_cpus:
+ type: integer
+ disk_size:
+ type: scalar-unit.size
+ mem_size:
+ type: scalar-unit.size
+
+org.openecomp.datatypes.flavors.LicenseFlavor:
+ derived_from: tosca.datatypes.Root
+ properties:
+ feature_group_uuid:
+ type: string
+
+org.openecomp.datatypes.flavors.VendorInfo:
+ derived_from: tosca.datatypes.Root
+ properties:
+ manufacturer_reference_number:
+ type: string
+ vendor_model:
+ type: string
+
+org.openecomp.datatypes.flavors.DeploymentFlavor:
+ derived_from: tosca.datatypes.Root
+ properties:
+ sp_part_number:
+ type: string
+ vendor_info:
+ type: org.openecomp.datatypes.flavors.VendorInfo
+ compute_flavor:
+ type: org.openecomp.datatypes.flavors.ComputeFlavor
+ license_flavor:
+ type: org.openecomp.datatypes.flavors.LicenseFlavor
+ required: false
+
+
+org.openecomp.datatypes.ImageInfo:
+ derived_from: tosca.datatypes.Root
+ properties:
+ software_version:
+ type: string
+ file_name:
+ type: string
+ file_hash:
+ type: string
+ description: checksum/signature
+ file_hash_type:
+ type: string
+ required: false
+ default: md5
--- /dev/null
+{
+ "payloadName": "Generic_PNF.yml",
+ "contactId": "jh0003",
+ "name": "Generic_PNF",
+ "description": "Represents a generic PNF.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "Generic_PNF"
+ ]
+}
\ No newline at end of file
--- /dev/null
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.PNF:
+ derived_from: tosca.nodes.Root
+ properties:
+ nf_function:
+ type: string
+ nf_role:
+ type: string
+ nf_type:
+ type: string
\ No newline at end of file
subnetpoolid:
type: string
requirements:
- virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- virtualBinding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo
- external_virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- node: org.openecomp.resource.vl.VL
+ - virtualLink:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ - virtualBinding:
+ capability: tosca.capabilities.network.Bindable
+ relationship: tosca.relationships.network.BindsTo
+ - external_virtualLink:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ node: org.openecomp.resource.vl.VL
capabilities:
internal_connectionPoint:
type: tosca.capabilities.Node
--- /dev/null
+{
+ "payloadName": "multiFlavorVFC.yml",
+ "contactId": "jh0003",
+ "name": "multiFlavorVFC",
+ "description": "Represents a generic multi flavor VFC.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "VFC",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "multiFlavorVFC"
+ ]
+}
\ No newline at end of file
--- /dev/null
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.MultiFlavorVFC:
+ derived_from: org.openecomp.resource.abstract.nodes.VFC
+ properties:
+ images:
+ type: map
+ entry_schema:
+ type: org.openecomp.datatypes.ImageInfo
+ required: false
--- /dev/null
+{
+ "payloadName": "vnfConfiguration.yml",
+ "contactId": "jh0003",
+ "name": "vnfConfiguration",
+ "description": "Configuration parameters for VNF",
+ "resourceIconPath": "vnfconfiguration",
+ "resourceType": "VFC",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "vnfConfiguration"
+ ]
+}
\ No newline at end of file
--- /dev/null
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.VnfConfiguration:
+ derived_from: tosca.nodes.Root
+ properties:
+ allowed_flavors:
+ description: a collection of all flavor valuesets available for a given VFC
+ type: map
+ entry_schema:
+ type: org.openecomp.datatypes.flavors.DeploymentFlavor
"eline",
"abstractSubstitute",
"Generic_VFC",
- "Generic_VF",
+ "Generic_VF",
+ "Generic_PNF",
"Generic_Service",
"contrailNetworkRules",
"contrailPort",
"contrailCompute",
"contrailV2VirtualMachineInterface",
"subInterface",
- "contrailV2VLANSubInterface"
+ "contrailV2VLANSubInterface",
+ "multiFlavorVFC",
+ "vnfConfiguration"
]
responseCodes = [200, 201]
"extVl",
"extCp",
"Generic_VFC",
- "Generic_VF",
+ "Generic_VF",
+ "Generic_PNF",
"Generic_Service",
"globalPort",
"globalNetwork",
"contrailVirtualNetwork",
"neutronNet",
"neutronPort",
+ "multiFlavorVFC",
+ "vnfConfiguration"
]
responseCodes = [200, 201]
<servlet-mapping>
<servlet-name>jerseyDistribution</servlet-name>
<url-pattern>/sdc/*</url-pattern>
- <url-pattern>/asdc/*</url-pattern>
</servlet-mapping>
<servlet>
import java.util.ArrayList;
import java.util.List;
+import javax.annotation.Resource;
+
import org.junit.Test;
import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import com.datastax.driver.core.Cluster;
+
+import fj.data.Either;
+
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class HealthCheckBusinessLogicTest {
HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic();
-
+
@Test
public void checkStausUpdated() {
HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, null);
HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, null);
- HealthCheckInfo checkInfoEsUp = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.UP, null, null);
- HealthCheckInfo checkInfoEsDown = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.DOWN, null, null);
-
/*
* HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null);
*/
checkInfosLeft.add(checkInfoTitanUp);
- checkInfosLeft.add(checkInfoEsUp);
checkInfosRight.add(checkInfoTitanUp);
- checkInfosRight.add(checkInfoEsUp);
statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
assertFalse("check false", statusChanged);
testSetDerivedFrom(resource);
testSetProperties(resource);
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
}
@Test
Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true));
- Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
}
Resource resource = createResource.left().value().left;
testSetCapabilities(resource);
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true);
}
}
});
- when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)))
+ when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)))
.thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
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.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
public static final String RESOURCE_NAME = "My-Resource_Name with space";
private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC";
+ private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
final ServletContext servletContext = Mockito.mock(ServletContext.class);
IAuditingManager iAuditingManager = null;
UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
+ NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
Resource resourceResponse = null;
Resource genericVF = null;
Resource genericVFC = null;
+ Resource genericPNF = null;
ComponentsUtils componentsUtils = new ComponentsUtils();
- ArtifactsBusinessLogic artifactManager = Mockito.mock(ArtifactsBusinessLogic.class);
+ ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic();
CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
+ when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
-
- ArtifactDefinition artifactDef = new ArtifactDefinition();
- artifactDef.setUniqueId("123.123");
- Either<ArtifactDefinition, StorageOperationStatus> returnEither = Either.left(artifactDef);
- when(artifactManager.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
-
- when(artifactManager.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(returnEither);
-
+
// createResource
resourceResponse = createResourceObject(true);
Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
// BL object
+ artifactManager.nodeTemplateOperation = nodeTemplateOperation;
bl = new ResourceBusinessLogic();
bl.setElementDao(mockElementDao);
bl.setUserAdmin(mockUserAdmin);
resource.setDerivedFrom(template);
resource.setVendorName("Motorola");
resource.setVendorRelease("1.0.0");
+ resource.setResourceVendorModelNumber("");
resource.setContactId("ya5467");
resource.setIcon("MyIcon");
resource.setCsarUUID("valid_vf.csar");
testVendorNameWrongFormatCreate();
testVendorReleaseWrongFormat();
testVendorReleaseExceedsLimitCreate();
+ testResourceVendorModelNumberExceedsLimit();
testResourceVendorNameMissing();
testResourceVendorReleaseMissing();
testResourceCategoryExist();
private void testVendorNameExceedsLimit() {
Resource resourceExccedsVendorNameLimit = createResourceObject(false);
- String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
+
+ private void testResourceVendorModelNumberExceedsLimit() {
+ Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
+ String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ }
private void testVendorNameWrongFormatCreate() {
Resource resource = createResourceObject(false);
@Test
- public void testGeneratedInputs() {
+ public void testVFGeneratedInputs() {
Resource resource = createVF();
List<InputDefinition> inputs = resource.getInputs();
}
@Test
- public void testUpdateGenericInputsToLatestOnCheckout() {
+ public void testVFUpdateGenericInputsToLatestOnCheckout() {
//create a VF that is derived from generic version 1.0
Resource resource = createVF();
@Test
- public void testUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
+ public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
//create a VF that is derived from generic version 1.0
Resource resource = createVF();
assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer"));
}
+ @Test
+ public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
+
+ Resource resource = createPNF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertTrue(8 == inputs.size());
+ for(InputDefinition input : inputs){
+ assertNotNull(input.getOwnerId());
+ }
+ assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName()));
+ assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion()));
+ assertTrue(0 == resource.getArtifacts().size());
+ }
+
+
private Resource createVF() {
genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
return createResponse.left().value();
}
+ private Resource createPNF() {
+
+ genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.PNF);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isLeft());
+ return createResponse.left().value();
+ }
+
private Resource setupGenericTypeMock(String toscaName) {
return genericType;
}
+
+
}
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.datamodel.ToscaElementTypeEnum;
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;
resource.setVendorRelease("1.0.0");
resource.setContactId("yavivi");
resource.setIcon("MyIcon.jpg");
-
+ resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
+
return resource;
}
resource.setVendorRelease("1.0.0");
resource.setContactId("yavivi");
resource.setIcon("MyIcon.jpg");
+ resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
return resource;
}
- HTTP_IV_REMOTE_ADDRESS
- HTTP_CSP_WSTYPE
-
-
# catalog backend hostname
beFqdn: sdccatalog.att.com
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
+minToscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
titanInMemoryGraph: true
titanLockTimeout: 600
+
+# The interval to try and reconnect to titan DB when it is down during ASDC startup:
titanReconnectIntervalInSeconds: 3
+
+# The read timeout towards Titan DB when health check is invoked:
titanHealthCheckReadTimeout: 1
+
+# The interval to try and reconnect to Elasticsearch when it is down during ASDC startup:
esReconnectIntervalInSeconds: 3
uebHealthCheckReconnectIntervalInSeconds: 15
uebHealthCheckReadTimeout: 4
+
# Protocols
protocols:
- http
- https
+# Default imports
+defaultImports:
+ - nodes:
+ file: nodes.yml
+ - datatypes:
+ file: data.yml
+ - capabilities:
+ file: capabilities.yml
+ - relationships:
+ file: relationships.yml
+ - groups:
+ file: groups.yml
+ - policies:
+ file: policies.yml
+
# Users
users:
tom: passwd
bob: passwd
-
+
neo4j:
host: neo4jhost
port: 7474
user: neo4j
password: "12345"
-
+
+cassandraConfig:
+ cassandraHosts: ['localhost']
+ localDataCenter:
+ reconnectTimeout : 30000
+ authenticate: false
+ username: koko
+ password: bobo
+ ssl: false
+ truststorePath : /path/path
+ truststorePassword : 123123
+ keySpaces:
+ - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
#Application-specific settings of ES
elasticSearch:
# Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour).
#
# If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month.
-
+
indicesTimeFrequency:
- indexPrefix: auditingevents
creationPeriod: month
- VL
- VF
- VFCMT
-
+ - Abstract
+
# validForResourceTypes usage
# validForResourceTypes:
# - VF
# displayName: "Network HEAT Template"
# type: HEAT_NET
# validForResourceTypes: *allResourceTypes
-
+
deploymentResourceInstanceArtifacts:
heatEnv:
displayName: "HEAT ENV"
type: HEAT_ENV
description: "Auto-generated HEAT Environment deployment artifact"
fileExtension: "env"
-
+ VfHeatEnv:
+ displayName: "VF HEAT ENV"
+ type: HEAT_ENV
+ description: "VF Auto-generated HEAT Environment deployment artifact"
+ fileExtension: "env"
+
#tosca artifacts placeholders
toscaArtifacts:
assetToscaTemplate:
type: TOSCA_CSAR
description: TOSCA definition package of the asset
+
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
resourceSecurityTemplate:
displayName: Resource Security Template
type: OTHER
-
+
excludeServiceCategory:
informationalServiceArtifacts:
serviceSecurityTemplate:
displayName: Service Security Template
type: OTHER
-
+
serviceApiArtifacts:
configuration:
displayName: Configuration
displayName: Testing
type: OTHER
-
additionalInformationMaxNumberOfKeys: 50
systemMonitoring:
MODEL_QUERY_SPEC:
acceptedTypes:
- xml
+#AAI Artifacts
AAI_SERVICE_MODEL:
acceptedTypes:
- xml
- yaml
- yml
validForResourceTypes: *allResourceTypes
- HEAT_NESTED:
+ HEAT_NET:
acceptedTypes:
- yaml
- yml
validForResourceTypes: *allResourceTypes
- HEAT_ARTIFACT:
- acceptedTypes:
- validForResourceTypes: *allResourceTypes
- HEAT_NET:
+ HEAT_NESTED:
acceptedTypes:
- yaml
- yml
validForResourceTypes: *allResourceTypes
+ HEAT_ARTIFACT:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
YANG_XML:
acceptedTypes:
- xml
acceptedTypes:
- xml
validForResourceTypes: *allResourceTypes
+ LIFECYCLE_OPERATIONS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes:
+ - VF
+ - VFC
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ validForResourceTypes: *allResourceTypes
APPC_CONFIG:
acceptedTypes:
validForResourceTypes:
- VF
+ DCAE_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_JSON:
+ acceptedTypes:
+ - json
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_POLICY:
+ acceptedTypes:
+ - emf
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_DOC:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_EVENT:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFCMT
AAI_VF_MODEL:
acceptedTypes:
- xml
SNMP_TRAP:
acceptedTypes:
validForResourceTypes: *allResourceTypes
-
+
resourceInstanceDeploymentArtifacts:
HEAT_ENV:
acceptedTypes:
VF_MODULES_METADATA:
acceptedTypes:
- json
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ DCAE_INVENTORY_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ DCAE_INVENTORY_JSON:
+ acceptedTypes:
+ - json
+ DCAE_INVENTORY_POLICY:
+ acceptedTypes:
+ - emf
+ DCAE_INVENTORY_DOC:
+ acceptedTypes:
+ DCAE_INVENTORY_BLUEPRINT:
+ acceptedTypes:
+ DCAE_INVENTORY_EVENT:
+ acceptedTypes:
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
resourceInformationalDeployedArtifacts:
-
requirementsToFulfillBeforeCert:
- CP:
- - tosca.capabilities.network.Bindable
capabilitiesToConsumeBeforeCert:
-
+
unLoggedUrls:
- /sdc2/rest/healthCheck
artifactsIndex: resources
-cassandraConfig:
- cassandraHosts: ['localhost']
- localDataCenter:
- reconnectTimeout : 30000
- authenticate: false
- username: koko
- password: bobo
- ssl: false
- truststorePath : /path/path
- truststorePassword : 123123
- keySpaces:
- - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
-
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
+
+onboarding:
+ protocol: http
+ host: localhost
+ port: 8080
+ downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
+
+
switchoverDetector:
- gBeFqdn: AIO-BE.ecomp.idns.com
- gFeFqdn: AIO-FE.ecomp.idns.com
+ gBeFqdn: AIO-BE.ecomp.idns.cip.com
+ gFeFqdn: AIO-FE.ecomp.idns.cip.com
beVip: 0.0.0.0
feVip: 0.0.0.0
beResolveAttempts: 3
changePriorityBody: '{"name":"AIO-BE.ecomp.idns.com","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.com","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'}
feSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com?user=root",
changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.com","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com"}'}
-
-
-heatEnvArtifactHeader: ""
-heatEnvArtifactFooter: ""
-
-onboarding:
- protocol: http
- host: localhost
- port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
applicationL1Cache:
datatypes:
- enabled: true
+ enabled: false
firstRunDelay: 10
pollIntervalInSec: 60
applicationL2Cache:
- enabled: false
+ enabled: true
catalogL1Cache:
enabled: true
resourcesSizeInCache: 300
syncIntervalInSecondes: 60
waitOnShutDownInMinutes: 30
numberOfCacheWorkers: 4
+
+toscaValidators:
+ stringMaxLength: 2500
+
+disableAudit: false
+
+vfModuleProperties:
+ min_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ max_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule:
+ initial_count:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ vf_module_type:
+ forBaseModule: Base
+ forNonBaseModule: Expansion
+
genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
+ PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
-
code: 204,
message: "No Content"
}
-#--------POL4050-----------------------------
+#--------POL4050-----------------------------
NOT_ALLOWED: {
code: 405,
message: "Error: Method not allowed.",
messageId: "POL4050"
}
-#--------POL5000-----------------------------
+#--------POL5000-----------------------------
GENERAL_ERROR: {
code: 500,
message: "Error: Internal Server Error. Please try again later.",
messageId: "POL5000"
}
-#---------POL5001------------------------------
+#---------POL5001------------------------------
MISSING_X_ECOMP_INSTANCE_ID: {
code: 400 ,
message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.",
messageId: "POL5001"
}
-#---------POL5002------------------------------
+#---------POL5002------------------------------
AUTH_REQUIRED: {
code: 401 ,
message: "Error: Authentication is required to use the API.",
messageId: "POL5002"
}
-#---------POL5003------------------------------
+#---------POL5003------------------------------
AUTH_FAILED: {
code: 403 ,
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
-#---------POL5004------------------------------
+#---------POL5004------------------------------
MISSING_USER_ID: {
code: 400 ,
message: "Error: Missing 'USER_ID' HTTP header.",
messageId: "POL5004"
}
-#---------SVC4000-----------------------------
+#---------SVC4000-----------------------------
INVALID_CONTENT: {
code: 400,
message: "Error: Invalid content.",
messageId: "SVC4000"
}
-#---------SVC4002-----------------------------
+#---------SVC4002-----------------------------
MISSING_INFORMATION: {
code: 403,
message: "Error: Missing information.",
messageId: "SVC4002"
}
-#---------SVC4003------------------------------
-# %1 - Users's ID
+#---------SVC4003------------------------------
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
messageId: "SVC4003"
}
-#---------SVC4004-----------------------------
-# %1 - Users's email address
+#---------SVC4004-----------------------------
+# %1 - Users's email address
INVALID_EMAIL_ADDRESS: {
code: 400,
message: "Error: Invalid email address '%1'.",
messageId: "SVC4004"
}
-#---------SVC4005------------------------------
+#---------SVC4005------------------------------
# %1 - role
INVALID_ROLE: {
code: 400,
message: "Error: Invalid role '%1'.",
messageId: "SVC4005"
}
-#---------SVC4006------------------------------
-# %1 - Users's USER_ID
+#---------SVC4006------------------------------
+# %1 - Users's USER_ID
USER_ALREADY_EXIST: {
code: 409,
message: "Error: User with '%1' ID already exists.",
messageId: "SVC4006"
}
-#---------SVC4007------------------------------
+#---------SVC4007------------------------------
DELETE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator can only be deleted by another administrator.",
messageId: "SVC4007"
}
-#---------SVC4008-----------------------------
-# %1 - Users's userId
+#---------SVC4008-----------------------------
+# %1 - Users's userId
INVALID_USER_ID: {
code: 400,
message: "Error: Invalid userId '%1'.",
messageId: "SVC4008"
}
-#---------SVC4049------------------------------
+#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
message: "Error: Invalid Content. Missing %1 contact.",
messageId: "SVC4049"
- }
-#---------SVC4050-----------------------------
+ }
+#---------SVC4050-----------------------------
# %1 - Service/Resource/Additional parameter
# %2 - service/resource/label name
COMPONENT_NAME_ALREADY_EXIST: {
message: "Error: %1 with name '%2' already exists.",
messageId: "SVC4050"
}
-#---------SVC4051------------------------------
-# %1 - resource/service
+#---------SVC4051------------------------------
+# %1 - resource/service
COMPONENT_MISSING_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Missing %1 category.",
messageId: "SVC4051"
}
-#---------SVC4052------------------------------
+#---------SVC4052------------------------------
COMPONENT_MISSING_TAGS: {
code: 400,
message: "Error: Invalid Content. At least one tag has to be specified.",
messageId: "SVC4052"
}
-#---------SVC4053------------------------------
+#---------SVC4053------------------------------
# %1 - service/resource
COMPONENT_MISSING_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. Missing %1 description.",
messageId: "SVC4053"
}
-#---------SVC4054------------------------------
+#---------SVC4054------------------------------
# %1 - resource/service
COMPONENT_INVALID_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 category.",
messageId: "SVC4054"
}
-#---------SVC4055------------------------------
+#---------SVC4055------------------------------
MISSING_VENDOR_NAME: {
code: 400,
message: "Error: Invalid Content. Missing vendor name.",
messageId: "SVC4055"
}
-#---------SVC4056------------------------------
+#---------SVC4056------------------------------
MISSING_VENDOR_RELEASE: {
code: 400,
message: "Error: Invalid Content. Missing vendor release.",
messageId: "SVC4056"
}
-#---------SVC4057------------------------------
+#---------SVC4057------------------------------
MISSING_DERIVED_FROM_TEMPLATE: {
code: 400,
message: "Error: Invalid Content. Missing derived from template specification.",
messageId: "SVC4057"
}
-#---------SVC4058------------------------------
+#---------SVC4058------------------------------
# %1 - service/resource
COMPONENT_MISSING_ICON: {
code: 400,
message: "Error: Invalid Content. Missing %1 icon.",
messageId: "SVC4058"
}
-#---------SVC4059------------------------------
+#---------SVC4059------------------------------
# %1 - service/resource
COMPONENT_INVALID_ICON: {
code: 400,
message: "Error: Invalid Content. Invalid %1 icon.",
messageId: "SVC4059"
}
-#---------SVC4060------------------------------
+#---------SVC4060------------------------------
PARENT_RESOURCE_NOT_FOUND: {
code: 400,
message: "Error: Invalid Content. Derived from resource template was not found.",
messageId: "SVC4060"
}
-#---------SVC4061------------------------------
+#---------SVC4061------------------------------
MULTIPLE_PARENT_RESOURCE_FOUND: {
code: 400,
message: "Error: Invalid Content. Multiple derived from resource template is not allowed.",
messageId: "SVC4061"
}
-#---------SVC4062------------------------------
+#---------SVC4062------------------------------
# %1 - service/resource
MISSING_COMPONENT_NAME: {
code: 400,
message: "Error: Invalid Content. Missing %1 name.",
messageId: "SVC4062"
}
-#---------SVC4063------------------------------
+#---------SVC4063------------------------------
#%1 - resource/service name
RESOURCE_NOT_FOUND: {
code: 404,
messageId: "SVC4063"
}
-#---------SVC4064------------------------------
+#---------SVC4064------------------------------
# %1 - Service/Resource/Property
COMPONENT_INVALID_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. %1 description contains non-english characters.",
messageId: "SVC4064"
}
-#---------SVC4065------------------------------
+#---------SVC4065------------------------------
# %1 - Service/Resource/Property
-# %2 - max resource/service name length
+# %2 - max resource/service name length
COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 description exceeds limit of %2 characters.",
messageId: "SVC4065"
}
-#---------SVC4066------------------------------
-# %1 - max length
+#---------SVC4066------------------------------
+# %1 - max length
COMPONENT_TAGS_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.",
messageId: "SVC4066"
}
#---------SVC4067------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor name exceeds limit of %1 characters.",
messageId: "SVC4067"
}
#---------SVC4068------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_RELEASE_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.",
messageId: "SVC4068"
}
-#---------SVC4069------------------------------
+#---------SVC4069------------------------------
# %1 - Service/Resource/Product
COMPONENT_INVALID_CONTACT: {
code: 400,
- message: "Error: Invalid Content. %1 Contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
+ message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
-#---------SVC4070------------------------------
+#---------SVC4070------------------------------
# %1 - Service/Resource
INVALID_COMPONENT_NAME: {
code: 400,
messageId: "SVC4070"
}
-#---------SVC4071------------------------------
+#---------SVC4071------------------------------
INVALID_VENDOR_NAME: {
code: 400,
message: 'Error: Invalid Content. Vendor name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4071"
}
-#---------SVC4072------------------------------
+#---------SVC4072------------------------------
INVALID_VENDOR_RELEASE: {
code: 400,
message: 'Error: Invalid Content. Vendor release is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4072"
}
-#---------SVC4073------------------------------
+#---------SVC4073------------------------------
# %1 - Service/Resource
-# %2 - max resource/service name
+# %2 - max resource/service name
COMPONENT_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 name exceeds limit of %2 characters.",
messageId: "SVC4073"
}
-#---------SVC4080------------------------------
+#---------SVC4080------------------------------
# %1 - resource/service name
# %2Â - resource/service
# %3 - First name of last modifier
message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).",
messageId: "SVC4080"
}
-#---------SVC4081-----------------------------
+#---------SVC4081-----------------------------
# %1 - resource/service name
# %2Â - resource/service
# %3 - First name of last modifier
messageId: "SVC4081"
}
-#-----------SVC4082---------------------------
+#-----------SVC4082---------------------------
# %1 - resource/service name
# %2Â - resource/service
# %3 - First name of last modifier
}
#-----------SVC4102---------------------------
-# %1Â -Â capability type name
+# %1Â -Â capability type name
CAPABILITY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Capability Type with name '%1' already exists.",
messageId: "SVC4114"
}
#-----------SVC4115---------------------------
-# %1Â -Â capability type name
+# %1Â -Â capability type name
MISSING_CAPABILITY_TYPE: {
code: 400,
message: "Error: Invalid Content. Missing Capability Type '%1'.",
message: "Error: Artifact '%1' already exists.",
messageId: "SVC4125"
}
-#---------SVC4126------------------------------
+#---------SVC4126------------------------------
# %1Â - resource/service/product/...
# %2Â - field (tag, vendor name...)
INVALID_FIELD_FORMAT: {
#-----------SVC4131---------------------------
# %1-resource/service
# %2-srtifact/artifacts
-# %3-semicolomn separated list of artifact
+# %3-semicolomn separated list of artifact
COMPONENT_MISSING_MANDATORY_ARTIFACTS: {
code: 403,
message: "Error: Missing mandatory informational %1 %2: [%3].",
message: "Error: Invalid Content. Missing interface life-cycle type.",
messageId: "SVC4134"
}
-#---------SVC4135------------------------------
+#---------SVC4135------------------------------
SERVICE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service category cannot be changed once the service is certified.",
messageId: "SVC4135"
}
-#---------SVC4136------------------------------
-# %1 - distribution environment name
+#---------SVC4136------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: {
code: 500,
message: "Error: Requested distribution environment '%1' is not available.",
messageId: "SVC4136"
}
-#---------SVC4137------------------------------
-# %1 - distribution environment name
+#---------SVC4137------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_FOUND: {
code: 400,
message: "Error: Requested distribution environment '%1' was not found.",
messageId: "SVC4137"
}
-#---------SVC4138------------------------------
+#---------SVC4138------------------------------
DISTRIBUTION_ENVIRONMENT_INVALID: {
code: 400,
message: "Error: Invalid distribution environment.",
messageId: "SVC4138"
}
-#---------SVC4139------------------------------
+#---------SVC4139------------------------------
# %1 - service name
DISTRIBUTION_ARTIFACT_NOT_FOUND: {
code: 409,
message: "Error: Service '%1' cannot be distributed due to missing deployment artifacts.",
messageId: "SVC4139"
}
-#---------SVC4200------------------------------
+#---------SVC4200------------------------------
# %1 - Service/Resource
-# %2 - max icon name length
+# %2 - max icon name length
COMPONENT_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 icon name exceeds limit of %2 characters.",
messageId: "SVC4200"
}
-#---------SVC4300------------------------------
+#---------SVC4300------------------------------
RESTRICTED_ACCESS: {
code: 403,
message: "Error: Restricted access.",
messageId: "SVC4300"
}
-#---------SVC4301------------------------------
+#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
code: 409,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
-#---------SVC4500------------------------------
+#---------SVC4500------------------------------
MISSING_BODY: {
code: 400 ,
message: "Error: Missing request body.",
message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." ,
messageId: "SVC4501"
}
-#---------SVC4502------------------------------
+#---------SVC4502------------------------------
DISTRIBUTION_ENV_DOES_NOT_EXIST: {
code: 400 ,
message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." ,
messageId: "SVC4503"
}
-#---------SVC4504------------------------------
+#---------SVC4504------------------------------
# %1 - Service/Resource
# %2 - service/resource version
COMPONENT_VERSION_NOT_FOUND: {
}
#-----------SVC4505---------------------------
#%1-artifact name
-
+
ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Artifact '%1' was not found.",
messageId: "SVC4505"
}
-#---------SVC4506------------------------------
+#---------SVC4506------------------------------
MISSING_ENV_NAME: {
code: 400 ,
message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.",
messageId: "SVC4506"
}
-#---------SVC4507------------------------------
+#---------SVC4507------------------------------
COMPONENT_INVALID_TAGS_NO_COMP_NAME: {
code: 400,
message: "Error: Invalid Content. One of the tags should be the component name.",
messageId: "SVC4507"
}
-
-#---------SVC4508------------------------------
+
+#---------SVC4508------------------------------
SERVICE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service name cannot be changed once the service is certified.",
messageId: "SVC4508"
}
-#---------SVC4509------------------------------
+#---------SVC4509------------------------------
SERVICE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the service is certified.",
messageId: "SVC4509"
}
-#---------SVC4510------------------------------
+#---------SVC4510------------------------------
# %1 - icon name max length
SERVICE_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Icon name exceeds limit of %1 characters.",
messageId: "SVC4510"
}
-#---------SVC4511------------------------------
+#---------SVC4511------------------------------
DISTRIBUTION_REQUESTED_NOT_FOUND: {
code: 404,
message: "Error: Requested distribution was not found.",
messageId: "SVC4511"
}
-#---------SVC4512------------------------------
+#---------SVC4512------------------------------
# %1 - Distribution ID
DISTRIBUTION_REQUESTED_FAILED: {
code: 403,
message: "Error: Requested distribution '%1' failed.",
messageId: "SVC4512"
}
-#---------SVC4513------------------------------
+#---------SVC4513------------------------------
RESOURCE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource category cannot be changed once the resource is certified.",
messageId: "SVC4513"
}
-#---------SVC4514------------------------------
+#---------SVC4514------------------------------
RESOURCE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource name cannot be changed once the resource is certified.",
messageId: "SVC4514"
}
-#---------SVC4515------------------------------
+#---------SVC4515------------------------------
RESOURCE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the resource is certified.",
messageId: "SVC4515"
}
-#---------SVC4516------------------------------
+#---------SVC4516------------------------------
RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Vendor name cannot be changed once the resource is certified.",
messageId: "SVC4516"
}
-#---------SVC4517------------------------------
+#---------SVC4517------------------------------
RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Derived from resource template cannot be changed once the resource is certified.",
messageId: "SVC4517"
}
-#---------SVC4518------------------------------
-# %1 - max length
+#---------SVC4518------------------------------
+# %1 - max length
COMPONENT_SINGLE_TAG_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.",
messageId: "SVC4518"
}
-#---------SVC4519------------------------------
+#---------SVC4519------------------------------
INVALID_DEFAULT_VALUE: {
code: 400,
message: "Error: mismatch in data-type occurred for property %1. data type is %2 and default value found is %3.",
messageId: "SVC4519"
}
-#---------SVC4520------------------------------
-# %1 - service or resource
+#---------SVC4520------------------------------
+# %1 - service or resource
ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: {
code: 409,
message: "Error: Maximal number of additional %1 parameters was reached.",
message: "Error: Invalid Content. The Additional information label and value cannot be empty.",
messageId: "SVC4521"
}
-#---------SVC4522------------------------------
+#---------SVC4522------------------------------
# %1 - label/value
# %2 - Maximal length of %1
ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: {
message: "Error: Requested additional information was not found.",
messageId: "SVC4524"
}
-#---------SVC4525------------------------------
+#---------SVC4525------------------------------
ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: {
code: 400,
message: 'Error: Invalid Content. Additional information contains non-english characters.',
messageId: "SVC4525"
}
-#---------SVC4526------------------------------
+#---------SVC4526------------------------------
RESOURCE_INSTANCE_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' resource instance was not found.",
messageId: "SVC4526"
}
-#---------SVC4527------------------------------
+#---------SVC4527------------------------------
ASDC_VERSION_NOT_FOUND: {
code: 500,
message: 'Error: ASDC version cannot be displayed.',
messageId: "SVC4527"
}
-#---------SVC4528------------------------------
+#---------SVC4528------------------------------
# %1-artifact url/artifact label/artifact description/VNF Service Indicator
MISSING_DATA: {
code: 400,
message: "Error: Invalid content. Missing %1.",
messageId: "SVC4528"
}
-#---------SVC4529------------------------------
+#---------SVC4529------------------------------
# %1-artifact url/artifact label/artifact description/artifact name
# %2 - Maximal length of %1
EXCEEDS_LIMIT: {
message: "Error: Invalid Content. %1 exceeds limit of %2 characters.",
messageId: "SVC4529"
}
-#---------SVC4530------------------------------
+#---------SVC4530------------------------------
ARTIFACT_INVALID_TIMEOUT: {
code: 400,
message: "Error: Invalid Content. Artifact Timeout should be set to valid positive non-zero number of minutes.",
messageId: "SVC4530"
}
-#---------SVC4531------------------------------
+#---------SVC4531------------------------------
SERVICE_IS_VNF_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: VNF Indicator cannot be updated for certified service.",
messageId: "SVC4531"
}
- #---------SVC4532------------------------------
+ #---------SVC4532------------------------------
RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE: {
code: 404,
message: "Error: Requested '%1' resource instance was not found on the service '%2.",
messageId: "SVC4532"
}
- #---------SVC4533------------------------------
- # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
+ #---------SVC4533------------------------------
+ # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
WRONG_ARTIFACT_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for %1 artifact type.",
messageId: "SVC4533"
}
-#---------SVC4534------------------------------
-# %1 - "HEAT"/"HEAT_ENV"
+#---------SVC4534------------------------------
+# %1 - "HEAT"/"HEAT_ENV"
INVALID_YAML: {
code: 400,
message: "Error: Uploaded YAML file for %1 artifact is invalid.",
messageId: "SVC4534"
}
-#---------SVC4535------------------------------
-# %1 - "HEAT"
+#---------SVC4535------------------------------
+# %1 - "HEAT"
INVALID_DEPLOYMENT_ARTIFACT_HEAT: {
code: 400,
message: "Error: Invalid %1 artifact.",
messageId: "SVC4535"
}
-#---------SVC4536------------------------------
+#---------SVC4536------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
+# %2 - resource/service name
+# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG
DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: {
code: 400,
messageId: "SVC4536"
}
-#---------SVC4537------------------------------
+#---------SVC4537------------------------------
MISSING_HEAT: {
code: 400,
message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.",
messageId: "SVC4537"
}
-#---------SVC4538------------------------------
+#---------SVC4538------------------------------
MISMATCH_HEAT_VS_HEAT_ENV: {
code: 400,
message: "Error: Invalid artifact content. Parameter's set in HEAT_ENV '%1' artifact doesn't match the parameters in HEAT '%2' artifact.",
messageId: "SVC4538"
}
-#---------SVC4539------------------------------
+#---------SVC4539------------------------------
INVALID_RESOURCE_PAYLOAD: {
code: 400,
message: "Error: Invalid resource payload.",
messageId: "SVC4539"
}
-#---------SVC4540------------------------------
+#---------SVC4540------------------------------
INVALID_TOSCA_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for TOSCA template.",
messageId: "SVC4540"
}
-#---------SVC4541------------------------------
+#---------SVC4541------------------------------
INVALID_YAML_FILE: {
code: 400,
message: "Error: Invalid YAML file.",
messageId: "SVC4541"
}
-#---------SVC4542------------------------------
+#---------SVC4542------------------------------
INVALID_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Invalid TOSCA template.",
messageId: "SVC4542"
}
-#---------SVC4543------------------------------
+#---------SVC4543------------------------------
NOT_RESOURCE_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Imported Service TOSCA template.",
messageId: "SVC4543"
}
-#---------SVC4544------------------------------
+#---------SVC4544------------------------------
NOT_SINGLE_RESOURCE: {
code: 400,
message: "Error: Imported TOSCA template should contain one resource definition.",
messageId: "SVC4544"
}
-#---------SVC4545------------------------------
+#---------SVC4545------------------------------
INVALID_RESOURCE_NAMESPACE: {
code: 400,
message: "Error: Invalid resource namespace.",
messageId: "SVC4545"
}
-#---------SVC4546------------------------------
+#---------SVC4546------------------------------
RESOURCE_ALREADY_EXISTS: {
code: 400,
message: "Error: Imported resource already exists in ASDC Catalog.",
messageId: "SVC4546"
}
-#---------SVC4549------------------------------
+#---------SVC4549------------------------------
INVALID_RESOURCE_CHECKSUM: {
code: 400,
message: "Error: Invalid resource checksum.",
messageId: "SVC4549"
}
-#---------SVC4550------------------------------
+#---------SVC4550------------------------------
#%1Â -Â Consumer salt
INVALID_LENGTH: {
code: 400,
message: "Error: Invalid %1 length.",
messageId: "SVC4550"
}
- #---------SVC4551------------------------------
+ #---------SVC4551------------------------------
#%1Â -Â ECOMP User name
ECOMP_USER_NOT_FOUND: {
code: 404,
messageId: "SVC4552"
}
#---------SVC4553-----------------------------
- #%1Â -Â Consumer name / Consumer password/ Consumer salt
+ #%1Â -Â Consumer name / Consumer password/ Consumer salt
INVALID_CONTENT_PARAM: {
code: 400,
message: "Error: %1 is invalid.",
messageId: "SVC4553"
}
- #---------SVC4554------------------------------
+ #---------SVC4554------------------------------
# %1 - "Resource"/"Service"
COMPONENT_ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.",
messageId: "SVC4554"
}
-#---------SVC4555------------------------------
+#---------SVC4555------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_LENGTH: {
message: "Error: Invalid %1 %2 name length.",
messageId: "SVC4555"
}
-#---------SVC4556------------------------------
+#---------SVC4556------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_FORMAT: {
message: "Error: Invalid %1 %2 name format.",
messageId: "SVC4556"
}
-#---------SVC4557------------------------------
+#---------SVC4557------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category name"
COMPONENT_CATEGORY_ALREADY_EXISTS: {
code: 403,
message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use one of available validated resource versions.",
messageId: "SVC4560"
- }
+ }
#---------SVC4561------------------------------
# %1 - "resource"/"product"
# %2 - "category"
message: "Error: %1 grouping '%2' already exists under '%3' sub-category.",
messageId: "SVC4563"
}
-#---------SVC4564------------------------------
+#---------SVC4564------------------------------
# %1 - product name
PRODUCT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' product was not found.",
messageId: "SVC4564"
}
-#---------SVC4565------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4565------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
# %3 - parameter name
INVALID_HEAT_PARAMETER_VALUE: {
code: 400,
message: "Error: Invalid %1 artifact. Invalid %2 value set for '%3' parameter.",
messageId: "SVC4565"
}
-#---------SVC4566------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4566------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
INVALID_HEAT_PARAMETER_TYPE: {
code: 400,
message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.",
messageId: "SVC4566"
}
-#---------SVC4567------------------------------
-# %1 - "YANG_XML"
+#---------SVC4567------------------------------
+# %1 - "YANG_XML"
INVALID_XML: {
code: 400,
message: "Error: Uploaded XML file for %1 artifact is invalid.",
messageId: "SVC4567"
}
-#---------SVC4567------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4567------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: User cannot be deleted. User '%1' has %2 projects.",
messageId: "SVC4567"
}
-#---------SVC4568------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4568------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: Role cannot be changed. User '%1' has %2 projects.",
messageId: "SVC4568"
}
-#---------SVC4570------------------------------
+#---------SVC4570------------------------------
UPDATE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator is not allowed to change his/her role.",
messageId: "SVC4570"
}
-#---------SVC4571------------------------------
+#---------SVC4571------------------------------
SERVICE_CANNOT_CONTAIN_SUBCATEGORY: {
code: 400,
message: "Error: Sub category cannot be defined for service",
messageId: "SVC4571"
}
-#---------SVC4572------------------------------
+#---------SVC4572------------------------------
# %1 - "Resource"/"Service"
COMPONENT_TOO_MUCH_CATEGORIES: {
code: 400,
message: "Error: %1 must have only 1 category",
messageId: "SVC4572"
}
-#---------SVC4574------------------------------
+#---------SVC4574------------------------------
RESOURCE_TOO_MUCH_SUBCATEGORIES: {
code: 400,
message: "Error: Resource must have only 1 sub category",
messageId: "SVC4574"
}
-#---------SVC4575------------------------------
+#---------SVC4575------------------------------
COMPONENT_MISSING_SUBCATEGORY: {
code: 400,
message: "Error: Missing sub category",
messageId: "SVC4575"
}
- #---------SVC4576------------------------------
+ #---------SVC4576------------------------------
# %1 - "component type"
UNSUPPORTED_ERROR: {
code: 400,
message: "Error : Requested component type %1 is unsupported.",
messageId: "SVC4576"
}
- #---------SVC4577------------------------------
+ #---------SVC4577------------------------------
# %1 - "resource type"
RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: {
code: 409,
message: "Error : Resource of type %1 cannot contain resource instances.",
messageId: "SVC4577"
}
-#---------SVC4578------------------------------
+#---------SVC4578------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "artifact name"
+# %2 - resource/service name
+# %3 - "artifact name"
DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS: {
code: 400,
message: "Error: %1 '%2' already has a deployment artifact named '%3'.",
messageId: "SVC4578"
}
-#---------SVC4579------------------------------
+#---------SVC4579------------------------------
# %1 - "Category"/"Sub-Category"/"Group"
# %2 - category/sub-category/grouping name.
INVALID_GROUP_ASSOCIATION: {
message: "Error: Invalid group association. %1 '%2' was not found.",
messageId: "SVC4579"
}
-#---------SVC4580------------------------------
+#---------SVC4580------------------------------
EMPTY_PRODUCT_CONTACTS_LIST: {
code: 400,
message: "Error: Invalid content. At least one Product Contact has to be specified.",
messageId: "SVC4580"
}
-#---------SVC4581------------------------------
-# %1 - userId
+#---------SVC4581------------------------------
+# %1 - UserId
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
messageId: "SVC4581"
}
-#---------SVC4582------------------------------
+#---------SVC4582------------------------------
# %1 - Product
# %2 - "abbreviated"/"full"
MISSING_ONE_OF_COMPONENT_NAMES: {
code: 400,
message: "Error: Invalid content. Missing %1 %2 name.",
messageId: "SVC4582"
- }
+ }
#---------SVC4583------------------------------
# %1 - "Icon"
# %2 - "resource"/"service"/"product"
messageId: "SVC4583"
}
#---------SVC4584------------------------------
-# %1 - service/VF name
+# %1 - service/VF name
# %2 - "service" /"VF"
# %3 - resource instance origin type
-# %4 - resource instance name
+# %4 - resource instance name
# %5 - requirement/capability
# %6 - requirement/capability name
# %7 - "fulfilled" (for req)/"consumed (for cap)"
message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.",
messageId: "SVC4584"
}
-#---------SVC4585------------------------------
+#---------SVC4585------------------------------
INVALID_OCCURRENCES: {
code: 400,
message: "Error: Invalid occurrences format.",
messageId: "SVC4585"
}
-#---------SVC4586------------------------------
-#---------SVC4586------------------------------
+#---------SVC4586------------------------------
+#---------SVC4586------------------------------
INVALID_SERVICE_API_URL: {
code: 400,
message: 'Error: Invalid Service API URL. Please check whether your URL has a valid domain extension and does not contain the following characters - #?&@%+;,=$<>~^`\[]{}|"*!',
messageId: "SVC4586"
}
-#---------SVC4587------------------------------
-# %1 - Data type name
+#---------SVC4587------------------------------
+# %1 - Data type name
DATA_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Data type %1 already exists.',
messageId: "SVC4587"
}
-#---------SVC4588------------------------------
-# %1 - Data type name
+#---------SVC4588------------------------------
+# %1 - Data type name
DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: {
code: 400,
message: 'Error: Invalid Data type %1. Data type must have either a valid derived from declaration or at least one valid property',
messageId: "SVC4588"
}
-#---------SVC4589------------------------------
-# %1 - Data type name
+#---------SVC4589------------------------------
+# %1 - Data type name
DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: {
code: 400,
message: "Error: Invalid Data type %1. 'properties' parameter cannot be empty if provided.",
messageId: "SVC4589"
}
-#---------SVC4590------------------------------
-# %1 - Property type name
+#---------SVC4590------------------------------
+# %1 - Property type name
# %2 - Property name
INVALID_PROPERTY_TYPE: {
code: 400,
message: "Error: Invalid Property type %1 in property %2.",
messageId: "SVC4590"
}
-#---------SVC4591------------------------------
+#---------SVC4591------------------------------
# %1 - Property inner type
-# %2 - Property name
+# %2 - Property name
INVALID_PROPERTY_INNER_TYPE: {
code: 400,
message: "Error: Invalid property inner type %1, in property %2",
messageId: "SVC4591"
}
-#---------SVC4592------------------------------
+#---------SVC4592------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
COMPONENT_INSTANCE_NOT_FOUND: {
message: "Error: Requested '%1' %2 was not found.",
messageId: "SVC4592"
}
-#---------SVC4593------------------------------
+#---------SVC4593------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
# %3 - "resource/"service"/"product"
-# %4 - container name
+# %4 - container name
COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: {
code: 404,
message: "Error: Requested '%1' %2 was not found on the %3 '%4'.",
#---------SVC4595------------------------------
#%1 - requirement / capability
#%2 - requirement name
-#%3 - parent containing the requirement
+#%3 - parent containing the requirement
IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED: {
code: 400,
message: "Error: Imported TOSCA template contains %1 '%2' that is already defined by derived template %3.",
messageId: "SVC4595"
}
-#---------SVC4596------------------------------
+#---------SVC4596------------------------------
# %1 - Data type name
DATA_TYPE_DERIVED_IS_MISSING: {
code: 400,
message: "Error: Invalid Content. The ancestor data type %1 cannot be found in the system.",
messageId: "SVC4596"
}
-#---------SVC4597------------------------------
+#---------SVC4597------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: {
message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.",
messageId: "SVC4597"
}
-#---------SVC4598------------------------------
+#---------SVC4598------------------------------
# %1 - Data type name
DATA_TYPE_DUPLICATE_PROPERTY: {
code: 400,
message: "Error: Invalid Content. The data type %1 contains duplicate property.",
messageId: "SVC4598"
}
-#---------SVC4599------------------------------
+#---------SVC4599------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: {
message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.",
messageId: "SVC4599"
}
-#---------SVC4600------------------------------
+#---------SVC4600------------------------------
# %1 - Data type name
DATA_TYPE_CANNOT_HAVE_PROPERTIES: {
code: 400,
message: "Error: Invalid Content. The data type %1 cannot have properties since it is of type scalar",
messageId: "SVC4600"
}
-#---------SVC4601------------------------------
+#---------SVC4601------------------------------
NOT_TOPOLOGY_TOSCA_TEMPLATE: {
code: 400,
message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.",
message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL",
messageId: "SVC4602"
}
-#---------SVC4603------------------------------
+#---------SVC4603------------------------------
# %1Â -Â component type
# %2 - component name
# %3Â - state
message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.",
messageId: "SVC4603"
}
-#---------SVC4604------------------------------
+#---------SVC4604------------------------------
# %1Â -Â csar file name
CSAR_INVALID: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. 'TOSCA-Metadata/Tosca.meta' file must be provided.",
messageId: "SVC4604"
}
-#---------SVC4605------------------------------
+#---------SVC4605------------------------------
# %1Â -Â csar file name
CSAR_INVALID_FORMAT: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. Invalid 'TOSCA-Metadata/Tosca.meta' file format.",
messageId: "SVC4605"
}
-#---------SVC4606------------------------------
+#---------SVC4606------------------------------
# %1Â -Â property name
# %2Â - property type
# %3 - property innerType
message: "Error: Invalid default value of property %1. Data type is %2 with inner type %3 and default value found is %4.",
messageId: "SVC4606"
}
-#---------SVC4607------------------------------
+#---------SVC4607------------------------------
# %1Â -Â csar file name
CSAR_NOT_FOUND: {
code: 400,
message: "Error: TOSCA CSAR '%1' is not found.",
messageId: "SVC4607"
}
-#---------SVC4608------------------------------
+#---------SVC4608------------------------------
# %1Â -Â artifact name
# %2Â - component type
# %3 - actual component type
messageId: "SVC4608"
}
-#---------SVC4609------------------------------
-# %1 - "INVALID_JSON"
+#---------SVC4609------------------------------
+# %1 - "INVALID_JSON"
INVALID_JSON: {
code: 400,
message: "Error: Uploaded JSON file for %1 artifact is invalid.",
messageId: "SVC4609"
}
-#---------SVC4610------------------------------
+#---------SVC4610------------------------------
# %1Â -Â csar file name
# %2Â -Â missing file name
YAML_NOT_FOUND_IN_CSAR: {
message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.",
messageId: "SVC4610"
}
-#---------SVC4611------------------------------
+#---------SVC4611------------------------------
# %1 - group name
GROUP_MEMBER_EMPTY: {
code: 400,
message: "Error: Invalid Content. Group %1 member list was provided but does not have values",
messageId: "SVC4611"
}
-#---------SVC4612------------------------------
-# %1 - group name
+#---------SVC4612------------------------------
+# %1 - group name
GROUP_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Group type %1 already exists.',
messageId: "SVC4612"
}
-#---------SVC4613------------------------------
+#---------SVC4613------------------------------
# %1Â -Â group name
# %2Â - VF name(component name)
# %3 - actual component type [VF]
code: 409,
message: "Error: Group with name '%1' already exists in %2 %3.",
messageId: "SVC4613"
- }
-#---------SVC4614------------------------------
+ }
+#---------SVC4614------------------------------
# %1Â -Â group type
GROUP_TYPE_IS_INVALID: {
code: 400,
message: "Error: Invalid content. Group type %1 does not exist",
messageId: "SVC4614"
}
-#---------SVC4615------------------------------
+#---------SVC4615------------------------------
# %1Â -Â group name
GROUP_MISSING_GROUP_TYPE: {
code: 400,
code: 400,
message: "Error: Member '%1' listed in group '%2' is not part of '%3' %4.",
messageId: "SVC4616"
- }
+ }
#---------SVC4617------------------------------
# %1 - member name
# %2 - group name
message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.",
messageId: "SVC4617"
}
-#---------SVC4618------------------------------
+#---------SVC4618------------------------------
# %1Â -Â missing file name
# %2Â -Â csar file name
ARTIFACT_NOT_FOUND_IN_CSAR: {
message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided",
messageId: "SVC4618"
}
-#---------SVC4619------------------------------
+#---------SVC4619------------------------------
# %1Â - artifact name
# %2Â -Â artifact type
# %3 - existing artifact type
message: "Error: artifact %1 in type %2 already exists in type %3.",
messageId: "SVC4619"
}
-#---------SVC4620------------------------------
+#---------SVC4620------------------------------
FAILED_RETRIVE_ARTIFACTS_TYPES: {
code: 400,
message: "Error: Failed to retrieve list of suported artifact types.",
messageId: "SVC4620"
}
-#---------SVC4621------------------------------
+#---------SVC4621------------------------------
# %1Â - artifact name
-# %2Â - master
+# %2Â - master
ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: {
code: 400,
message: "Error: artifact %1 already exists in master %2 .",
messageId: "SVC4621"
}
-#---------SVC4622------------------------------
+#---------SVC4622------------------------------
# %1Â - artifact name
-# %2Â - artifact type
+# %2Â - artifact type
# %3Â - master name
# %4 - master type
ARTIFACT_NOT_VALID_IN_MASTER: {
message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.",
messageId: "SVC4622"
}
-#---------SVC4623------------------------------
+#---------SVC4623------------------------------
# %1Â - artifact name
-# %2Â - artifact type
+# %2Â - artifact type
# %3Â - env name
# %4 - existing env
ARTIFACT_NOT_VALID_ENV: {
message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4",
messageId: "SVC4623"
}
-#---------SVC4624------------------------------
+#---------SVC4624------------------------------
# %1Â -Â groups names
# %2 - VF name
# %3 - component type [VF ]
message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.",
messageId: "SVC4624"
}
-#---------SVC4625------------------------------
+#---------SVC4625------------------------------
# %1Â -Â groups name
GROUP_ARTIFACT_ALREADY_ASSOCIATED: {
code: 400,
message: "Error: Invalid Content. Artifact already associated to group '%1'.",
messageId: "SVC4625"
}
-#---------SVC4626------------------------------
+#---------SVC4626------------------------------
# %1Â -Â groups name
GROUP_ARTIFACT_ALREADY_DISSOCIATED: {
code: 400,
message: "Error: property %1 listed in group %2 is not exist in group type %3.",
messageId: "SVC4627"
}
-#---------SVC4628------------------------------
+#---------SVC4628------------------------------
# %1 - csarUUID
# %2 - VF name
VSP_ALREADY_EXISTS: {
message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.",
messageId: "SVC4628"
}
-#---------SVC4629------------------------------
+#---------SVC4629------------------------------
# %1 - VF name
MISSING_CSAR_UUID: {
code: 400,
message: "Error: The Csar UUID or payload name is missing for VF %1.",
messageId: "SVC4629"
}
-#---------SVC4630------------------------------
+#---------SVC4630------------------------------
# %1 - VF name
# %2 - new csarUUID
# %3 - old csarUUID
message: "Error: Resource %1 cannot be updated using CsarUUID %2 since the resource is linked to a different VSP with csarUUID %3.",
messageId: "SVC4630"
}
-#---------SVC4631------------------------------
-# %1 - policy name
+#---------SVC4631------------------------------
+# %1 - policy name
POLICY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Policy type %1 already exists.",
code: 404,
message: "Error: Requested '%1' attribute was not found.",
messageId: "SVC4637"
- }
+ }
#-----------SVC4638---------------------------
#%1 - attribute name
ATTRIBUTE_ALREADY_EXIST: {
message: "Error: Invalid Content. VF Module name '%1' contains invalid characters",
messageId: "SVC4646"
}
-
+
#---------SVC4647------------------------------
# %1 - "modifiedName"
INVALID_VF_MODULE_NAME_MODIFICATION: {
message: "Error: Once resource is certified, derived_from can be changed only to a sibling",
messageId: "SVC4651"
}
-#---------SVC4652------------------------------
+#---------SVC4652------------------------------
# %1 - resource/service
COMPONENT_INVALID_SUBCATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 sub category.",
messageId: "SVC4652"
}
-#---------SVC4653------------------------------
-# %1 - group instance uniqueId
+#---------SVC4653------------------------------
+# %1 - group instance uniqueId
# %2 - service uniqueId
GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE: {
code: 404,
message: "Error: Requested group instance %1 was not found on component %2.",
messageId: "SVC4653"
}
-#---------SVC4654------------------------------
-# %1 - group property name
+#---------SVC4654------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: {
message: "Error: Value of %1 must be not higher than %2, and not lower than %3.",
messageId: "SVC4654"
}
-#---------SVC4655------------------------------
-# %1 - group property name
+#---------SVC4655------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: {
message: "Error: Value of %1 must be between %2 and %3.",
messageId: "SVC4655"
}
-#---------SVC4656------------------------------
-# %1 - group property name
+#---------SVC4656------------------------------
+# %1 - group property name
# %2 - lower/higher
# %3 - valid max/min value
INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER: {
code: 400,
message: "Error: Value of %1 must be %2 or equals to %3.",
messageId: "SVC4656"
- }
+ }
#---------SVC4657------------------------------
# %1 - certificationRequest / startTesting
RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID: {
# %1 – asset type [service / resource ]
# %2 – main asset uuid
# %3 – not found asset type [service / resource]
-# %4 – not found asset name
+# %4 – not found asset name
ASSET_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
message: "Error: CSAR packaging failed for %1 %2. %3 %4 was not found",
#---------SVC4659------------------------------
# %1 – asset type [service / resource ]
# %2 – main asset uuid
-# %3 – Artifact name
+# %3 – Artifact name
# %4 – Artifact uuid
ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
- message: " Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found",
+ message: "Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found",
messageId: "SVC4659"
+ }
+#---------SVC4660------------------------------
+# %1 - assetType
+# %2 - matching generic node type name
+ GENERIC_TYPE_NOT_FOUND: {
+ code: 404,
+ message: "Creation of %1 failed. Generic type %2 was not found",
+ messageId: "SVC4660"
+ }
+#---------SVC4661------------------------------
+# %1 - assetType
+# %2 - matching generic node type name
+ TOSCA_SCHEMA_FILES_NOT_FOUND: {
+ code: 400,
+ message: "Error: CSAR packaging failed. TOSCA schema files for SDC-Version: %1 and Conformance-Level %2 were not found",
+ messageId: "SVC4661"
+ }
+#---------SVC4662------------------------------
+# %1 - file name
+# %2 - parser error
+ TOSCA_PARSE_ERROR: {
+ code: 400,
+ message: "Error: Invalid TOSCA template in file %1. %2",
+ messageId: "SVC4662"
+ }
+#---------SVC4663------------------------------
+# %1 - max length
+ RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Resource vendor model number exceeds limit of %1 characters.",
+ messageId: "SVC4663"
+ }
+#---------SVC4664------------------------------
+ INVALID_RESOURCE_VENDOR_MODEL_NUMBER: {
+ code: 400,
+ message: 'Error: Invalid Content. Resource vendor model number is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4664"
+ }
+#---------SVC4665------------------------------
+# %1 - max length
+ SERVICE_TYPE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service type exceeds limit of %1 characters.",
+ messageId: "SVC4665"
+ }
+#---------SVC4666------------------------------
+ INVALID_SERVICE_TYPE: {
+ code: 400,
+ message: 'Error: Invalid Content. Serivce type is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4666"
+ }
+#---------SVC4667------------------------------
+# %1 - max length
+ SERVICE_ROLE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service role exceeds limit of %1 characters.",
+ messageId: "SVC4667"
+ }
+#---------SVC4668------------------------------
+ INVALID_SERVICE_ROLE: {
+ code: 400,
+ message: 'Error: Invalid Content. Service role is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4668"
+ }
+
+ #---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ }
+
+ #---------SVC4670------------------------------
+ ARTIFACT_NAME_INVALID: {
+ code: 400,
+ message: "Error: Artifact name is invalid.",
+ messageId: "SVC4670"
}
\ No newline at end of file
// CapabilityType related
CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
// Resource related
- RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND, TOSCA_PARSE_ERROR,
+ RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND,INVALID_RESOURCE_TYPE, TOSCA_PARSE_ERROR,
+ // Service related
+ SERVICE_TYPE_EXCEEDS_LIMIT, INVALID_SERVICE_TYPE, SERVICE_ROLE_EXCEEDS_LIMIT, INVALID_SERVICE_ROLE,
// Component name related
COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME,
// Component description related
// contactId related
COMPONENT_MISSING_CONTACT, COMPONENT_INVALID_CONTACT,
// Vendor related
- VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE,
+ VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE, RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, INVALID_RESOURCE_VENDOR_MODEL_NUMBER,
// Category related
COMPONENT_MISSING_CATEGORY, COMPONENT_INVALID_CATEGORY, COMPONENT_ELEMENT_INVALID_NAME_FORMAT, COMPONENT_ELEMENT_INVALID_NAME_LENGTH, COMPONENT_CATEGORY_ALREADY_EXISTS, COMPONENT_CATEGORY_NOT_FOUND, COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY, COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY,
// Service API URL
GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST,
// CSAR
- MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND,
+ MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID,
// Group
GROUP_HAS_CYCLIC_DEPENDENCY, GROUP_ALREADY_EXIST, GROUP_TYPE_IS_INVALID, GROUP_MISSING_GROUP_TYPE, GROUP_INVALID_COMPONENT_INSTANCE, GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, GROUP_IS_MISSING, GROUP_ARTIFACT_ALREADY_ASSOCIATED, GROUP_ARTIFACT_ALREADY_DISSOCIATED, GROUP_PROPERTY_NOT_FOUND, INVALID_VF_MODULE_NAME, INVALID_VF_MODULE_NAME_MODIFICATION, INVALID_VF_MODULE_TYPE,
// Inputs
INPUT_IS_NOT_CHILD_OF_COMPONENT,
+ CFVC_LOOP_DETECTED,
;
}
--- /dev/null
+package org.openecomp.sdc.be.dao.cassandra;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.mapping.annotations.Accessor;
+import com.datastax.driver.mapping.annotations.Param;
+import com.datastax.driver.mapping.annotations.Query;
+
+@Accessor
+public interface MigrationTasksAccessor {
+
+ @Query("SELECT minor_version FROM sdcrepository.migrationTasks WHERE major_version = :majorVersion order by minor_version desc limit 1")
+ ResultSet getLatestMinorVersion(@Param("majorVersion") Long majorVersion);
+
+ @Query("DELETE FROM sdcrepository.migrationTasks WHERE major_version = :majorVersion")
+ void deleteTasksForMajorVersion(@Param("majorVersion") Long majorVersion);
+
+}
--- /dev/null
+package org.openecomp.sdc.be.dao.cassandra;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.Mapper;
+import com.datastax.driver.mapping.MappingManager;
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.math.BigInteger;
+
+@Component("sdc-migration-tasks-cassandra-dao")
+public class MigrationTasksDao extends CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(MigrationTasksDao.class.getName());
+ private MigrationTasksAccessor migrationTasksAccessor;
+ private Mapper<MigrationTaskEntry> migrationTaskMapper;
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.REPO_KEYSPACE;
+ if (client.isConnected()) {
+ Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
+ if (result.isLeft()) {
+ session = result.left().value().left;
+ manager = result.left().value().right;
+ migrationTasksAccessor = manager.createAccessor(MigrationTasksAccessor.class);
+ migrationTaskMapper = manager.mapper(MigrationTaskEntry.class);
+ logger.info("** migrationTasksAccessor created");
+ } else {
+ logger.info("** migrationTasksAccessor failed");
+ throw new RuntimeException("Artifact keyspace [" + keyspace + "] failed to connect with error : "
+ + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** migrationTasksAccessor created, but not connected");
+ }
+ }
+
+ public BigInteger getLatestMinorVersion(BigInteger majorVersion) {
+ try {
+ ResultSet latestMinorVersion = migrationTasksAccessor.getLatestMinorVersion(majorVersion.longValue());
+ Row minorVersionRow = latestMinorVersion.one();
+ return minorVersionRow == null ? BigInteger.valueOf(Long.MIN_VALUE) : BigInteger.valueOf(minorVersionRow.getLong(0));
+ } catch (RuntimeException e) {
+ logger.error("failed to get latest minor version for major version {}", majorVersion, e);
+ throw e;
+ }
+ }
+
+ public void deleteAllTasksForVersion(BigInteger majorVersion) {
+ try {
+ migrationTasksAccessor.deleteTasksForMajorVersion(majorVersion.longValue());
+ } catch (RuntimeException e) {
+ logger.error("failed to delete tasks for major version {}", majorVersion, e);
+ throw e;
+ }
+ }
+
+ public void createMigrationTask(MigrationTaskEntry migrationTask) {
+ migrationTaskMapper.save(migrationTask);
+ }
+
+
+}
package org.openecomp.sdc.be.dao.cassandra.schema;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ArtifactTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.AuthEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.CategoryEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ComponentCacheTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ConsumerEventTableDefinition;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDeployEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDownloadEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribEngineEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribNotifEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribStatusEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ExternalApiEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetCatHierEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ResAdminEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.SdcSchemaFilesTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAccessEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.*;
public enum Table {
GET_CATEGORY_HIERARCHY_EVENT(new GetCatHierEventTableDesc()),
EXTERNAL_API_EVENT(new ExternalApiEventTableDesc()),
COMPONENT_CACHE(new ComponentCacheTableDescription()),
- SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription());
-
+ SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription()),
+ SDC_REPO(new MigrationTasksTableDescription());
ITableDescription tableDescription;
Table(ITableDescription tableDescription) {
--- /dev/null
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import com.datastax.driver.core.DataType;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MAJOR_VERSION;
+import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MINOR_VERSION;
+
+public class MigrationTasksTableDescription implements ITableDescription {
+
+ private static final String MIGRATION_TASKS_TABLE = "migrationTasks";
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ return Collections.singletonList(ImmutablePair.of(MAJOR_VERSION.getFieldName(), MAJOR_VERSION.getFieldType()));
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ return Collections.singletonList(ImmutablePair.of(MINOR_VERSION.getFieldName(), MINOR_VERSION.getFieldType()));
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+ Arrays.stream(SdcRepoFieldsDescription.values())
+ .filter(column -> !column.equals(MAJOR_VERSION) && !column.equals(MINOR_VERSION))
+ .forEach(column -> columns.put(column.getFieldName(), ImmutablePair.of(column.getFieldType(), column.isIndexed())));
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.REPO_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return MIGRATION_TASKS_TABLE;
+ }
+
+ enum SdcRepoFieldsDescription {
+ MAJOR_VERSION("major_version", DataType.bigint(), true),
+ MINOR_VERSION("minor_version", DataType.bigint(), false),
+ TIMESTAMP("timestamp", DataType.timestamp(), false),
+ NAME("task_name", DataType.varchar(), false),
+ STATUS("task_status", DataType.varchar(), false),
+ MESSAGE("msg", DataType.varchar(), false),
+ EXECUTION_TIME("execution_time", DataType.cdouble(), false);
+
+ private String fieldName;
+ private boolean isIndexed;
+ private DataType fieldType;
+
+ SdcRepoFieldsDescription(String fieldName, DataType dataType, boolean indexed ) {
+ this.fieldName = fieldName;
+ this.fieldType = dataType;
+ this.isIndexed = indexed;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public boolean isIndexed() {
+ return isIndexed;
+ }
+
+ public DataType getFieldType() {
+ return fieldType;
+ }
+ }
+}
}
if (hasNotProps != null && !hasNotProps.isEmpty()) {
for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) {
- query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
+ if(entry.getValue() instanceof List){
+ buildMultipleNegateQueryFromList(entry, query);
+ }else{
+ query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
+ }
}
}
Iterable<TitanVertex> vertices = query.vertices();
}
+
+ private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, TitanGraphQuery query){
+ List<Object> negateList = (List<Object>) entry.getValue();
+ for (Object listItem : negateList) {
+ query.hasNot(entry.getKey().getProperty(), listItem);
+ }
+ }
+
+
/**
*
* @param parentVertex
}
return null;
}
+
+ public boolean isInstanceArtifactsLabel() {
+ return this.equals(INSTANCE_ARTIFACTS) || this.equals(INST_DEPLOYMENT_ARTIFACTS);
+ }
}
--- /dev/null
+package org.openecomp.sdc.be.resources.data;
+
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+import java.math.BigInteger;
+import java.util.Date;
+
+@Table(keyspace = "sdcrepository", name = "migrationTasks")
+public class MigrationTaskEntry {
+
+ @PartitionKey(0)
+ @Column(name = "major_version")
+ private Long majorVersion;
+
+ @ClusteringColumn
+ @Column(name = "minor_version")
+ private Long minorVersion;
+
+ @Column(name = "timestamp")
+ private Date timestamp;
+
+ @Column(name = "task_name")
+ private String taskName;
+
+ @Column(name = "execution_time")
+ private double executionTime;
+
+ @Column(name = "task_status")
+ private String taskStatus;
+
+ @Column(name = "msg")
+ private String message;
+
+ public void setMajorVersion(Long majorVersion) {
+ this.majorVersion = majorVersion;
+ }
+
+ public void setMinorVersion(Long minorVersion) {
+ this.minorVersion = minorVersion;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public void setTaskName(String taskName) {
+ this.taskName = taskName;
+ }
+
+ public void setTaskStatus(String taskStatus) {
+ this.taskStatus = taskStatus;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void setExecutionTime(double executionTime) {
+ this.executionTime = executionTime;
+ }
+
+ public Long getMajorVersion() {
+ return majorVersion;
+ }
+
+ public Long getMinorVersion() {
+ return minorVersion;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public String getTaskName() {
+ return taskName;
+ }
+
+ public String getTaskStatus() {
+ return taskStatus;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public double getExecutionTime() {
+ return executionTime;
+ }
+}
public interface AuditingTypesConstants {
- public static final String ARTIFACT_KEYSPACE = "sdcartifact";
- public static final String AUDIT_KEYSPACE = "sdcaudit";
- public static final String COMPONENT_KEYSPACE = "sdccomponent";
- public static final String TITAN_KEYSPACE = "titan";
+ String ARTIFACT_KEYSPACE = "sdcartifact";
+ String REPO_KEYSPACE = "sdcrepository";
+ String AUDIT_KEYSPACE = "sdcaudit";
+ String COMPONENT_KEYSPACE = "sdccomponent";
+ String TITAN_KEYSPACE = "titan";
- public static final String USER_ADMIN_EVENT_TYPE = "useradminevent";
- public static final String USER_ACCESS_EVENT_TYPE = "useraccessevent";
- public static final String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent";
- public static final String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent";
+ String USER_ADMIN_EVENT_TYPE = "useradminevent";
+ String USER_ACCESS_EVENT_TYPE = "useraccessevent";
+ String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent";
+ String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent";
- public static final String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent";
- public static final String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent";
- public static final String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent";
- public static final String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent";
- public static final String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent";
- public static final String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent";
+ String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent";
+ String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent";
+ String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent";
+ String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent";
+ String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent";
+ String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent";
- public static final String AUTH_EVENT_TYPE = "authevent";
- public static final String CONSUMER_EVENT_TYPE = "consumerevent";
- public static final String CATEGORY_EVENT_TYPE = "categoryevent";
- public static final String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent";
- public static final String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent";
- public static final String EXTERNAL_API_EVENT_TYPE = "externalapievent";
+ String AUTH_EVENT_TYPE = "authevent";
+ String CONSUMER_EVENT_TYPE = "consumerevent";
+ String CATEGORY_EVENT_TYPE = "categoryevent";
+ String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent";
+ String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent";
+ String EXTERNAL_API_EVENT_TYPE = "externalapievent";
}
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.FE, HealthCheckStatus.UP,
ExternalConfiguration.getAppVersion(), "OK"));
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.DOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.UNKNOWN, null, null));
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.UNKNOWN, null, null));
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ON_BOARDING, HealthCheckStatus.UNKNOWN, null, null));
HealthCheckWrapper hcWrapper = new HealthCheckWrapper(healthCheckInfos, "UNKNOWN", "UNKNOWN");
return hcWrapper;
}
<version>${commons-jci-core.version}</version>
<scope>test</scope>
</dependency>
- </dependencies>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4</artifactId>
+ <version>1.7.0RC4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito-common</artifactId>
+ <version>1.6.5</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
<build>
<plugins>
<plugin>
import java.io.Serializable;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Optional;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.openecomp.sdc.be.config.ConfigurationManager;
this.deploymentArtifacts = deploymentArtifacts;
}
+ public Map<String, ArtifactDefinition> getAllArtifacts() {
+ HashMap<String, ArtifactDefinition> allArtifacts = new HashMap<>();
+ allArtifacts.putAll(Optional.ofNullable(this.deploymentArtifacts).orElse(Collections.emptyMap()));
+ allArtifacts.putAll(Optional.ofNullable(this.artifacts).orElse(Collections.emptyMap()));
+ return allArtifacts;
+ }
+
public List<CategoryDefinition> getCategories() {
return categories;
}
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement {
+public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon {
/**
*
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-
-public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, Serializable{
+public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon, Serializable {
/**
*
}
+ //returns true iff groupName has the same prefix has the resource
+ public boolean isSamePrefix(String resourceName){
+ String name = this.getName();
+ if ( name != null && name.toLowerCase().trim().startsWith(resourceName.toLowerCase()))
+ return true;
+ return false;
+ }
+
}
--- /dev/null
+package org.openecomp.sdc.be.model;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+
+public interface IPropertyInputCommon {
+
+ String getType();
+ SchemaDefinition getSchema();
+ List<PropertyRule> getRules();
+ String getName();
+}
--- /dev/null
+package org.openecomp.sdc.be.model;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.PriorityQueue;
+import java.util.Queue;
+
+public class ImportCsarInfo {
+ String vfResourceName;
+ User modifier;
+ String csarUUID;
+ Map<String, byte[]> csar;
+ Map<String, String> createdNodesToscaResourceNames;
+ Queue<String> cvfcToCreateQueue;
+
+ public ImportCsarInfo(String vfResourceName, User modifier, String csarUUID, Map<String, byte[]> csar){
+ this.vfResourceName = vfResourceName;
+ this.modifier = modifier;
+ this.csarUUID = csarUUID;
+ this.csar = csar;
+ this.createdNodesToscaResourceNames = new HashMap<>();
+ this.cvfcToCreateQueue = new PriorityQueue<>();
+ }
+
+ public String getVfResourceName() {
+ return vfResourceName;
+ }
+
+ public void setVfResourceName(String vfResourceName) {
+ this.vfResourceName = vfResourceName;
+ }
+
+ public User getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(User modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getCsarUUID() {
+ return csarUUID;
+ }
+
+ public void setCsarUUID(String csarUUID) {
+ this.csarUUID = csarUUID;
+ }
+
+ public Map<String, byte[]> getCsar() {
+ return csar;
+ }
+
+ public void setCsar(Map<String, byte[]> csar) {
+ this.csar = csar;
+ }
+
+ public Map<String, String> getCreatedNodesToscaResourceNames() {
+ return createdNodesToscaResourceNames;
+ }
+
+ public void setCreatedNodesToscaResourceNames(Map<String, String> createdNodesToscaResourceNames) {
+ this.createdNodesToscaResourceNames = createdNodesToscaResourceNames;
+ }
+
+ public Queue<String> getCvfcToCreateQueue() {
+ return cvfcToCreateQueue;
+ }
+
+ public void setCvfcToCreateQueue(Queue<String> cvfcToCreateQueue) {
+ this.cvfcToCreateQueue = cvfcToCreateQueue;
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.be.model;
+
+import java.util.List;
+import java.util.Map;
+
+public class NodeTypeInfo {
+ String type;
+ String templateFileName;
+ List<String> derivedFrom;
+ boolean isNested;
+ Map<String, Object> mappedToscaTemplate;
+
+ public NodeTypeInfo getUnmarkedCopy(){
+ NodeTypeInfo unmarked = new NodeTypeInfo();
+ unmarked.type = this.type;
+ unmarked.templateFileName = this.templateFileName;
+ unmarked.derivedFrom = this.derivedFrom;
+ unmarked.isNested = false;
+ unmarked.mappedToscaTemplate = this.mappedToscaTemplate;
+ return unmarked;
+ }
+
+ public String getType() {
+ return type;
+ }
+ public void setType(String type) {
+ this.type = type;
+ }
+ public String getTemplateFileName() {
+ return templateFileName;
+ }
+ public void setTemplateFileName(String templateFileName) {
+ this.templateFileName = templateFileName;
+ }
+ public List<String> getDerivedFrom() {
+ return derivedFrom;
+ }
+ public void setDerivedFrom(List<String> derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+ public boolean isNested() {
+ return isNested;
+ }
+ public void setNested(boolean isNested) {
+ this.isNested = isNested;
+ }
+
+ public Map<String, Object> getMappedToscaTemplate() {
+ return mappedToscaTemplate;
+ }
+
+ public void setMappedToscaTemplate(Map<String, Object> mappedToscaTemplate) {
+ this.mappedToscaTemplate = mappedToscaTemplate;
+ }
+}
if ( !savedRelation.getRequirementId().equals(this.getRequirementUid()) ){
return false;
}
- if ( !savedRelation.getCapabiltyId().equals(this.getCapabilityUid()) ){
+ if ( !savedRelation.getCapabilityId().equals(this.getCapabilityUid()) ){
return false;
}
if ( !savedRelation.getRequirement().equals(this.getRequirement()) ){
((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
.setVendorRelease(vendorRelease);
}
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber){
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).
+ setResourceVendorModelNumber(resourceVendorModelNumber);
+ }
public String getVendorName() {
return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
.getVendorRelease();
}
+ public String getResourceVendorModelNumber(){
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
+ .getResourceVendorModelNumber();
+ }
+
@Override
public String fetchGenericTypeToscaNameFromConfig(){
String result = super.fetchGenericTypeToscaNameFromConfig();
@Override
public boolean shouldGenerateInputs(){
//TODO add complex VFC condition when supported
- return ResourceTypeEnum.VF == this.getResourceType();
+ return ResourceTypeEnum.VF == this.getResourceType() || ResourceTypeEnum.CVFC == this.getResourceType() || ResourceTypeEnum.PNF == this.getResourceType();
}
@Override
public void setNamingPolicy(String namingPolicy) {
getServiceMetadataDefinition().setNamingPolicy(namingPolicy);
}
-
+
public String getNamingPolicy() {
return getServiceMetadataDefinition().getNamingPolicy();
}
+
+ public void setServiceType(String serviceType){
+ getServiceMetadataDefinition().setServiceType(serviceType);
+ }
+
+ public String getServiceType(){
+ return getServiceMetadataDefinition().getServiceType();
+ }
+
+ public void setServiceRole(String serviceRole){
+ getServiceMetadataDefinition().setServiceRole(serviceRole);
+ }
+
+ public String getServiceRole(){
+ return getServiceMetadataDefinition().getServiceRole();
+ }
private ServiceMetadataDataDefinition getServiceMetadataDefinition() {
return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition();
private Map<String, List<UploadCapInfo>> capabilities;
private Map<String, List<UploadReqInfo>> requirements;
private Map<String, List<UploadPropInfo>> properties;
+ private Map<String, String> capabilitiesNamesToUpdate;
+ private Map<String, String> requirementsNamesToUpdate;
public Map<String, List<UploadPropInfo>> getProperties() {
return properties;
this.requirements = requirements;
}
+ public Map<String, String> getCapabilitiesNamesToUpdate() {
+ return capabilitiesNamesToUpdate;
+ }
+
+ public void setCapabilitiesNamesToUpdate(Map<String, String> capabilitiesNamesToUpdate) {
+ this.capabilitiesNamesToUpdate = capabilitiesNamesToUpdate;
+ }
+
+ public Map<String, String> getRequirementsNamesToUpdate() {
+ return requirementsNamesToUpdate;
+ }
+
+ public void setRequirementsNamesToUpdate(Map<String, String> requirementsNamesToUpdate) {
+ this.requirementsNamesToUpdate = requirementsNamesToUpdate;
+ }
+
}
return Either.left(resMap);
}
+ /**
+ *
+ * @param parentId the id of the instance container
+ * @param instanceId the id of the instance of which to return its artifacts
+ * @return instance and instance deployment artifacts mapped by artifact label name
+ */
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) {
+ Map<String, ArtifactDataDefinition> resMap = new HashMap<>();
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ if (instArtifacts.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value()));
+ }
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ if (deployInstArtifacts.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deployInstArtifacts.right().value()));
+ }
+ resMap.putAll(instArtifacts.left().value());
+ resMap.putAll(deployInstArtifacts.left().value());
+ return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap));
+ }
+
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) {
Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null;
}
private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum);
+ if (artifactsEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value());
+ return Either.right(artifactsEither.right().value());
+ }
+ Map<String, ArtifactDataDefinition> artifactDataMap = artifactsEither.left().value();
+ return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap));
+ }
- Map<String, ArtifactDefinition> artMap = null;
- Map<String, ArtifactDataDefinition> artifactDataMap = null;
+ private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum);
+ }
- if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
- Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
- if (resultEither.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
- return Either.right(resultEither.right().value());
- }
- artifactDataMap = resultEither.left().value();
- } else {
- Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
- if (resultEither.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
- return Either.right(resultEither.right().value());
- }
- Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value();
- MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId);
- if (artifactPerInstance != null) {
- artifactDataMap = artifactPerInstance.getMapToscaDataDefinition();
- }
- }
+ private Map<String, ArtifactDefinition> convertArtifactMapToArtifactDefinitionMap(Map<String, ArtifactDataDefinition> artifactDataMap) {
+ Map<String, ArtifactDefinition> artMap = new HashMap<>();
if (artifactDataMap != null && !artifactDataMap.isEmpty()) {
- artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
- } else {
- artMap = new HashMap<>();
+ artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
}
- return Either.left(artMap);
+ return artMap;
+ }
+ private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
+ if (resultEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
+ return Either.right(resultEither.right().value());
+ }
+ Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value();
+ MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId);
+ return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>());
}
private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) {
*
* @param toscaElementUid
* @param edgeLabel
- * @param vertexLabel
* @param uniqueKeys
- * @param mapKeyField
* @return
*/
- public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) {
+ public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) {
StorageOperationStatus statusRes = StorageOperationStatus.OK;
Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
if (statusRes == StorageOperationStatus.OK) {
- statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKeys, mapKeyField);
+ statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys);
}
return statusRes;
}
List<String> uniqueKeys = new ArrayList<>();
uniqueKeys.add(uniqueKey);
- return deleteToscaDataElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, mapKeyField);
+ return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys);
}
@SuppressWarnings("unchecked")
- /**
- * Deletes tosca data elements belonging to tosca element according label
- *
- * @param toscaElement
- * @param edgeLabel
- * @param vertexLabel
- * @param uniqueKeys
- * @param mapKeyField
- * @return
- */
- public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) {
+/**
+ * Deletes tosca data elements belonging to tosca element according label
+ * @param toscaElement
+ * @param edgeLabel
+ * @param uniqueKeys
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex;
- Map<String, ToscaDataDefinition> existingToscaDataMap = null;
+ Map<String, ToscaDataDefinition> existingToscaDataMap;
Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight()) {
TitanOperationStatus status = toscaDataVertexRes.right().value();
}
if (result == null) {
List<String> groupName = groups.stream().map(g -> g.getName()).collect(Collectors.toList());
- status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupName, JsonPresentationFields.NAME);
+ status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
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.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.DistributionStatusEnum;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.RelationshipImpl;
dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION));
if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null)
dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME));
-// if (StringUtils.isEmpty(dataDefinition.getToscaComponentName()) && originToscaElement != null)
-
- dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
-
+ if (originToscaElement != null)
+ dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
if (dataDefinition.getOriginType() == null && originToscaElement != null) {
ResourceTypeEnum resourceType = originToscaElement.getResourceType();
OriginTypeEnum originType = null;
case VFC:
originType = OriginTypeEnum.VFC;
break;
+ case CVFC:
+ originType = OriginTypeEnum.CVFC;
+ break;
case VL:
originType = OriginTypeEnum.VL;
break;
case CP:
originType = OriginTypeEnum.CP;
break;
+ case PNF:
+ originType = OriginTypeEnum.PNF;
+ break;
default:
break;
}
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value());
}
- // update cap/req jsons, fullfilled cap/req jsons!!!!!
+ // update cap/req jsons, fulfilled cap/req jsons!!!!!
Either<GraphVertex, TitanOperationStatus> status;
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
}
GraphVertex containerV = containerVEither.left().value();
- // DE191707 - validatations
+ // DE191707 - validations
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
-
}
- Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapability = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
- Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
+ Map<String, MapListCapabiltyDataDefinition> fulfilledCapability = capFullResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
- Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
+ Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight();
for (RequirementAndRelationshipPair relationPair : relationPairList) {
Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
RelationshipInstDataDefinition relationInJson = entryInJson.getValue();
if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid)) {
if (relationPair.equalsTo(relationInJson)) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(),
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(),
relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId());
iterator.remove();
// update calculated cap/req
- StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relationInJson);
+ StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
- status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, fromResInstanceUid, relationInJson);
+ status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
RelationshipInstDataDefinition relation) {
StorageOperationStatus status;
+ String hereIsTheKey = null;
MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid);
- if (reqByInstance == null) {
- // move from fullfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) {
+ // move from fulfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey);
} else {
- ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
- if (reqByType == null) {
- // move from fullfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
- } else {
- Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
- .filter(cap -> cap.getOwnerId().equals(relation.getRequirementOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getRequirementId())).findFirst();
+ hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
+ ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
+ Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
+ .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst();
- if (requirementOptional.isPresent()) {
+ if (requirementOptional.isPresent()) {
- RequirementDataDefinition requirement = requirementOptional.get();
- String leftOccurrences = requirement.getLeftOccurrences();
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- ++leftIntValue;
- requirement.setLeftOccurrences(String.valueOf(leftIntValue));
- }
- status = StorageOperationStatus.OK;
- } else {
- // move from fullfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ RequirementDataDefinition requirement = requirementOptional.get();
+ String leftOccurrences = requirement.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ requirement.setLeftOccurrences(String.valueOf(leftIntValue));
}
+ status = StorageOperationStatus.OK;
+ } else {
+ // move from fulfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey);
}
}
return status;
}
- private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
+
+ private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> fullFilledCapability, String toResInstanceUid,
RelationshipInstDataDefinition relation) {
StorageOperationStatus status;
- MapListCapabiltyDataDefinition capByInstance = calculatedCapabilty.get(toResInstanceUid);
- if (capByInstance == null) {
- // move from fullfilled
- status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ String hereIsTheKey = null;
+ MapListCapabiltyDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid);
+ if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) {
+ // move from fulfilled
+ status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey);
} else {
- ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
- if (capByType == null) {
- // move from fullfilled
- status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
- } else {
- Optional<CapabilityDataDefinition> capabiltyOptional = capByType.getListToscaDataDefinition().stream()
- .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabiltyId())).findFirst();
+ hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
+ ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
+ Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream()
+ .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())).findFirst();
- if (capabiltyOptional.isPresent()) {
+ if (capabilityOptional.isPresent()) {
- CapabilityDataDefinition capability = capabiltyOptional.get();
- String leftOccurrences = capability.getLeftOccurrences();
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- ++leftIntValue;
- capability.setLeftOccurrences(String.valueOf(leftIntValue));
- }
- status = StorageOperationStatus.OK;
- } else {
- // move from fullfilled
- status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ CapabilityDataDefinition capability = capabilityOptional.get();
+ String leftOccurrences = capability.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ capability.setLeftOccurrences(String.valueOf(leftIntValue));
}
+ status = StorageOperationStatus.OK;
+ } else {
+ // move from fulfilled
+ status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey);
}
}
return status;
}
- private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
- RelationshipInstDataDefinition relation) {
- MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid);
+ private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> fullFilledCapability, String toResInstanceUid,
+ RelationshipInstDataDefinition relation, String hereIsTheKey) {
+ MapListCapabiltyDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid);
if (capByInstance == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty in fullfilled list for instance {} ", toResInstanceUid);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
- ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
- if (capByType == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} in fullfilled list for instance {} ", relation.getType(), toResInstanceUid);
+ if (null == hereIsTheKey)
+ hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
+ if (null == hereIsTheKey) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
+ ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
CapabilityDataDefinition cap = iterator.next();
- if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getCapabiltyId())) {
+ if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) {
found = true;
iterator.remove();
// return to calculated list
++leftIntValue;
cap.setLeftOccurrences(String.valueOf(leftIntValue));
- MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapabilty.get(toResInstanceUid);
+ MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid);
if (mapListCapaDataDef == null) {
mapListCapaDataDef = new MapListCapabiltyDataDefinition();
}
- ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(relation.getType());
+ ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey);
if (findByKey == null) {
findByKey = new ListCapabilityDataDefinition();
- mapListCapaDataDef.put(relation.getType(), findByKey);
+ mapListCapaDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(cap);
break;
}
}
if (found == false) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), toResInstanceUid);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
- RelationshipInstDataDefinition relation) {
+ RelationshipInstDataDefinition relation, String hereIsTheKey) {
MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid);
if (reqByInstance == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
- ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
- if (reqByType == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} in fullfilled list for instance {} ", relation.getType(), fromResInstanceUid);
+ if(null == hereIsTheKey)
+ hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
+ if (null == hereIsTheKey) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
+ ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
Iterator<RequirementDataDefinition> iterator = reqByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
if (mapListReqDataDef == null) {
mapListReqDataDef = new MapListRequirementDataDefinition();
}
- ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(relation.getType());
+ ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey);
if (findByKey == null) {
findByKey = new ListRequirementDataDefinition();
- mapListReqDataDef.put(relation.getType(), findByKey);
+ mapListReqDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(req);
break;
}
}
if (found == false) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), fromResInstanceUid);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
- CapabilityDataDefinition capabiltyForRelation = null;
+ CapabilityDataDefinition capabilityForRelation = null;
Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator();
while (iteratorCap.hasNext()) {
CapabilityDataDefinition cap = iteratorCap.next();
if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) {
- capabiltyForRelation = cap;
+ capabilityForRelation = cap;
String leftOccurrences = cap.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
--leftIntValue;
- capabiltyForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
+ capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
if (leftIntValue == 0) {
// remove from calculated
iteratorCap.remove();
- // move to fullfilled
+ // move to fulfilled
MapListCapabiltyDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId);
if (mapListCapabiltyFullFilledInst == null) {
mapListCapabiltyFullFilledInst = new MapListCapabiltyDataDefinition();
listCapabilityFull = new ListCapabilityDataDefinition();
mapListCapabiltyFullFilledInst.put(type, listCapabilityFull);
}
- listCapabilityFull.add(capabiltyForRelation);
+ listCapabilityFull.add(capabilityForRelation);
}
break;
} else {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabiltyForRelation.getType(), toInstId, containerId);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
- if (capabiltyForRelation == null) {
+ if (capabilityForRelation == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
if (leftIntValue == 0) {
// remove from calculated
iteratorReq.remove();
- // move to fullfilled
+ // move to fulfilled
MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId);
if (mapListRequirementFullFilledInst == null) {
mapListRequirementFullFilledInst = new MapListRequirementDataDefinition();
}
}
}
- if (!capabiltyForRelation.getType().equals(requirementForRelation.getCapability())) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capabilty from type {} and requirement {} from {} to {} in container {}.", capabiltyForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
+ if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair);
-
relationshipTypeData.setType(requirementForRelation.getRelationship());
-
return Either.left(relationshipTypeData);
}
relationshipInstData.setModificationTime(creationDate);
relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId());
relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId());
- relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid());
+ relationshipInstData.setCapabilityId(relationPair.getCapabilityUid());
relationshipInstData.setRequirementId(relationPair.getRequirementUid());
relationshipInstData.setFromId(fromResInstanceUid);
relationshipInstData.setToId(toInstId);
return result;
}
StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate);
- if (associateInstProperties != StorageOperationStatus.OK) {
+ if (associateInstGroups != StorageOperationStatus.OK) {
result = Either.right(associateInstInputs);
return result;
}
GraphVertex categoryV = childVertex.left().value();
Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
CategoryDefinition category = new CategoryDefinition();
- category.setUniqueId((String) metadataProperties.get(GraphPropertyEnum.UNIQUE_ID));
+ category.setUniqueId(categoryV.getUniqueId());
category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
- Type listTypeCat = new TypeToken<List<String>>() {
- }.getType();
+ Type listTypeCat = new TypeToken<List<String>>() {}.getType();
List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
category.setIcons(iconsfromJsonCat);
categories.add(category);
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
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.UniqueIdBuilder;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
//TODO remove after jsonModelMigration
- public void resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
- fixToscaComponentName(vfInst, origCompMap);
+ public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
+ return fixToscaComponentName(vfInst, origCompMap);
}
private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
return false;
}
- origComp = origCompEither.left().value();
+ origComp = origCompEither.left().value();
origCompMap.put(origCompUid, origComp);
} else {
origComp = origCompMap.get(origCompUid);
}
return false;
}
+
+ public Either<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId) {
+ Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ GraphVertex toscaElement = null;
+ GraphVertex modifier = null;
+ GraphVertex owner;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
+ if (getVerticesRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if (result == null) {
+ toscaElement = getVerticesRes.left().value().get(toscaElementId);
+ modifier = getVerticesRes.left().value().get(modifierId);
+ owner = getVerticesRes.left().value().get(ownerId);
+
+ StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
+ }
+ }
+ if (result == null) {
+ LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED;
+
+ toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, "1.0");
+
+ resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
+ if (resultUpdate.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
+ result = Either.right(resultUpdate.right().value());
+ }
+ }
+ if (result == null) {
+ ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
+ result = operation.getToscaElement(toscaElement.getUniqueId());
+ }
+ return result;
+
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
+
+ StorageOperationStatus result = null;
+ TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
+ if (status != TitanOperationStatus.OK) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
+ properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
+ status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
}
package org.openecomp.sdc.be.model.jsontitan.operations;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
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.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.UserData;
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.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import java.lang.reflect.Type;
+import java.util.*;
+import java.util.Map.Entry;
public abstract class ToscaElementOperation extends BaseOperation {
private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName());
return status;
}
- public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement, boolean isHighestVersions) {
+ public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) {
Either<List<GraphVertex>, TitanOperationStatus> listOfComponents;
if (isHighestVersions) {
- listOfComponents = getListOfHighestComponents(componentType, toscaElement);
- } else {
- listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, toscaElement);
+ listOfComponents = getListOfHighestComponents(componentType, excludeTypes);
}
+ else {
+ listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
+ }
+
if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value()));
}
for (GraphVertex vertexComponent : highestAndAllCertified) {
Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true));
if (component.isRight()) {
- log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
+ log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
return Either.right(component.right().value());
} else {
result.add(component.left().value());
return Either.left(result);
}
- private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) {
+ private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
-
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
- return titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
}
- public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) {
+ // highest + (certified && !highest)
+ public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
long startFetchAllStates = System.currentTimeMillis();
+ Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes);
+
Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- Either<List<GraphVertex>, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchCertified, propertiesHasNotToMatchCertified,
+ Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified,
JsonParseFlagEnum.ParseMetadata);
- if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(certifiedNodes.right().value());
- }
-
- Map<GraphPropertyEnum, Object> propertiesToMatchHighest = new HashMap<>();
- propertiesToMatchHighest.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- propertiesToMatchHighest.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- if (componentType == ComponentTypeEnum.RESOURCE) {
- propertiesToMatchHighest.put(GraphPropertyEnum.IS_ABSTRACT, false);
- }
-
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatchHighest = new HashMap<>();
- propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true);
- propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- Either<List<GraphVertex>, TitanOperationStatus> highestNode = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchHighest, propertiesHasNotToMatchHighest, JsonParseFlagEnum.ParseMetadata);
- if (highestNode.isRight() && highestNode.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(highestNode.right().value());
+ if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(certifiedNotHighestNodes.right().value());
}
long endFetchAllStates = System.currentTimeMillis();
List<GraphVertex> allNodes = new ArrayList<>();
- if (certifiedNodes.isLeft()) {
- allNodes.addAll(certifiedNodes.left().value());
- }
- if (highestNode.isLeft()) {
- allNodes.addAll(highestNode.left().value());
- }
-
- int certifiedSize;
- int nonCertifiedSize;
-
- if (certifiedNodes.isRight()) {
- certifiedSize = 0;
- } else {
- certifiedSize = certifiedNodes.left().value().size();
+ if (certifiedNotHighestNodes.isLeft()) {
+ allNodes.addAll(certifiedNotHighestNodes.left().value());
}
-
- if (highestNode.isRight()) {
- nonCertifiedSize = 0;
- } else {
- nonCertifiedSize = highestNode.left().value().size();
+ if (highestNodes.isLeft()) {
+ allNodes.addAll(highestNodes.left().value());
}
- log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", componentType, certifiedSize, nonCertifiedSize);
log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
return Either.left(allNodes);
}
package org.openecomp.sdc.be.model.jsontitan.operations;
import java.util.*;
+import fj.data.Either;
import java.util.Map.Entry;
import java.util.stream.Collectors;
-
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-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.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-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.User;
+import org.openecomp.sdc.be.datatypes.elements.*;
+import org.openecomp.sdc.be.datatypes.enums.*;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
-import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
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.DaoStatusConverter;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("tosca-operation-facade")
public class ToscaOperationFacade {
- @Autowired
- private NodeTypeOperation nodeTypeOperation;
- @Autowired
- private TopologyTemplateOperation topologyTemplateOperation;
- @Autowired
- private NodeTemplateOperation nodeTemplateOperation;
- @Autowired
- private GroupsOperation groupsOperation;
- @Autowired
- private TitanDao titanDao;
-
- private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
+ @Autowired
+ private NodeTypeOperation nodeTypeOperation;
+ @Autowired
+ private TopologyTemplateOperation topologyTemplateOperation;
+ @Autowired
+ private NodeTemplateOperation nodeTemplateOperation;
+ @Autowired
+ private GroupsOperation groupsOperation;
+ @Autowired
+ private TitanDao titanDao;
+
+ private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
+
+ return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.setIgnoreCapabiltyProperties(false);
+
+ return getToscaElement(componentId, filters);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value(), filters);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value());
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
+ return getToscaElementByOperation(componentVertex);
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ TitanOperationStatus status = getVertexEither.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(false);
+ } else {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ }
+ return Either.left(true);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
+ Map<GraphPropertyEnum, Object> props = new HashMap<>();
+ props.put(GraphPropertyEnum.UUID, component.getUUID());
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value().get(0));
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
+ return getToscaElementByOperation(componentV, new ComponentParametersView());
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
+ VertexTypeEnum label = componentV.getLabel();
+
+ ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
+ Either<ToscaElement, StorageOperationStatus> toscaElement;
+ String componentId = componentV.getUniqueId();
+ if (toscaOperation != null) {
+ log.debug("Need to fetch tosca element for id {}", componentId);
+ toscaElement = toscaOperation.getToscaElement(componentV, filters);
+ } else {
+ log.debug("not supported tosca type {} for id {}", label, componentId);
+ toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (toscaElement.isRight()) {
+ return Either.right(toscaElement.right().value());
+ }
+ return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
+ }
+
+ private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
+ VertexTypeEnum label = componentV.getLabel();
+ switch (label) {
+ case NODE_TYPE:
+ return nodeTypeOperation;
+ case TOPOLOGY_TEMPLATE:
+ return topologyTemplateOperation;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ *
+ * @param resource
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
+ ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
+
+ ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
+ Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
+ if (createToscaElement.isLeft()) {
+ log.debug("Component created successfully!!!");
+ T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
+ return Either.left(dataModel);
+ }
+ return Either.right(createToscaElement.right().value());
+ }
+
+ /**
+ *
+ * @param componentToDelete
+ * @return
+ */
+ public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
+
+ if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
+ // component already marked for delete
+ return StorageOperationStatus.OK;
+ } else {
+
+ Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ if (getResponse.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
+
+ }
+ GraphVertex componentV = getResponse.left().value();
+
+ // same operation for node type and topology template operations
+ Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
+ if (result.isRight()) {
+ return result.right().value();
+ }
+ return StorageOperationStatus.OK;
+ }
+ }
+
+ /**
+ *
+ * @param componentId
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
+ if (deleteElement.isRight()) {
+ log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
+ return Either.right(deleteElement.right().value());
+ }
+ T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
+
+ return Either.left(dataModel);
+ }
+
+ private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
+ VertexTypeEnum label = componentV.getLabel();
+ Either<ToscaElement, StorageOperationStatus> toscaElement;
+ Object componentId = componentV.getUniqueId();
+ switch (label) {
+ case NODE_TYPE:
+ log.debug("Need to fetch node type for id {}", componentId);
+ toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
+ break;
+ case TOPOLOGY_TEMPLATE:
+ log.debug("Need to fetch topology template for id {}", componentId);
+ toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
+ break;
+ default:
+ log.debug("not supported tosca type {} for id {}", label, componentId);
+ toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
+ break;
+ }
+ return toscaElement;
+ }
+
+ private ToscaElementOperation getToscaElementOperation(Component component) {
+ return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
+ return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
+ return getLatestByName(GraphPropertyEnum.NAME, resourceName);
+
+ }
+
+ public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
+ Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
+
+ Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
+ properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
+
+ Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+
+ if (resources.isRight()) {
+ if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(new Integer(0));
+ } else {
+ log.debug("failed to get resources from graph with property name: {}", csarUUID);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ }
+ }
+
+ List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+
+ return Either.left(new Integer(resourceList.size()));
+
+ }
- return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
- ComponentParametersView filters = new ComponentParametersView();
- filters.setIgnoreCapabiltyProperties(false);
+ public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
+ Either<List<ToscaElement>, StorageOperationStatus> followedResources;
+ if (componentType == ComponentTypeEnum.RESOURCE) {
+ followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
+ } else {
+ followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
+ }
- return getToscaElement(componentId, filters);
- }
+ Set<T> components = new HashSet<>();
+ if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
+ return Either.right(followedResources.right().value());
+ }
+ if (followedResources.isLeft()) {
+ List<ToscaElement> toscaElements = followedResources.left().value();
+ toscaElements.forEach(te -> {
+ T component = ModelConverter.convertFromToscaElement(te);
+ components.add(component);
+ });
+ }
+ return Either.left(components);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
+
+ return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
+
+ Either<Resource, StorageOperationStatus> result = null;
+ Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
+ props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
+
+ if (getLatestRes.isRight()) {
+ TitanOperationStatus status = getLatestRes.right().value();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ List<GraphVertex> resources = getLatestRes.left().value();
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex resource : resources) {
+ double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = resource;
+ }
+ }
+ result = getToscaElement(highestResource.getUniqueId());
+ }
+ return result;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
+ Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
+ if (validateUniquenessRes.isLeft()) {
+ return Either.left(!validateUniquenessRes.left().value());
+ }
+ return validateUniquenessRes;
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
+
+ }
+
+ public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
+ if (status.isRight()) {
+ return status.right().value();
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
+
+ Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
+ properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
+
+ Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+
+ if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get resources from graph with property name: {}", name);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ }
+ List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+ if (resourceList != null && resourceList.size() > 0) {
+ if (log.isDebugEnabled()) {
+ StringBuilder builder = new StringBuilder();
+ for (GraphVertex resourceData : resourceList) {
+ builder.append(resourceData.getUniqueId() + "|");
+ }
+ log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
+ }
+ return Either.left(false);
+ } else {
+ log.debug("resources with property name:{} does not exists in graph", name);
+ return Either.left(true);
+ }
+
+ }
+
+ /**
+ *
+ * @param newComponent
+ * @param oldComponent
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
+
+ // TODO
+ // newComponent.setInterfaces(oldComponent.getInterfaces);
+ newComponent.setArtifacts(oldComponent.getArtifacts());
+ newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
+ newComponent.setGroups(oldComponent.getGroups());
+ newComponent.setInputs(null);
+ newComponent.setLastUpdateDate(null);
+ newComponent.setHighestVersion(true);
+
+ Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (componentVEither.isRight()) {
+ log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
+ }
+ GraphVertex componentv = componentVEither.left().value();
+ Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
+ }
+
+ Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
+ if (deleteToscaComponent.isRight()) {
+ log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
+ return Either.right(deleteToscaComponent.right().value());
+ }
+ Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
+ if (createToscaComponent.isRight()) {
+ log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
+ return Either.right(createToscaComponent.right().value());
+ }
+ T newElement = createToscaComponent.left().value();
+ Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (newVersionEither.isRight()) {
+ log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
+ }
+ if (parentVertexEither.isLeft()) {
+ GraphVertex previousVersionV = parentVertexEither.left().value();
+ TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
+ if (createEdge != TitanOperationStatus.OK) {
+ log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
+ }
+ }
+ return Either.left(newElement);
+ }
+
+ /**
+ *
+ * @param componentToUpdate
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
+ return updateToscaElement(componentToUpdate, new ComponentParametersView());
+ }
+
+ /**
+ *
+ * @param componentToUpdate
+ * @param type
+ * @param filterResult
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
+ String componentId = componentToUpdate.getUniqueId();
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ GraphVertex elementV = getVertexEither.left().value();
+ ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
+
+ ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
+ Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
+ if (updateToscaElement.isRight()) {
+ log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
+ return Either.right(updateToscaElement.right().value());
+ }
+ return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(property, nodeName);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ if (highestResources.isRight()) {
+ TitanOperationStatus status = highestResources.right().value();
+ log.debug("failed to find resource with name {}. status={} ", nodeName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+
+ List<GraphVertex> resources = highestResources.left().value();
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex vertex : resources) {
+ Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
+ double resourceVersion = Double.valueOf((String) versionObj);
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = vertex;
+ }
+ }
+ return getToscaElementByOperation(highestResource);
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
+
+ Either<List<T>, StorageOperationStatus> result = null;
+ Either<T, StorageOperationStatus> getComponentRes;
+ List<T> components = new ArrayList<>();
+ List<GraphVertex> componentVertices;
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
+ if (componentType != null)
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (getComponentsRes.isRight()) {
+ TitanOperationStatus status = getComponentsRes.right().value();
+ log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ componentVertices = getComponentsRes.left().value();
+ for (GraphVertex componentVertex : componentVertices) {
+ getComponentRes = getToscaElementByOperation(componentVertex);
+ if (getComponentRes.isRight()) {
+ log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
+ result = Either.right(getComponentRes.right().value());
+ break;
+ }
+ T componentBySystemName = getComponentRes.left().value();
+ log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
+ components.add(componentBySystemName);
+ }
+ }
+ if (result == null) {
+ result = Either.left(components);
+ }
+ return result;
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
+ return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.NAME, name);
+ hasProperties.put(GraphPropertyEnum.VERSION, version);
+ hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
+ if (componentType != null) {
+ hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ }
+ Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ if (getResourceRes.isRight()) {
+ TitanOperationStatus status = getResourceRes.right().value();
+ log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ return getToscaElementByOperation(getResourceRes.left().value().get(0));
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
+ List<T> components = new ArrayList<>();
+ Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
+ List<ToscaElement> toscaElements = new ArrayList<>();
+ List<ResourceTypeEnum> excludedResourceTypes =
+ Optional.ofNullable(excludeTypes).orElse(Collections.emptyList())
+ .stream()
+ .filter(type -> !type.equals(OriginTypeEnum.SERVICE))
+ .map(type -> ResourceTypeEnum.getTypeByName(type.name())).collect(Collectors.toList());
+
+ switch (componentType) {
+ case RESOURCE:
+ catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludedResourceTypes , isHighestVersions);
+ if (catalogDataResult.isRight()) {
+ return Either.right(catalogDataResult.right().value());
+ }
+ toscaElements = catalogDataResult.left().value();
+ break;
+ case SERVICE:
+ if (excludeTypes!= null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
+ break;
+ }
+ catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
+ if (catalogDataResult.isRight()) {
+ return Either.right(catalogDataResult.right().value());
+ }
+ toscaElements = catalogDataResult.left().value();
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ toscaElements.forEach(te -> {
+ T component = ModelConverter.convertFromToscaElement(te);
+ components.add(component);
+ });
+ return Either.left(components);
+ }
+
+ public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
+ Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
+ List<String> deleted = new ArrayList<>();
+ switch (componentType) {
+ case RESOURCE:
+ allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ case SERVICE:
+ case PRODUCT:
+ allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (allComponentsMarkedForDeletion.isRight()) {
+ return Either.right(allComponentsMarkedForDeletion.right().value());
+ }
+ List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
+
+ Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
+ if (allNotDeletedElements.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+ }
+ List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
+ for (GraphVertex elementV : allMarked) {
+ if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
+ Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
+ if (deleteToscaElement.isRight()) {
+ log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
+ }
+ } else {
+ deleted.add(elementV.getUniqueId());
+ log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
+ }
+ }
+ return Either.left(deleted);
+ }
+
+ public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
+ Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
+ switch (componentType) {
+ case RESOURCE:
+ allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ case SERVICE:
+ case PRODUCT:
+ allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (allComponentsMarkedForDeletion.isRight()) {
+ return Either.right(allComponentsMarkedForDeletion.right().value());
+ }
+ return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
+ }
+
+ public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
+ Either<Boolean, StorageOperationStatus> result;
+ Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
+ if (allNotDeletedElements.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+ } else {
+ result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+ componentInstance.setIcon(origComponent.getIcon());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
+
+ if (addResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ result = Either.right(addResult.right().value());
+ }
+ if (result == null) {
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
+ String createdInstanceId = addResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
+ }
+ return result;
+ }
+
+ public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
+
+ StorageOperationStatus result = null;
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ componentInstance.setIcon(origComponent.getIcon());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), componentInstance);
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
+ String createdInstanceId = updateResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
+ }
+ return result;
+ }
+
+ public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
+
+ Either<Component, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
+
+ Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
+ result = Either.left(updatedComponent);
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
+ String deletedInstanceId = updateResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
+ }
+ return result;
+ }
+
+ private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
+
+ Integer nextCounter = 0;
+
+ if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
+
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
+ Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
+ Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
+
+ if (maxCounterFromNames == null && maxCounterFromIds != null) {
+ nextCounter = maxCounterFromIds + 1;
+ } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
+ nextCounter = maxCounterFromNames + 1;
+ } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
+ nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
+ }
+ }
+ return nextCounter.toString();
+ }
+
+ private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
+
+ Integer maxCounter = 0;
+ List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
+ .collect(Collectors.toList());
+
+ if (CollectionUtils.isEmpty(countersStr)) {
+ return null;
+ }
+ Integer currCounter = null;
+ for (String counter : countersStr) {
+ if (StringUtils.isEmpty(counter)) {
+ continue;
+ }
+ try {
+ currCounter = Integer.parseInt(counter);
+ } catch (Exception e) {
+ continue;
+ }
+ maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
+ }
+ if (currCounter == null) {
+ return null;
+ }
+ return maxCounter;
+ }
+
+ private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
+
+ Integer maxCounter = 0;
+ List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
+ .collect(Collectors.toList());
+
+ if (CollectionUtils.isEmpty(countersStr)) {
+ return null;
+ }
+ Integer currCounter = null;
+ for (String counter : countersStr) {
+ if (StringUtils.isEmpty(counter)) {
+ continue;
+ }
+ try {
+ currCounter = Integer.parseInt(counter);
+ } catch (Exception e) {
+ continue;
+ }
+ maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
+ }
+ if (currCounter == null) {
+ return null;
+ }
+ return maxCounter;
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
+
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+
+ StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ List<InputDefinition> inputsResList = null;
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ }
+ return Either.left(inputsResList);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+
+ StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ List<InputDefinition> inputsResList = null;
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ }
+ return Either.left(inputsResList);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
- }
- return getToscaElementByOperation(getVertexEither.left().value(), filters);
- }
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ return Either.left(instProperties);
+ }
+ return Either.right(status);
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
+ }
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
}
- return getToscaElementByOperation(getVertexEither.left().value());
- }
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instInputs != null) {
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
- return getToscaElementByOperation(componentVertex);
- }
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
- public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- TitanOperationStatus status = getVertexEither.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- return Either.left(false);
- } else {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ instPropsMap.put(entry.getKey(), propertiesMap);
}
}
- return Either.left(true);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
- Map<GraphPropertyEnum, Object> props = new HashMap<>();
- props.put(GraphPropertyEnum.UUID, component.getUUID());
- props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
- return getToscaElementByOperation(getVertexEither.left().value().get(0));
- }
-
- private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
- return getToscaElementByOperation(componentV, new ComponentParametersView());
- }
-
- private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
- VertexTypeEnum label = componentV.getLabel();
-
- ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
- Either<ToscaElement, StorageOperationStatus> toscaElement;
- String componentId = componentV.getUniqueId();
- if (toscaOperation != null) {
- log.debug("Need to fetch tosca element for id {}", componentId);
- toscaElement = toscaOperation.getToscaElement(componentV, filters);
- } else {
- log.debug("not supported tosca type {} for id {}", label, componentId);
- toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- if (toscaElement.isRight()) {
- return Either.right(toscaElement.right().value());
- }
- return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
- }
- private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
- VertexTypeEnum label = componentV.getLabel();
- switch (label) {
- case NODE_TYPE:
- return nodeTypeOperation;
- case TOPOLOGY_TEMPLATE:
- return topologyTemplateOperation;
- default:
- return null;
- }
- }
+ StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
- /**
- *
- * @param resource
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
- ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
-
- ToscaElementOperation toscaElementOperation = getToscaElementOperation(toscaElement);
- Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
- if (createToscaElement.isLeft()) {
+ if (StorageOperationStatus.OK == status) {
log.debug("Component created successfully!!!");
- T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
- return Either.left(dataModel);
- }
- return Either.right(createToscaElement.right().value());
- }
-
- /**
- *
- * @param componentToDelete
- * @return
- */
- public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
-
- if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
- // component already marked for delete
- return StorageOperationStatus.OK;
- } else {
-
- Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
- if (getResponse.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
-
- }
- GraphVertex componentV = getResponse.left().value();
-
- // same operation for node type and topology template operations
- Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
- if (result.isRight()) {
- return result.right().value();
- }
- return StorageOperationStatus.OK;
- }
- }
-
- /**
- *
- * @param componentId
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
- Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
- if (deleteElement.isRight()) {
- log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
- return Either.right(deleteElement.right().value());
+ return Either.left(instInputs);
}
- T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
-
- return Either.left(dataModel);
- }
-
- private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
- VertexTypeEnum label = componentV.getLabel();
- Either<ToscaElement, StorageOperationStatus> toscaElement;
- Object componentId = componentV.getUniqueId();
- switch (label) {
- case NODE_TYPE:
- log.debug("Need to fetch node type for id {}", componentId);
- toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
- break;
- case TOPOLOGY_TEMPLATE:
- log.debug("Need to fetch topology template for id {}", componentId);
- toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
- break;
- default:
- log.debug("not supported tosca type {} for id {}", label, componentId);
- toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
- break;
- }
- return toscaElement;
- }
-
- private ToscaElementOperation getToscaElementOperation(ToscaElement toscaElement) {
-
- ComponentTypeEnum componentType = toscaElement.getComponentType();
- switch (componentType) {
- case RESOURCE:
- ResourceTypeEnum resourceType = toscaElement.getResourceType();
- if (resourceType == ResourceTypeEnum.VF) {
- return topologyTemplateOperation;
- } else {
- return nodeTypeOperation;
- }
- case SERVICE:
- case PRODUCT:
- return topologyTemplateOperation;
- default:
- break;
- }
- return null;
- }
-
- private ToscaElementOperation getToscaElementOperation(Component component) {
-
- switch (component.getComponentType()) {
- case RESOURCE:
- ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
- if (resourceType != null && resourceType == ResourceTypeEnum.VF) {
- return topologyTemplateOperation;
- } else {
- return nodeTypeOperation;
- }
- case SERVICE:
- case PRODUCT:
- return topologyTemplateOperation;
- default:
- break;
- }
- return null;
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
- return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
-
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
- return getLatestByName(GraphPropertyEnum.NAME, resourceName);
+ return Either.right(status);
}
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
+
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ if (instProperties != null) {
+
+ for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
+ List<ComponentInstanceInput> props = entry.getValue();
+ String componentInstanseId = entry.getKey();
+ if (props != null && !props.isEmpty()) {
+ for (ComponentInstanceInput property : props) {
+ List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
+ Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
+ if (instanceProperty.isPresent()) {
+ status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
+ } else {
+ status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
+ }
+ if (status != StorageOperationStatus.OK) {
+ log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
+ return Either.right(status);
+ } else {
+ log.trace("instance input {} for instance {} updated", property, componentInstanseId);
+ }
+ }
+ }
+ }
+ }
+ return Either.left(instProperties);
+ }
+
+ public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
- public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
- Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
-
- Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
- properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
-
- Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
-
- if (resources.isRight()) {
- if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
- return Either.left(new Integer(0));
- } else {
- log.debug("failed to get resources from graph with property name: {}", csarUUID);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
- }
- }
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
- List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+ }
- return Either.left(new Integer(resourceList.size()));
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
- }
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
- public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
- Either<List<ToscaElement>, StorageOperationStatus> followedResources;
- if (componentType == ComponentTypeEnum.RESOURCE) {
- followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
- } else {
- followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
- }
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- Set<T> components = new HashSet<>();
- if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
- return Either.right(followedResources.right().value());
- }
- if (followedResources.isLeft()) {
- List<ToscaElement> toscaElements = followedResources.left().value();
- toscaElements.forEach(te -> {
- T component = ModelConverter.convertFromToscaElement(te);
- components.add(component);
- });
- }
- return Either.left(components);
- }
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
- public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
+ return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
- return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
- }
+ }
- public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
- Either<Resource, StorageOperationStatus> result = null;
- Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
- props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ if (instProperties != null) {
- if (getLatestRes.isRight()) {
- TitanOperationStatus status = getLatestRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- List<GraphVertex> resources = getLatestRes.left().value();
- double version = 0.0;
- GraphVertex highestResource = null;
- for (GraphVertex resource : resources) {
- double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = resource;
- }
- }
- result = getToscaElement(highestResource.getUniqueId());
- }
- return result;
- }
+ for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ List<ComponentInstanceProperty> props = entry.getValue();
+ String componentInstanseId = entry.getKey();
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
+ if (props != null && !props.isEmpty()) {
+ for (ComponentInstanceProperty property : props) {
+ Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ if (instanceProperty.isPresent()) {
+ status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
+ } else {
+ status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
+ }
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
- Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
- if (validateUniquenessRes.isLeft()) {
- return Either.left(!validateUniquenessRes.left().value());
- }
- return validateUniquenessRes;
- }
+ }
+ }
+ }
+ }
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
- return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
+ return Either.left(instProperties);
- }
+ }
- public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
- Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
- if (status.isRight()) {
- return status.right().value();
- }
- return StorageOperationStatus.OK;
- }
+ public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
- protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
- Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
- properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
+ }
- Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
+ if (instArtifacts != null) {
- if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get resources from graph with property name: {}", name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
- }
- List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
- if (resourceList != null && resourceList.size() > 0) {
- if (log.isDebugEnabled()) {
- StringBuilder builder = new StringBuilder();
- for (GraphVertex resourceData : resourceList) {
- builder.append(resourceData.getUniqueId() + "|");
- }
- log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
- }
- return Either.left(false);
- } else {
- log.debug("resources with property name:{} does not exists in graph", name);
- return Either.left(true);
- }
+ MapArtifactDataDefinition artifactsMap;
+ for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
+ Map<String, ArtifactDefinition> artList = entry.getValue();
+ Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
- }
+ instArtMap.put(entry.getKey(), artifactsMap);
+ }
+ }
+
+ return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap);
+
+ }
+
+ public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
- /**
- *
- * @param newComponent
- * @param oldComponent
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
-
- // TODO
- // newComponent.setInterfaces(oldComponent.getInterfaces);
- newComponent.setArtifacts(oldComponent.getArtifacts());
- newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
- newComponent.setGroups(oldComponent.getGroups());
- newComponent.setInputs(null);
- newComponent.setLastUpdateDate(null);
- newComponent.setHighestVersion(true);
-
- Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (componentVEither.isRight()) {
- log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
- }
- GraphVertex componentv = componentVEither.left().value();
- Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
- if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
- }
+ }
- Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
- if (deleteToscaComponent.isRight()) {
- log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
- return Either.right(deleteToscaComponent.right().value());
- }
- Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
- if (createToscaComponent.isRight()) {
- log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
- return Either.right(createToscaComponent.right().value());
- }
- T newElement = createToscaComponent.left().value();
- Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (newVersionEither.isRight()) {
- log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
- }
- if (parentVertexEither.isLeft()) {
- GraphVertex previousVersionV = parentVertexEither.left().value();
- TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
- if (createEdge != TitanOperationStatus.OK) {
- log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
- }
- }
- return Either.left(newElement);
- }
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
+ if (instArttributes != null) {
- /**
- *
- * @param componentToUpdate
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
- return updateToscaElement(componentToUpdate, new ComponentParametersView());
- }
+ MapPropertiesDataDefinition attributesMap;
+ for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
+ attributesMap = new MapPropertiesDataDefinition();
+ attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+ instAttr.put(entry.getKey(), attributesMap);
+ }
+ }
- /**
- *
- * @param componentToUpdate
- * @param type
- * @param filterResult
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
- String componentId = componentToUpdate.getUniqueId();
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
- }
- GraphVertex elementV = getVertexEither.left().value();
- ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
-
- ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
- Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
- if (updateToscaElement.isRight()) {
- log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
- return Either.right(updateToscaElement.right().value());
- }
- return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
- }
+ return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
- private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
- Either<T, StorageOperationStatus> result;
+ }
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
- propertiesToMatch.put(property, nodeName);
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+ GraphVertex vertex = getVertexEither.left().value();
- Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
- if (highestResources.isRight()) {
- TitanOperationStatus status = highestResources.right().value();
- log.debug("failed to find resource with name {}. status={} ", nodeName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
+ Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
- List<GraphVertex> resources = highestResources.left().value();
- double version = 0.0;
- GraphVertex highestResource = null;
- for (GraphVertex vertex : resources) {
- Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
- double resourceVersion = Double.valueOf((String) versionObj);
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = vertex;
- }
- }
- return getToscaElementByOperation(highestResource);
- }
+ Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
+ Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
+ ;
+ if (instCapabilties != null) {
+ for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
- public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
+ Map<String, List<CapabilityDefinition>> caps = entry.getValue();
+ Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
+ mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
+ MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
+
+ MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
+
+ calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
+ calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
+ }
+ }
+
+ if (instReg != null) {
+ for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
+
+ Map<String, List<RequirementDefinition>> req = entry.getValue();
+ Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
+ mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
+
+ calcRequirements.put(entry.getKey().getUniqueId(), capMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
+
+ return status;
+ }
+
+ private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
+
+ Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
+
+ fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ return Either.left(new ArrayList<>());
+ } else {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ }
+ } else {
+ List<Component> nonAbstractLatestComponents = new ArrayList<>();
+ ComponentParametersView params = new ComponentParametersView(true);
+ params.setIgnoreAllVersions(false);
+ for (GraphVertex vertexComponent : getRes.left().value()) {
+ Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
+ if (componentRes.isRight()) {
+ log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
+ return Either.right(componentRes.right().value());
+ } else {
+ Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
+
+ nonAbstractLatestComponents.add(component);
+ }
+ }
+
+ return Either.left(nonAbstractLatestComponents);
+ }
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
+ if (isHighest != null) {
+ hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
+ }
+
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
+ if (getRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ } else {
+ List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
+ ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
+ : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
+ result = Either.left(latestVersion);
+ }
+ return result;
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result;
+ Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ } else {
+ ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
+ result = Either.left(componentMetadata);
+ }
+ return result;
+ }
+
+ private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
+ Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
+ for (ComponentMetadataData resourceData : resourceDataList) {
+ ComponentMetadataData latestVersionData = resourceData;
+
+ ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
+ Pair<String, String> pair = createKeyPair(latestVersionData);
+ if (latestVersionMap.containsKey(pair)) {
+ latestVersionData = latestVersionMap.get(pair);
+ String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
+ String newVersion = metadataDataDefinition.getVersion();
+ if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
+ latestVersionData = resourceData;
+ }
+ }
+ if (log.isDebugEnabled())
+ log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
+
+ latestVersionMap.put(pair, latestVersionData);
+ }
+
+ Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
+ for (ComponentMetadataData resourceData : latestVersionMap.values()) {
+ ComponentMetadataData latestVersionData = resourceData;
+ ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
+ if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
+ latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
+ String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
+ String newVersion = metadataDataDefinition.getVersion();
+ if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
+ latestVersionData = resourceData;
+ }
+ }
+ if (log.isDebugEnabled())
+ log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
+ resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
+ }
+
+ return resVersionMap;
+ }
+
+ private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
+ Pair<String, String> pair;
+ NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
+ switch (label) {
+ case Resource:
+ pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
+ break;
+ default:
+ pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
+ break;
+ }
+
+ return pair;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+
+ Either<List<Component>, StorageOperationStatus> result = null;
+ List<Component> components = new ArrayList<>();
+ if (componentUids == null) {
+ Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
+ if (componentUidsRes.isRight()) {
+ result = Either.right(componentUidsRes.right().value());
+ } else {
+ componentUids = componentUidsRes.left().value();
+ }
+ }
+ if (!componentUids.isEmpty()) {
+ for (String componentUid : componentUids) {
+ ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
+ if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
+ componentParametersView.setIgnoreCapabilities(false);
+ componentParametersView.setIgnoreRequirements(false);
+ }
+ Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
+ if (getToscaElementRes.isRight()) {
+ if (log.isDebugEnabled())
+ log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
+ result = Either.right(getToscaElementRes.right().value());
+ break;
+ }
+ Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
+ component.setContactId(null);
+ component.setCreationDate(null);
+ component.setCreatorUserId(null);
+ component.setCreatorFullName(null);
+ component.setLastUpdateDate(null);
+ component.setLastUpdaterUserId(null);
+ component.setLastUpdaterFullName(null);
+ component.setNormalizedName(null);
+ components.add(component);
+ }
+ }
+ if (result == null) {
+ result = Either.left(components);
+ }
+ return result;
+ }
+
+ private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+
+ Either<List<String>, StorageOperationStatus> result = null;
+ Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
+ if (getToscaElementsRes.isRight()) {
+ result = Either.right(getToscaElementsRes.right().value());
+ } else {
+ List<Component> collection = getToscaElementsRes.left().value();
+ if (collection == null) {
+ componentUids = new ArrayList<>();
+ } else {
+ componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
+ }
+ }
+ if (result == null) {
+ result = Either.left(componentUids);
+ }
+ return result;
+ }
+
+ private ComponentParametersView buildComponentViewForNotAbstract() {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreCategories(false);
+ componentParametersView.setIgnoreAllVersions(false);
+ return componentParametersView;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
+ if (result.isLeft()) {
+ result = Either.left(!result.left().value());
+ }
+ return result;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ String normalizedName = ValidationUtils.normaliseComponentName(name);
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
+ properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
+ if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+ if (vertexList != null && !vertexList.isEmpty()) {
+ return Either.left(false);
+ } else {
+ return Either.left(true);
+ }
+ }
+
+
+ private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
+ switch (internalComponentType.toLowerCase()) {
+ case "vf":
+ case "cvfc":
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
+ break;
+ case "service":
+ case "pnf" :
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
+ break;
+ case "vl":
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
+ break;
+ default:
+ break;
+ }
+ }
+
+
+ private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ break;
+ case SERVICE:
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ break;
+ default:
+ break;
+ }
+ switch (internalComponentType.toLowerCase()) {
+ case "vf":
+ case "cvfc":
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
+ break;
+ case "service":
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
+ hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+
+ hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
+ hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
+ hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
+ if (internalComponentType != null) {
+ fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
+ }
+ } else {
+ fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
+ }
+ }
+
+ private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
+ if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
+ internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
+ }
+ if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
+ internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ }
+ return internalVertexTypes;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
+ List<Component> result = new ArrayList<>();
+ for (VertexTypeEnum vertexType : internalVertexTypes) {
+ Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
+ if (listByVertexType.isRight()) {
+ return listByVertexType;
+ }
+ result.addAll(listByVertexType.left().value());
+ }
+ return Either.left(result);
+
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
+ return componentListByUuid;
+ }
- Either<List<T>, StorageOperationStatus> result = null;
- Either<T, StorageOperationStatus> getComponentRes;
- List<T> components = new ArrayList<>();
- List<GraphVertex> componentVertices;
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
- propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
- if (componentType != null)
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+ if (additionalPropertiesToMatch != null) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
- Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- if (getComponentsRes.isRight()) {
- TitanOperationStatus status = getComponentsRes.right().value();
- log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- componentVertices = getComponentsRes.left().value();
- for (GraphVertex componentVertex : componentVertices) {
- getComponentRes = getToscaElementByOperation(componentVertex);
- if (getComponentRes.isRight()) {
- log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
- result = Either.right(getComponentRes.right().value());
- break;
- }
- T componentBySystemName = getComponentRes.left().value();
- log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
- components.add(componentBySystemName);
- }
- }
- if (result == null) {
- result = Either.left(components);
- }
- return result;
- }
+ propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
- return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
- }
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
- Either<T, StorageOperationStatus> result;
+ Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+ if (vertexEither.isRight()) {
+ log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
- hasProperties.put(GraphPropertyEnum.NAME, name);
- hasProperties.put(GraphPropertyEnum.VERSION, version);
- hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
- if (componentType != null) {
- hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- }
- Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
- if (getResourceRes.isRight()) {
- TitanOperationStatus status = getResourceRes.right().value();
- log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- return getToscaElementByOperation(getResourceRes.left().value().get(0));
- }
+ if (vertexList == null || vertexList.isEmpty()) {
+ log.debug("Component with uuid {} was not found", componentUuid);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
- public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, boolean isHighestVersions) {
- List<T> components = new ArrayList<>();
- Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
- List<ToscaElement> toscaElements;
- switch (componentType) {
- case RESOURCE:
- catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.NodeType, isHighestVersions);
- if (catalogDataResult.isRight()) {
- return Either.right(catalogDataResult.right().value());
- }
- toscaElements = catalogDataResult.left().value();
- Either<List<ToscaElement>, StorageOperationStatus> resourceCatalogData = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions);
- if (resourceCatalogData.isRight()) {
- return Either.right(resourceCatalogData.right().value());
- }
- toscaElements.addAll(resourceCatalogData.left().value());
- break;
- case SERVICE:
- catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions);
- if (catalogDataResult.isRight()) {
- return Either.right(catalogDataResult.right().value());
+ ArrayList<Component> latestComponents = new ArrayList<>();
+ for (GraphVertex vertex : vertexList) {
+ Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
+
+ if(toscaElementByOperation.isRight()){
+ log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
+ return Either.right(toscaElementByOperation.right().value());
}
- toscaElements = catalogDataResult.left().value();
- break;
- default:
- log.debug("Not supported component type {}", componentType);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- toscaElements.forEach(te -> {
- T component = ModelConverter.convertFromToscaElement(te);
- components.add(component);
- });
- return Either.left(components);
- }
-
- public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
- Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
- List<String> deleted = new ArrayList<>();
- switch (componentType) {
- case RESOURCE:
- allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- case SERVICE:
- case PRODUCT:
- allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- default:
- log.debug("Not supported component type {}", componentType);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- if (allComponentsMarkedForDeletion.isRight()) {
- return Either.right(allComponentsMarkedForDeletion.right().value());
- }
- List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
-
- Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
- if (allNotDeletedElements.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+
+ latestComponents.add(toscaElementByOperation.left().value());
}
- List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
- for (GraphVertex elementV : allMarked) {
- if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
- Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
- if (deleteToscaElement.isRight()) {
- log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
+
+ if(latestComponents.size() > 1) {
+ for (Component component : latestComponents) {
+ if(component.isHighestVersion()){
+ LinkedList<Component> highestComponent = new LinkedList<>();
+ highestComponent.add(component);
+ return Either.left(highestComponent);
}
- } else {
- deleted.add(elementV.getUniqueId());
- log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
- }
- }
- return Either.left(deleted);
- }
-
- public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
- Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
- switch (componentType) {
- case RESOURCE:
- allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- case SERVICE:
- case PRODUCT:
- allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- default:
- log.debug("Not supported component type {}", componentType);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- if (allComponentsMarkedForDeletion.isRight()) {
- return Either.right(allComponentsMarkedForDeletion.right().value());
- }
- return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
- }
-
- public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- Either<Boolean, StorageOperationStatus> result;
- Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
- if (allNotDeletedElements.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
- } else {
- result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
- }
- return result;
- }
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
- Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
- componentInstance.setIcon(origComponent.getIcon());
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
- ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
-
- if (addResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
- result = Either.right(addResult.right().value());
- }
- if (result == null) {
- updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
- if (updateContainerComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
- result = Either.right(updateContainerComponentRes.right().value());
- }
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
- String createdInstanceId = addResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
- result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
- }
- return result;
- }
-
- public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
-
- StorageOperationStatus result = null;
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
-
- Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
- if (metadataVertex.isRight()) {
- TitanOperationStatus status = metadataVertex.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- }
- if (result == null) {
- result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
- }
- return result;
- }
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
- componentInstance.setIcon(origComponent.getIcon());
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
- ModelConverter.convertToToscaElement(origComponent), componentInstance);
- if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
- result = Either.right(updateResult.right().value());
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
- String createdInstanceId = updateResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
- result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
- }
- return result;
- }
-
- public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
-
- Either<Component, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
-
- Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
- if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
- result = Either.right(updateResult.right().value());
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
- result = Either.left(updatedComponent);
- }
- return result;
- }
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
-
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
- if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
- result = Either.right(updateResult.right().value());
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
- String deletedInstanceId = updateResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
- result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
- }
- return result;
- }
-
- private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
-
- Integer nextCounter = 0;
-
- if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
-
- String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
- Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
- Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
-
- if (maxCounterFromNames == null && maxCounterFromIds != null) {
- nextCounter = maxCounterFromIds + 1;
- } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
- nextCounter = maxCounterFromNames + 1;
- } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
- nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
- }
- }
- return nextCounter.toString();
- }
-
- private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
-
- Integer maxCounter = 0;
- List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
- .collect(Collectors.toList());
-
- if (CollectionUtils.isEmpty(countersStr)) {
- return null;
- }
- Integer currCounter = null;
- for (String counter : countersStr) {
- if (StringUtils.isEmpty(counter)) {
- continue;
- }
- try {
- currCounter = Integer.parseInt(counter);
- } catch (Exception e) {
- continue;
}
- maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
- }
- if (currCounter == null) {
- return null;
- }
- return maxCounter;
- }
-
- private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
-
- Integer maxCounter = 0;
- List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
- .collect(Collectors.toList());
-
- if (CollectionUtils.isEmpty(countersStr)) {
- return null;
- }
- Integer currCounter = null;
- for (String counter : countersStr) {
- if (StringUtils.isEmpty(counter)) {
- continue;
- }
- try {
- currCounter = Integer.parseInt(counter);
- } catch (Exception e) {
- continue;
- }
- maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
- }
- if (currCounter == null) {
- return null;
- }
- return maxCounter;
- }
-
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
- return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
-
- }
-
- public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
-
- StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
-
- if (StorageOperationStatus.OK == status) {
- log.debug("Component created successfully!!!");
- List<InputDefinition> inputsResList = null;
- if (inputsMap != null && !inputsMap.isEmpty()) {
- inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
- }
- return Either.left(inputsResList);
- }
- return Either.right(status);
-
- }
-
- public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
-
- StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
-
- if (StorageOperationStatus.OK == status) {
- log.debug("Component created successfully!!!");
- List<InputDefinition> inputsResList = null;
- if (inputsMap != null && !inputsMap.isEmpty()) {
- inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
- }
- return Either.left(inputsResList);
- }
- return Either.right(status);
-
- }
-
- public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
- if (instProperties != null) {
-
- MapPropertiesDataDefinition propertiesMap;
- for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
- propertiesMap = new MapPropertiesDataDefinition();
-
- propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
-
- instPropsMap.put(entry.getKey(), propertiesMap);
- }
- }
-
- StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
-
- if (StorageOperationStatus.OK == status) {
- log.debug("Component created successfully!!!");
- return Either.left(instProperties);
- }
- return Either.right(status);
-
- }
-
- public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- if (instProperties != null) {
-
- for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
- List<ComponentInstanceInput> props = entry.getValue();
- String componentInstanseId = entry.getKey();
- if (props != null && !props.isEmpty()) {
- for (ComponentInstanceInput property : props) {
- List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
- Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
- if (instanceProperty.isPresent()) {
- status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
- } else {
- status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
- }
- if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
- return Either.right(status);
- } else {
- log.trace("instance input {} for instance {} updated", property, componentInstanseId);
- }
- }
- }
- }
- }
- return Either.left(instProperties);
- }
-
- public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
- if (instProperties != null) {
-
- MapPropertiesDataDefinition propertiesMap;
- for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
- propertiesMap = new MapPropertiesDataDefinition();
-
- propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
-
- instPropsMap.put(entry.getKey(), propertiesMap);
- }
- }
-
- return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
-
- }
-
- public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- if (instProperties != null) {
-
- for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
- List<ComponentInstanceProperty> props = entry.getValue();
- String componentInstanseId = entry.getKey();
- List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
- if (props != null && !props.isEmpty()) {
- for (ComponentInstanceProperty property : props) {
- Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
- if (instanceProperty.isPresent()) {
- status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
- } else {
- status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
- }
-
- }
- }
- }
- }
-
- return Either.left(instProperties);
-
- }
-
- public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
- if (instArtifacts != null) {
-
- MapArtifactDataDefinition artifactsMap;
- for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
- Map<String, ArtifactDefinition> artList = entry.getValue();
- Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
- artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
-
- instArtMap.put(entry.getKey(), artifactsMap);
- }
- }
-
- return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap);
-
- }
-
- public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
- if (instArttributes != null) {
-
- MapPropertiesDataDefinition attributesMap;
- for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
- attributesMap = new MapPropertiesDataDefinition();
- attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- instAttr.put(entry.getKey(), attributesMap);
- }
- }
-
- return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
-
- }
-
- public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
-
- Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
-
- Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
- Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
- ;
- if (instCapabilties != null) {
- for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
-
- Map<String, List<CapabilityDefinition>> caps = entry.getValue();
- Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
- for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
- mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
- }
-
- ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
- MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
-
- MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
-
- calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
- calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
- }
- }
-
- if (instReg != null) {
- for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
-
- Map<String, List<RequirementDefinition>> req = entry.getValue();
- Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
- for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
- mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
- }
-
- MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
-
- calcRequirements.put(entry.getKey().getUniqueId(), capMap);
- }
- }
-
- StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
-
- return status;
- }
-
- private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
-
- Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
-
- fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
-
- Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
- if (getRes.isRight()) {
- if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<>());
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- }
- } else {
- List<Component> nonAbstractLatestComponents = new ArrayList<>();
- ComponentParametersView params = new ComponentParametersView(true);
- params.setIgnoreAllVersions(false);
- for (GraphVertex vertexComponent : getRes.left().value()) {
- Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
- if (componentRes.isRight()) {
- log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
- return Either.right(componentRes.right().value());
- } else {
- Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
-
- nonAbstractLatestComponents.add(component);
- }
- }
-
- return Either.left(nonAbstractLatestComponents);
- }
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
-
- Either<ComponentMetadataData, StorageOperationStatus> result;
-
- Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
-
- hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
- if (isHighest != null) {
- hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
- }
-
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
- if (getRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- } else {
- List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
- ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
- : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
- result = Either.left(latestVersion);
- }
- return result;
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
-
- Either<ComponentMetadataData, StorageOperationStatus> result;
- Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
- if (getRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- } else {
- ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
- result = Either.left(componentMetadata);
- }
- return result;
- }
-
- private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
- Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
- for (ComponentMetadataData resourceData : resourceDataList) {
- ComponentMetadataData latestVersionData = resourceData;
-
- ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
- Pair<String, String> pair = createKeyPair(latestVersionData);
- if (latestVersionMap.containsKey(pair)) {
- latestVersionData = latestVersionMap.get(pair);
- String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
- String newVersion = metadataDataDefinition.getVersion();
- if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
- latestVersionData = resourceData;
- }
- }
- if (log.isDebugEnabled())
- log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
-
- latestVersionMap.put(pair, latestVersionData);
- }
-
- Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
- for (ComponentMetadataData resourceData : latestVersionMap.values()) {
- ComponentMetadataData latestVersionData = resourceData;
- ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
- if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
- latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
- String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
- String newVersion = metadataDataDefinition.getVersion();
- if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
- latestVersionData = resourceData;
- }
- }
- if (log.isDebugEnabled())
- log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
- resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
- }
-
- return resVersionMap;
- }
-
- private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
- Pair<String, String> pair;
- NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
- switch (label) {
- case Resource:
- pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
- break;
- default:
- pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
- break;
- }
-
- return pair;
- }
-
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
-
- Either<List<Component>, StorageOperationStatus> result = null;
- List<Component> components = new ArrayList<>();
- if (componentUids == null) {
- Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
- if (componentUidsRes.isRight()) {
- result = Either.right(componentUidsRes.right().value());
- } else {
- componentUids = componentUidsRes.left().value();
- }
- }
- if (!componentUids.isEmpty()) {
- for (String componentUid : componentUids) {
- ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
- if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
- componentParametersView.setIgnoreCapabilities(false);
- componentParametersView.setIgnoreRequirements(false);
- }
- Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
- if (getToscaElementRes.isRight()) {
- if (log.isDebugEnabled())
- log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
- result = Either.right(getToscaElementRes.right().value());
- break;
- }
- Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
- component.setContactId(null);
- component.setCreationDate(null);
- component.setCreatorUserId(null);
- component.setCreatorFullName(null);
- component.setLastUpdateDate(null);
- component.setLastUpdaterUserId(null);
- component.setLastUpdaterFullName(null);
- component.setNormalizedName(null);
- components.add(component);
- }
- }
- if (result == null) {
- result = Either.left(components);
- }
- return result;
- }
-
- private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
-
- Either<List<String>, StorageOperationStatus> result = null;
- Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
- if (getToscaElementsRes.isRight()) {
- result = Either.right(getToscaElementsRes.right().value());
- } else {
- List<Component> collection = getToscaElementsRes.left().value();
- if (collection == null) {
- componentUids = new ArrayList<>();
- } else {
- componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
- }
- }
- if (result == null) {
- result = Either.left(componentUids);
- }
- return result;
- }
-
- private ComponentParametersView buildComponentViewForNotAbstract() {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreCategories(false);
- componentParametersView.setIgnoreAllVersions(false);
- return componentParametersView;
- }
-
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
- Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
- if (result.isLeft()) {
- result = Either.left(!result.left().value());
- }
- return result;
- }
-
- public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
- VertexTypeEnum vertexType = getVertexTypeByComponentAndResourceTypeEnum(resourceType, componentType);
- String normalizedName = ValidationUtils.normaliseComponentName(name);
- Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
- properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
- properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
- Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
- if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
- }
- List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
- if (vertexList != null && !vertexList.isEmpty()) {
- return Either.left(false);
- } else {
- return Either.left(true);
- }
- }
-
- // UI query parameter is either VFC/CP/VL(for yaml upload/update) or VF (for CSAR upload/user composed VF)
- // TODO implementation of topology template VFCs may require updating this method - depending on UI implementation
- private VertexTypeEnum getVertexTypeByComponentAndResourceTypeEnum(ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
- VertexTypeEnum vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE;
- if (ComponentTypeEnum.RESOURCE == componentType && ResourceTypeEnum.VF != resourceType) {
- vertexType = VertexTypeEnum.NODE_TYPE;
- }
- return vertexType;
- }
-
- private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
- switch (internalComponentType.toLowerCase()) {
- case "vf":
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
- break;
- case "service":
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFC.name());
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
- break;
- case "vl":
- hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
- break;
- default:
- break;
- }
- }
-
- private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, ComponentTypeEnum componentTypeEnum) {
- switch (componentTypeEnum) {
- case RESOURCE:
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- break;
- case SERVICE:
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- break;
- default:
- break;
- }
- }
-
- private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
- hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
-
- hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
- hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
- hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
- if (internalComponentType != null) {
- fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
- }
- } else {
- fillTopologyTemplatePropsMap(hasProps, componentTypeEnum);
- }
- }
-
- private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
- List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
- if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
- internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
- }
- if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType)) {
- internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
- }
- return internalVertexTypes;
- }
-
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
- List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
- List<Component> result = new ArrayList<>();
- for (VertexTypeEnum vertexType : internalVertexTypes) {
- Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
- if (listByVertexType.isRight()) {
- return listByVertexType;
- }
- result.addAll(listByVertexType.left().value());
- }
- return Either.left(result);
-
- }
-
- public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
- return componentListByUuid;
- }
-
- public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- if (additionalPropertiesToMatch != null) {
- propertiesToMatch.putAll(additionalPropertiesToMatch);
- }
-
- propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
-
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
-
- if (vertexEither.isRight()) {
- log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
- }
- List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
-
- if (vertexList == null || vertexList.isEmpty()) {
- log.debug("Component with uuid {} was not found", componentUuid);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- ArrayList<Component> latestComponents = new ArrayList<>();
- for (GraphVertex vertex : vertexList) {
- Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
-
- if(toscaElementByOperation.isRight()){
- log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
- return Either.right(toscaElementByOperation.right().value());
- }
-
- latestComponents.add(toscaElementByOperation.left().value());
- }
-
- if(latestComponents.size() > 1) {
- for (Component component : latestComponents) {
- if(component.isHighestVersion()){
- LinkedList<Component> highestComponent = new LinkedList<>();
- highestComponent.add(component);
- return Either.left(highestComponent);
- }
- }
- }
+ }
- return Either.left(latestComponents);
- }
-
- public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
-
- Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
-
- if (latestVersionListEither.isRight()) {
- return Either.right(latestVersionListEither.right().value());
- }
-
- List<Component> latestVersionList = latestVersionListEither.left().value();
-
- if (latestVersionList.isEmpty()) {
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
-
- return Either.left(component);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
-
- List<Resource> resources = new ArrayList<>();
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
- if (isHighest != null) {
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
- }
- propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
-
- if (getResourcesRes.isRight()) {
- log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
- }
- List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
- for (GraphVertex resourceV : resourceVerticies) {
- Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
- if (getResourceRes.isRight()) {
- return Either.right(getResourceRes.right().value());
- }
- resources.add(getResourceRes.left().value());
- }
- return Either.left(resources);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
- Either<T, StorageOperationStatus> result;
-
- Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
-
- hasProperties.put(GraphPropertyEnum.NAME, name);
- hasProperties.put(GraphPropertyEnum.VERSION, version);
- hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
- hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
- if (getResourceRes.isRight()) {
- TitanOperationStatus status = getResourceRes.right().value();
- log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- return getToscaElementByOperation(getResourceRes.left().value().get(0));
- }
-
- public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
- return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
- }
-
- public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
- Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
- props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- if (componentType != null) {
- props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- }
- Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
- propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
-
- GraphVertex resourceMetadataData = null;
- List<GraphVertex> resourceMetadataDataList = null;
- Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
- if (byCsar.isRight()) {
- if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
- // Fix Defect DE256036
- if (StringUtils.isEmpty(systemName)) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
- }
-
- props.clear();
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
- Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
- if (bySystemname.isRight()) {
- log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
- }
- if (bySystemname.left().value().size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- resourceMetadataDataList = bySystemname.left().value();
- if (resourceMetadataDataList.size() == 1) {
- resourceMetadataData = resourceMetadataDataList.get(0);
- } else {
- for (GraphVertex curResource : resourceMetadataDataList) {
- if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
- resourceMetadataData = curResource;
- break;
- }
- }
- }
- if (resourceMetadataData == null) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
- log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
- // correct error will be returned from create flow. with all
- // correct audit records!!!!!
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
- return resource;
- }
- } else {
- resourceMetadataDataList = byCsar.left().value();
- if (resourceMetadataDataList.size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- if (resourceMetadataDataList.size() == 1) {
- resourceMetadataData = resourceMetadataDataList.get(0);
- } else {
- for (GraphVertex curResource : resourceMetadataDataList) {
- if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
- resourceMetadataData = curResource;
- break;
- }
- }
- }
- if (resourceMetadataData == null) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
- return resource;
- }
- return null;
- }
-
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
-
- String currentTemplateNameChecked = templateNameExtends;
-
- while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
-
- if (latestByToscaResourceName.isRight()) {
- return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
- }
-
- Resource value = latestByToscaResourceName.left().value();
-
- if (value.getDerivedFrom() != null) {
- currentTemplateNameChecked = value.getDerivedFrom().get(0);
- } else {
- currentTemplateNameChecked = null;
- }
- }
-
- return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
- }
-
- public Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) {
-
- Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
- props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props);
-
- if (resourcesByTypeEither.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
- }
-
- List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
- List<Component> components = new ArrayList<>();
-
- for (GraphVertex vertex : vertexList) {
- components.add(getToscaElementByOperation(vertex).left().value());
- }
-
- return Either.left(components);
-
- }
-
- public void commit() {
- titanDao.commit();
- }
-
- public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
- Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
- if (updateDistributionStatus.isRight()) {
- return Either.right(updateDistributionStatus.right().value());
- }
- GraphVertex serviceV = updateDistributionStatus.left().value();
- service.setDistributionStatus(distributionStatus);
- service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
- return Either.left(service);
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
-
- Either<ComponentMetadataData, StorageOperationStatus> result = null;
- GraphVertex serviceVertex;
- Either<GraphVertex, TitanOperationStatus> updateRes = null;
- Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
- if (getRes.isRight()) {
- TitanOperationStatus status = getRes.right().value();
- log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- serviceVertex = getRes.left().value();
- long lastUpdateDate = System.currentTimeMillis();
- serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
- component.setLastUpdateDate(lastUpdateDate);
- updateRes = titanDao.updateVertex(serviceVertex);
- if (updateRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
- }
- }
- if (result == null) {
- result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
- }
- return result;
- }
-
- public TitanDao getTitanDao() {
- return titanDao;
- }
-
- public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- return getServicesWithDistStatus(distStatus, propertiesToMatch);
- }
-
- public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
-
- List<Service> servicesAll = new ArrayList<>();
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
- propertiesToMatch.putAll(additionalPropertiesToMatch);
- }
-
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
-
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- if (distStatus != null && !distStatus.isEmpty()) {
- for (DistributionStatusEnum state : distStatus) {
- propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
- Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
- if (fetchServicesByCriteria.isRight()) {
- return fetchServicesByCriteria;
- } else {
- servicesAll = fetchServicesByCriteria.left().value();
- }
- }
- return Either.left(servicesAll);
- } else {
- return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
- }
- }
-
- // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
- // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- // if (getRes.isRight()) {
- // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
- // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- // }
- // } else {
- // for (GraphVertex vertex : getRes.left().value()) {
- // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
- // if (getServiceRes.isRight()) {
- // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
- // return Either.right(getServiceRes.right().value());
- // } else {
- // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
- // }
- // }
- // }
- // return Either.left(servicesAll);
- // }
-
- private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
- Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- if (getRes.isRight()) {
- if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- }
- } else {
- for (GraphVertex vertex : getRes.left().value()) {
- // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
- Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
-
- if (getServiceRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
- return Either.right(getServiceRes.right().value());
- } else {
- servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
- }
- }
- }
- return Either.left(servicesAll);
- }
-
- public void rollback() {
- titanDao.rollback();
- }
-
- public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
- Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
-
- return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
- }
-
- public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
- return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
- }
-
- public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
- return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
-
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- newPropertyDefinition.setName(propertyName);
- newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
- StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreProperties(false);
- getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- PropertyDefinition newProperty = null;
- List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
- if (CollectionUtils.isNotEmpty(properties)) {
- Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
- if (newPropertyOptional.isPresent()) {
- newProperty = newPropertyOptional.get();
- }
- }
- if (newProperty == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- } else {
- result = Either.left(newProperty);
- }
- }
- return result;
- }
-
- public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
- return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
- }
-
- public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
- return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
- }
-
- public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
- return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreProperties(false);
- getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
- if (newProperty.isPresent()) {
- result = Either.left(newProperty.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
- String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
- newAttributeDef.setUniqueId(attUniqueId);
- }
-
- StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreAttributesFrom(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
- if (newAttribute.isPresent()) {
- result = Either.left(newAttribute.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreAttributesFrom(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
- if (newProperty.isPresent()) {
- result = Either.left(newProperty.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<InputDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreInputs(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
- if (updatedInput.isPresent()) {
- result = Either.left(updatedInput.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
- return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
- }
-
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
- return groupsOperation.updateGroups(component, componentType, updatedGroups);
- }
-
- public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
- return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
- }
-
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
- return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
- }
-
- public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
- return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
- }
-
- public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
- return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
- }
-
- public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
- return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
- }
-
- public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
- return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
- }
-
- public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
- return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
- }
-
- public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
- this.nodeTypeOperation = nodeTypeOperation;
- }
-
- public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
- this.topologyTemplateOperation = topologyTemplateOperation;
+ return Either.left(latestComponents);
+ }
+
+ public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
+
+ Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
+
+ if (latestVersionListEither.isRight()) {
+ return Either.right(latestVersionListEither.right().value());
+ }
+
+ List<Component> latestVersionList = latestVersionListEither.left().value();
+
+ if (latestVersionList.isEmpty()) {
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
+
+ return Either.left(component);
+ }
+
+ public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
+
+ List<Resource> resources = new ArrayList<>();
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
+ if (isHighest != null) {
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
+ }
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+
+ if (getResourcesRes.isRight()) {
+ log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
+ }
+ List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
+ for (GraphVertex resourceV : resourceVerticies) {
+ Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
+ if (getResourceRes.isRight()) {
+ return Either.right(getResourceRes.right().value());
+ }
+ resources.add(getResourceRes.left().value());
+ }
+ return Either.left(resources);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.NAME, name);
+ hasProperties.put(GraphPropertyEnum.VERSION, version);
+ hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ if (getResourceRes.isRight()) {
+ TitanOperationStatus status = getResourceRes.right().value();
+ log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ return getToscaElementByOperation(getResourceRes.left().value().get(0));
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
+ return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ if (componentType != null) {
+ props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ }
+ Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
+ propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
+
+ GraphVertex resourceMetadataData = null;
+ List<GraphVertex> resourceMetadataDataList = null;
+ Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
+ if (byCsar.isRight()) {
+ if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
+ // Fix Defect DE256036
+ if (StringUtils.isEmpty(systemName)) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
+ }
+
+ props.clear();
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
+ Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
+ if (bySystemname.isRight()) {
+ log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
+ }
+ if (bySystemname.left().value().size() > 2) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ resourceMetadataDataList = bySystemname.left().value();
+ if (resourceMetadataDataList.size() == 1) {
+ resourceMetadataData = resourceMetadataDataList.get(0);
+ } else {
+ for (GraphVertex curResource : resourceMetadataDataList) {
+ if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
+ resourceMetadataData = curResource;
+ break;
+ }
+ }
+ }
+ if (resourceMetadataData == null) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
+ log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
+ // correct error will be returned from create flow. with all
+ // correct audit records!!!!!
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
+ return resource;
+ }
+ } else {
+ resourceMetadataDataList = byCsar.left().value();
+ if (resourceMetadataDataList.size() > 2) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ if (resourceMetadataDataList.size() == 1) {
+ resourceMetadataData = resourceMetadataDataList.get(0);
+ } else {
+ for (GraphVertex curResource : resourceMetadataDataList) {
+ if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
+ resourceMetadataData = curResource;
+ break;
+ }
+ }
+ }
+ if (resourceMetadataData == null) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
+ return resource;
+ }
+ return null;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
+
+ String currentTemplateNameChecked = templateNameExtends;
+
+ while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
+
+ if (latestByToscaResourceName.isRight()) {
+ return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
+ }
+
+ Resource value = latestByToscaResourceName.left().value();
+
+ if (value.getDerivedFrom() != null) {
+ currentTemplateNameChecked = value.getDerivedFrom().get(0);
+ } else {
+ currentTemplateNameChecked = null;
+ }
+ }
+
+ return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
+ }
+
+ public Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) {
+
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props);
+
+ if (resourcesByTypeEither.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
+ }
+
+ List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
+ List<Component> components = new ArrayList<>();
+
+ for (GraphVertex vertex : vertexList) {
+ components.add(getToscaElementByOperation(vertex).left().value());
+ }
+
+ return Either.left(components);
+
+ }
+
+ public void commit() {
+ titanDao.commit();
+ }
+
+ public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
+ Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
+ if (updateDistributionStatus.isRight()) {
+ return Either.right(updateDistributionStatus.right().value());
+ }
+ GraphVertex serviceV = updateDistributionStatus.left().value();
+ service.setDistributionStatus(distributionStatus);
+ service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
+ return Either.left(service);
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result = null;
+ GraphVertex serviceVertex;
+ Either<GraphVertex, TitanOperationStatus> updateRes = null;
+ Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ TitanOperationStatus status = getRes.right().value();
+ log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ serviceVertex = getRes.left().value();
+ long lastUpdateDate = System.currentTimeMillis();
+ serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
+ component.setLastUpdateDate(lastUpdateDate);
+ updateRes = titanDao.updateVertex(serviceVertex);
+ if (updateRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
+ }
+ }
+ if (result == null) {
+ result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
+ }
+ return result;
+ }
+
+ public TitanDao getTitanDao() {
+ return titanDao;
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ return getServicesWithDistStatus(distStatus, propertiesToMatch);
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+
+ List<Service> servicesAll = new ArrayList<>();
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
+
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ if (distStatus != null && !distStatus.isEmpty()) {
+ for (DistributionStatusEnum state : distStatus) {
+ propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
+ Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ if (fetchServicesByCriteria.isRight()) {
+ return fetchServicesByCriteria;
+ } else {
+ servicesAll = fetchServicesByCriteria.left().value();
+ }
+ }
+ return Either.left(servicesAll);
+ } else {
+ return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ }
+ }
+
+ // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+ // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ // if (getRes.isRight()) {
+ // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
+ // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ // }
+ // } else {
+ // for (GraphVertex vertex : getRes.left().value()) {
+ // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
+ // if (getServiceRes.isRight()) {
+ // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ // return Either.right(getServiceRes.right().value());
+ // } else {
+ // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
+ // }
+ // }
+ // }
+ // return Either.left(servicesAll);
+ // }
+
+ private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (getRes.isRight()) {
+ if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ }
+ } else {
+ for (GraphVertex vertex : getRes.left().value()) {
+ // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
+ Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
+
+ if (getServiceRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ return Either.right(getServiceRes.right().value());
+ } else {
+ servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
+ }
+ }
+ }
+ return Either.left(servicesAll);
+ }
+
+ public void rollback() {
+ titanDao.rollback();
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
+ Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+
+ return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
+ return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
+ return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
+
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ newPropertyDefinition.setName(propertyName);
+ newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
+ StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ PropertyDefinition newProperty = null;
+ List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
+ if (CollectionUtils.isNotEmpty(properties)) {
+ Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
+ if (newPropertyOptional.isPresent()) {
+ newProperty = newPropertyOptional.get();
+ }
+ }
+ if (newProperty == null) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ } else {
+ result = Either.left(newProperty);
+ }
+ }
+ return result;
+ }
+
+ public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
+ return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
+ return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
+ return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ if (newProperty.isPresent()) {
+ result = Either.left(newProperty.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
+ String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
+ newAttributeDef.setUniqueId(attUniqueId);
+ }
+
+ StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreAttributesFrom(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ if (newAttribute.isPresent()) {
+ result = Either.left(newAttribute.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreAttributesFrom(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ if (newProperty.isPresent()) {
+ result = Either.left(newProperty.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<InputDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreInputs(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
+ if (updatedInput.isPresent()) {
+ result = Either.left(updatedInput.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * method - ename the group instances after referenced container name renamed
+ * flow - VF rename -(triggers)-> Group rename
+ *
+ * @param containerComponent - container such as service
+ * @param componentInstance - context component
+ * @param componentInstanceId - id
+ *
+ * @return - successfull/failed status
+ * **/
+ public Either<StorageOperationStatus,StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId){
+ String uniqueId = componentInstance.getUniqueId();
+ StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement( containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId );
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
+ return Either.right(status);
+ }
+ status = addGroupInstancesToComponentInstance( containerComponent , componentInstance, componentInstance.getGroupInstances() );
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
+ return Either.right(status);
+ }
+ return Either.left(status);
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
+ return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
+ }
+
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
+ return groupsOperation.updateGroups(component, componentType, updatedGroups);
+ }
+
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
+ return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
+ return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
+ return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
+ }
+
+ public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
+ }
+
+ public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
+ this.nodeTypeOperation = nodeTypeOperation;
+ }
+
+ public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
+ this.topologyTemplateOperation = topologyTemplateOperation;
+ }
+
+ public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
+ return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
}
}
return vertexType;
}
- private static boolean isAtomicComponent(ResourceTypeEnum resourceType) {
- if (resourceType == null || resourceType == ResourceTypeEnum.VF)
+ public static boolean isAtomicComponent(ResourceTypeEnum resourceType) {
+ if (resourceType == null || resourceType == ResourceTypeEnum.VF || resourceType == ResourceTypeEnum.PNF || resourceType == ResourceTypeEnum.CVFC)
return false;
return true;
}
relationshipPair.setId(relation.getUniqueId());
relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId());
- relationshipPair.setCapabilityUid(relation.getCapabiltyId());
+ relationshipPair.setCapabilityUid(relation.getCapabilityId());
relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId());
relationshipPair.setRequirementUid(relation.getRequirementId());
relationshipPair.setRequirement(relation.getRequirement());
requirementCapabilityRelDef.setToId(relation.getToNode());
requirementCapabilityRelDef.setUniqueId(p.getId());
requirementCapabilityRelDef.setCapabilityOwnerId(p.getCapabilityOwnerId());
- requirementCapabilityRelDef.setCapabiltyId(p.getCapabilityUid());
+ requirementCapabilityRelDef.setCapabilityId(p.getCapabilityUid());
requirementCapabilityRelDef.setRequirementOwnerId(p.getRequirementOwnerId());
requirementCapabilityRelDef.setRequirementId(p.getRequirementUid());
requirementCapabilityRelDef.setRequirement(p.getRequirement());
resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME));
resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE));
+ // field isn't mandatory , but shouldn't be null(should be an empty string instead)
+ if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){
+ resource.setResourceVendorModelNumber(((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)));
+ } else {
+ resource.setResourceVendorModelNumber("");
+ }
+ } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
+ Service service = (Service) component;
+ if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){
+ service.setServiceType(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)));
+ } else {
+ service.setServiceType("");
+ }
+ if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){
+ service.setServiceRole(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)));
+ } else {
+ service.setServiceRole("");
+ }
}
component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL));
component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON));
toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName());
toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName());
toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease());
+ // field isn't mandatory , but shouldn't be null(should be an empty string instead)
+ if (((Resource) component).getResourceVendorModelNumber() != null){
+ toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber());
+ } else {
+ toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, "");
+ }
+ } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
+ // field isn't mandatory , but shouldn't be null(should be an empty string instead)
+ if (((Service) component).getServiceType() != null){
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType());
+ } else {
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, "");
+ }
+ if (((Service) component).getServiceRole() != null){
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole());
+ } else {
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, "");
+ }
}
toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel());
toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted());
toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId());
}
- private static boolean isAtomicComponent(Component component) {
+ public static boolean isAtomicComponent(Component component) {
ComponentTypeEnum componentType = component.getComponentType();
if (!componentType.equals(ComponentTypeEnum.RESOURCE)) {
return false;
import java.util.Map;
import java.util.Set;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import fj.data.Either;
public Either<Service, StorageOperationStatus> getService(String uniqueId, boolean inTransaction);
+ public Either<Service, StorageOperationStatus> getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction);
+
public Either<Service, StorageOperationStatus> deleteService(String uniqueId);
public Either<Service, StorageOperationStatus> deleteService(String uniqueId, boolean inTransaction);
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.model.ComponentInstanceProperty;
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.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.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.slf4j.Logger;
log.debug("Before adding {} to graph. data = {}", defName, someData);
+ @SuppressWarnings("unchecked")
Either<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData);
log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);
value = jsonElement.toString();
}
- return value;
+ return value;
}
protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
public List<PropertyConstraint> convertConstraints(List<String> constraints) {
- if (constraints == null || constraints.size() == 0) {
+ if (constraints == null || constraints.isEmpty()) {
return null;
}
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList());
-
}
}
case VL:
componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VL);
break;
+ case CVFC:
+ componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CVFC);
+ break;
+ case PNF:
+ componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PNF);
+ break;
+
}
break;
default:
case "service":
properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name()));
properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name()));
+ properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.CVFC.name()));
// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
// ResourceTypeEnum.VFC.name());
@Override
public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) {
return getElementType(this::getGroupTypeByUid, uniqueId, inTransaction);
-
}
@Override
@Override
public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction) {
return getElementType(this::getPolicyTypeByUid, uniqueId, inTransaction);
-
}
private Either<PolicyTypeDefinition, TitanOperationStatus> getPolicyTypeByUid(String uniqueId) {
private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
final boolean isScalarF, JsonElement entryValue) {
Object convertedValue;
+ if (entryValue.isJsonPrimitive()) {
+ return json2JavaPrimitive(entryValue.getAsJsonPrimitive());
+ }
JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
return true;
}
- String coverted = ValidationUtils.removeNoneUtf8Chars(value);
- return ValidationUtils.validateIsEnglish(coverted);
+ String converted = ValidationUtils.removeNoneUtf8Chars(value);
+ return ValidationUtils.validateIsEnglish(converted);
}
@Override
if (value.length() > STRING_MAXIMUM_LENGTH) {
return false;
}
- String coverted = ValidationUtils.removeNoneUtf8Chars(value);
- return ValidationUtils.validateIsEnglish(coverted);
+ String converted = ValidationUtils.removeNoneUtf8Chars(value);
+ return ValidationUtils.validateIsEnglish(converted);
}
@Override
log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH);
return false;
}
- String coverted = ValidationUtils.removeNoneUtf8Chars(value);
- boolean isValid = ValidationUtils.validateIsAscii(coverted);
+ String converted = ValidationUtils.removeNoneUtf8Chars(value);
+ boolean isValid = ValidationUtils.validateIsAscii(converted);
if (false == isValid && log.isDebugEnabled()) {
log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20)));
private String vendorName;
private String vendorRelease;
+ private String resourceVendorModelNumber;
private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC;
private Boolean isAbstract;
private String cost;
super(categories, metadata);
this.vendorName = metadata.getVendorName();
this.vendorRelease = metadata.getVendorRelease();
+ this.resourceVendorModelNumber = metadata.getResourceVendorModelNumber();
this.resourceType = metadata.getResourceType();
this.cost = metadata.getCost();
this.licenseType = metadata.getLicenseType();
public void setVendorRelease(String vendorRelease) {
this.vendorRelease = vendorRelease;
}
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
public ResourceTypeEnum getResourceType() {
return resourceType;
private String distributionStatus;
private Boolean ecompGeneratedNaming;
private String namingPolicy;
+ private String serviceType;
+ private String serviceRole;
public UiServiceMetadata(List<CategoryDefinition> categories, ServiceMetadataDataDefinition metadata) {
super(categories, metadata);
this.distributionStatus = metadata.getDistributionStatus();
this.ecompGeneratedNaming = metadata.isEcompGeneratedNaming();
this.namingPolicy = metadata.getNamingPolicy();
+ this.serviceType = metadata.getServiceType();
+ this.serviceRole = metadata.getServiceRole();
}
public String getDistributionStatus() {
public void setNamingPolicy(String namingPolicy) {
this.namingPolicy = namingPolicy;
}
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
}
--- /dev/null
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.junit.Test;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.*;
+
+public class ArtifactsOperationsTest {
+
+ private static final String SERVICE_ID = "serviceId";
+ private static final String INSTANCE_ID = "instanceId";
+ private ArtifactsOperations testInstance = mock(ArtifactsOperations.class, CALLS_REAL_METHODS);
+
+ @Test
+ public void getInstanceArtifacts_collectAllInstanceArtifacts() throws Exception {
+ Map<String, ToscaDataDefinition> instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1"));
+
+ Map<String, ToscaDataDefinition> instanceDeploymentArtifacts = new HashMap<>();
+ instanceDeploymentArtifacts.put(INSTANCE_ID, getArtifactsByInstance("name2", "name3"));
+ instanceDeploymentArtifacts.put("instanceId2", getArtifactsByInstance("name4"));
+
+ doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ doReturn(Either.left(instanceDeploymentArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID);
+
+ assertTrue(allInstArtifacts.isLeft());
+ assertEquals(allInstArtifacts.left().value().size(), 3);
+ assertTrue(allInstArtifacts.left().value().containsKey("name1"));
+ assertTrue(allInstArtifacts.left().value().containsKey("name2"));
+ assertTrue(allInstArtifacts.left().value().containsKey("name3"));
+ assertFalse(allInstArtifacts.left().value().containsKey("name4"));//this key is of different instance
+ }
+
+ @Test
+ public void getInstanceArtifacts_noArtifactsForInstance() throws Exception {
+ Map<String, ToscaDataDefinition> instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1"));
+
+ doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, "someOtherInstance");
+
+ assertTrue(allInstArtifacts.isLeft());
+ assertTrue(allInstArtifacts.left().value().isEmpty());
+ }
+
+ @Test
+ public void getInstanceArtifacts_errorGettingInstanceArtifacts() throws Exception {
+ doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID);
+ verify(testInstance, times(0)).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ assertTrue(allInstArtifacts.isRight());
+ }
+
+ @Test
+ public void getAllInstanceArtifacts_errorGettingDeploymentArtifacts() throws Exception {
+ doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID);
+ assertTrue(allInstArtifacts.isRight());
+ }
+
+ private ToscaDataDefinition getArtifactsByInstance(String ... artifactsNames) {
+ MapArtifactDataDefinition artifactsByInstance = new MapArtifactDataDefinition();
+ Map<String, ArtifactDataDefinition> artifactsByName = new HashMap<>();
+ for (String artifactName : artifactsNames) {
+ artifactsByName.put(artifactName, new ArtifactDataDefinition());
+ }
+ artifactsByInstance.setMapToscaDataDefinition(artifactsByName);
+ return artifactsByInstance;
+ }
+}
--- /dev/null
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.apache.cassandra.cql3.CQL3Type;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.*;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Created by chaya on 6/12/2017.
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+public class ToscaElementOperationTest extends ModelTestBase{
+
+ private List<GraphVertex> allVertices = new ArrayList<>();
+ private boolean isInitialized = false;
+
+ @javax.annotation.Resource
+ ToscaElementOperationTestImpl toscaElementOperation;
+
+ @javax.annotation.Resource
+ TitanDao titanDao;
+
+ @BeforeClass
+ public static void initTest(){
+ ModelTestBase.init();
+
+ }
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void beforeTest() {
+ if (!isInitialized) {
+ GraphTestUtils.clearGraph(titanDao);
+ //exportGraphMl(titanDao.getGraph().left().value(),"");
+ initGraphForTest();
+ isInitialized = true;
+ }
+ }
+
+ @Test
+ public void testGetAllHighestResourcesNoFilter() {
+
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ }
+ }, null);
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetAllResourcesCertifiedNoFilter() {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, null);
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ });
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetHighestResourcesExclude() {
+
+ // exclude VFCMT
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VFCMT);
+ assertTrue(genericTestGetResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP);
+ assertTrue(genericTestGetResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL & VF & VFC
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC);
+ assertTrue(genericTestGetResourcesWithExcludeList(excludeList));
+ }
+
+ @Test
+ public void testGetAllResourcesCertifiedExclude() {
+ // exclude VFCMT
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VFCMT);
+ assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP);
+ assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL & VF & VFC
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC);
+ assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList));
+ }
+
+ @Test
+ public void testGetAllHighestServicesNoFilter() {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ }
+ }, null);
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetAllCertifiedServicesNoFilter() {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, null);
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ });
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetServicesExcludeList() {
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VF, ResourceTypeEnum.VFCMT);
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ }
+ }, null);
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetCertifiedServicesExcludeList() {
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VL);
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, null);
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ });
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ private boolean genericTestGetResourcesWithExcludeList(List<ResourceTypeEnum> excludeList) {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludeList, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.RESOURCE_TYPE, excludeList);
+ }
+ });
+ return highestResources.stream().count() == (highestResourcesExpectedCount);
+ }
+
+ private boolean genericTestGetCertifiedResourcesWithExcludeList(List<ResourceTypeEnum> excludeList) {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludeList, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.RESOURCE_TYPE, excludeList);
+ }
+ });
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.RESOURCE_TYPE, excludeList);
+ }
+ });
+ return highestResources.stream().count() == highestResourcesExpectedCount;
+ }
+
+ private void initGraphForTest() {
+ Map<GraphPropertyEnum, Object> highstVerticesProps = new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ };
+
+ Map<GraphPropertyEnum, Object> certifiedVerticesProps = new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ };
+
+ // add vertices with higestVersion = true
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VF));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFC));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFCMT));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VL));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.CP));
+ allVertices.add(GraphTestUtils.createServiceVertex(titanDao, highstVerticesProps));
+
+ // add vertices with non-additional properties
+ for (int i=0 ; i<2 ; i++) {
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VF));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFC));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFCMT));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VL));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.CP));
+ allVertices.add(GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()));
+ }
+
+ // add certified vertices
+ for (int i=0; i<3; i++) {
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VF));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFC));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFCMT));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VL));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.CP));
+ allVertices.add(GraphTestUtils.createServiceVertex(titanDao, certifiedVerticesProps));
+ }
+ //allVertices.stream().forEach( v -> System.out.println("type: "+v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)));
+ //String result = GraphTestUtils.exportGraphMl(titanDao.getGraph().left().value(), "");
+ //System.out.println("graph is: " + result);
+ }
+
+ private long calculateCount(HashMap<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> doesntHaveProps){
+ return allVertices.stream().
+ filter(v -> {
+ Map<GraphPropertyEnum, Object> vertexProps = v.getMetadataProperties();
+ if (hasProps != null) {
+ for (Map.Entry<GraphPropertyEnum, Object> prop: hasProps.entrySet()){
+ Object value = vertexProps.get(prop.getKey());
+ if ( value == null || !value.equals(prop.getValue())) {
+ return false;
+ }
+ }
+ }
+
+ if (doesntHaveProps != null) {
+ for (Map.Entry<GraphPropertyEnum, Object> prop : doesntHaveProps.entrySet()) {
+ Object value = vertexProps.get(prop.getKey());
+ Object propValue = prop.getValue();
+ if ( value != null && propValue != null && propValue instanceof List ) {
+ for (ResourceTypeEnum propVal : (List<ResourceTypeEnum>)propValue) {
+ if (propVal.name().equals(value)) {
+ return false;
+ }
+ }
+ }
+ else if (value != null && value.equals(propValue)){
+ return false;
+ }
+ }
+ }
+ return true;
+ }).count();
+ }
+}
--- /dev/null
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+/**
+ * Created by cb478c on 6/13/2017.
+ */
+@org.springframework.stereotype.Component("test-tosca-element-operation")
+public class ToscaElementOperationTestImpl extends ToscaElementOperation {
+
+ @Override
+ protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
+ titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
+ T toscaElement = convertToComponent(vertexComponent);
+ return Either.left(toscaElement);
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
+
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.model.jsontitan.utils;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.io.IoCore;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.UUID;
+
+public final class GraphTestUtils {
+
+ public static GraphVertex createResourceVertex(TitanDao titanDao, Map<GraphPropertyEnum,Object> metadataProps, ResourceTypeEnum type) {
+ GraphVertex vertex = new GraphVertex();
+ if (type == ResourceTypeEnum.VF) {
+ vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ } else {
+ vertex.setLabel(VertexTypeEnum.NODE_TYPE);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE);
+ }
+ String uuid = UUID.randomUUID().toString();
+ vertex.setUniqueId(uuid);
+
+ vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name());
+ vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false);
+ for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) {
+ vertex.addMetadataProperty(prop.getKey(), prop.getValue());
+ }
+ titanDao.createVertex(vertex);
+ titanDao.commit();
+ return vertex;
+ }
+
+ public static GraphVertex createServiceVertex(TitanDao titanDao, Map<GraphPropertyEnum, Object> metadataProps){
+ GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ String uuid = UUID.randomUUID().toString();
+ vertex.setUniqueId(uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) {
+ vertex.addMetadataProperty(prop.getKey(), prop.getValue());
+ }
+ titanDao.createVertex(vertex);
+ titanDao.commit();
+ return vertex;
+ }
+
+ public static void clearGraph(TitanDao titanDao) {
+ Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph();
+ TitanGraph graph = graphResult.left().value();
+
+ Iterable<TitanVertex> vertices = graph.query().vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ while (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ vertex.remove();
+ }
+ }
+ titanDao.commit();
+ }
+
+ public static String exportGraphMl(TitanGraph graph, String outputDirectory) {
+ String result = null;
+ String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
+ try {
+ try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
+ graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
+ }
+ result = outputFile;
+ graph.tx().commit();
+ } catch (Exception e) {
+ graph.tx().rollback();
+ e.printStackTrace();
+ }
+ return result;
+ }
+}
-----------------------------
ADMIN
DESIGNER
-PRODUCT_STRATEGIST
-PRODUCT_MANAGER
TESTER
OPS
GOVERNOR
"POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
"GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
"GET_resource_artifact_types": "/v1/artifactTypes",
- "GET_product_catalog": "/v1/productScreen",
- "GET_product_category": "/v1/productCategories",
- "GET_product_category_temp": "/v1/artifactTypes",
- "POST_product": "/v1/catalog/products/:id/metadata",
- "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_product": "/v1/catalog/products/:id",
- "GET_product_sub_category": "/v1/productSubCategories",
"GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
"GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
"kibana": "/sdc1/kibanaProxy/"
},
"resourceTypesFilter":{
"resource":["CP","VFC","VL"],
- "service":["CP","VF","VL"],
- "product":[]
+ "service":["CP","VF","VL", "PNF","CVFC"]
},
"logConfig": {
"minLogLevel": "debug",
"default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
}
},
- "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
+ "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER"],
"tutorial": {
"tabs": [
{
}
};
-module.exports = SDC_CONFIG;
\ No newline at end of file
+module.exports = SDC_CONFIG;
"title": "Designer's Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": true,
- "showCreateNewProduct": false
+ "showCreateNew": true
},
"changeLifecycleStateButtons":{
"NOT_CERTIFIED_CHECKOUT":{ "submitForTesting": {"text":"Submit for Testing", "url":"lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
]
},
- "PRODUCT_STRATEGIST":{
- "title": "Product Strategist's Workspace",
- "pages":[],
- "dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
- },
- "changeLifecycleStateButtons":{},
-
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
- "PRODUCT_MANAGER":{
- "title": "Product Manager Workspace",
- "pages":[],
- "dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": true
- },
- "changeLifecycleStateButtons":{
- "NOT_CERTIFIED_CHECKOUT":{ "checkIn": {"text":"Check in", "url":"lifecycleState/CHECKIN", "confirmationModal": "lifecycleState/CHECKIN"},
- "deleteVersion":{"text":"Delete Version", "url":"lifecycleState/UNDOCHECKOUT", "alertModal": "lifecycleState/UNDOCHECKOUT"}
- },
- "NOT_CERTIFIED_CHECKIN":{ "checkOut": {"text":"Check Out", "url":"lifecycleState/CHECKOUT"}
- }
- },
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
"TESTER":{
"title": "Tester's Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
+ "showCreateNew": false
},
"changeLifecycleStateButtons":{
"READY_FOR_CERTIFICATION":{ "startTesting": {"text":"Start Testing", "url":"lifecycleState/startCertification"}
"title": "Operations Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
+ "showCreateNew": false
},
"changeLifecycleStateButtons":{
"DISTRIBUTION_APPROVED":{ "distribute": {"text":"Distribute", "url":"distribution/PROD/activate", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
"title": "Governance Rep's Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
+ "showCreateNew": false
},
"changeLifecycleStateButtons":{
"DISTRIBUTION_NOT_APPROVED":{ "approve": {"text":"Approve", "url":"distribution-state/approve", "confirmationModal": "distribution-state/approve", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
}
},
- "PRODUCT_MANAGER":{
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ],
- "NOT_OWNER":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
- "PRODUCT_STRATEGIST":{
- "title": "Product Strategist's Workspace",
- "pages":[],
- "dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": true
- },
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ],
- "NOT_OWNER":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
"OTHER":{
"states":{
"ANY":{
"component_workspace_menu_option": {
"VFC":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
],
"VL":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
],
"CP":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
],
"VF":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
// {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.resource_inputs"},
{"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
],
+ "PNF":[
+ {"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
+ {"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
+ {"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
+ {"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"},
+ {"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
+ {"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
+ ],
"SERVICE":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
{"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"},
{"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
{"text":"Management Workflow", "action":"onMenuItemPressed", "state": "workspace.management_workflow"},
{"text":"Network Call Flow ", "action":"onMenuItemPressed", "state": "workspace.network_call_flow"},
- {"text":"Monitor ", "action":"onMenuItemPressed", "state": "workspace.distribution", "disabledRoles": ["ADMIN", "TESTER", "GOVERNOR", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"]},
+ {"text":"Monitor ", "action":"onMenuItemPressed", "state": "workspace.distribution", "disabledRoles": ["ADMIN", "TESTER", "GOVERNOR", "DESIGNER"]},
{"text":"Deployment", "action":"onMenuItemPressed", "state": "workspace.deployment"},
// {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.service_inputs"},
{"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
- ],
- "PRODUCT":[
- {"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Hierarchy", "action":"onMenuItemPressed", "state": "workspace.hierarchy"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
- {"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"}
]
}
"firstName": "op",
"lastName": "ss",
"xEcompRequestId": "ccccc"
- },
- "product_strategist": {
- "userId": "ps0001",
- "email": "product_strategist@sdc.com",
- "firstName": "Orit",
- "lastName": "Barda",
- "xEcompRequestId": "ccccc"
- },
- "product_manager": {
- "userId": "pm0001",
- "email": "product_manager@sdc.com",
- "firstName": "Orit",
- "lastName": "Barda",
- "xEcompRequestId": "ccccc"
}
},
"statuses": {
"POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
"GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
"GET_resource_artifact_types": "/v1/artifactTypes",
- "GET_product_catalog": "/v1/productScreen",
- "GET_product_category": "/v1/productCategories",
- "GET_product_category_temp": "/v1/artifactTypes",
- "POST_product": "/v1/catalog/products/:id/metadata",
- "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_product": "/v1/catalog/products/:id",
- "GET_product_sub_category": "/v1/productSubCategories",
"GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
"GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
"kibana": "/sdc1/kibanaProxy/"
},
"resourceTypesFilter":{
"resource":["CP","VFC","VL"],
- "service":["CP","VF","VL"],
- "product":[]
+ "service":["CP","VF","VL", "PNF","CVFC"]
},
"logConfig": {
"minLogLevel": "debug",
"default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
}
},
- "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
+ "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER"],
"tutorial": {
"tabs": [
{
]
}
-
};
module.exports = SDC_CONFIG;
</excludes>
<followSymlinks>false</followSymlinks>
</fileset>
- <fileset>
- <directory>${basedir}/node_modules</directory>
- </fileset>
</filesets>
</configuration>
</execution>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.4</version>
-
+
<configuration>
<installDirectory>${project.parent.basedir}</installDirectory>
</configuration>
-
+
<executions>
<execution>
<id>install node and npm</id>
<npmVersion>3.10.10</npmVersion>
</configuration>
</execution>
-
+
<execution>
<id>npm set progress off</id>
<goals>
data: {unsavedChanges: false, bodyClass: 'general'}
}
);
- //
- $stateProvider.state(
- States.WORKSPACE_ICONS, {
- url: 'icons',
- parent: 'workspace',
- controller: viewModelsModuleName + '.IconsViewModel',
- templateUrl: './view-models/workspace/tabs/icons/icons-view.html',
- data: {unsavedChanges: false, bodyClass: 'icons'}
-
- }
- );
$stateProvider.state(
States.WORKSPACE_ACTIVITY_LOG, {
}
);
- $stateProvider.state(
- States.WORKSPACE_HIERARCHY, {
- url: 'hierarchy',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ProductHierarchyViewModel',
- templateUrl: './view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html',
- data: {unsavedChanges: false}
-
- }
- );
-
$stateProvider.state(
States.WORKSPACE_INFORMATION_ARTIFACTS, {
url: 'information_artifacts',
ng1appModule.value('ComponentNameValidationPattern', /^(?=.*[^. ])[\s\w\&_.:-]{1,1024}$/); //DE250513 - same as ValidationPattern above, plus requirement that name not consist of dots and/or spaces alone.
ng1appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
-ng1appModule.value('VendorValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
+ng1appModule.value('VendorReleaseValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
ng1appModule.value('VendorNameValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,60}$/);
ng1appModule.value('VendorModelNumberValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,65}$/);
ng1appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
categoryResourceService.getAllCategories((categories: Categories):void => {
cacheService.set('serviceCategories', categories.serviceCategories);
cacheService.set('resourceCategories', categories.resourceCategories);
- cacheService.set('productCategories', categories.productCategories);
}, onError);
};
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
{
selector: 'node',
css: {
- 'font-family': 'omnes-regular,sans-serif',
+ 'font-family': 'OpenSans-Regular,sans-serif',
+
'font-size': 14,
'events': 'yes',
'text-events': 'yes',
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
-import {
- Component,
- IAppMenu,
- LeftPanelModel,
- NodesFactory,
- LeftPaletteComponent,
- CompositionCiNodeBase,
- ComponentInstance
-} from "app/models";
+import {Component, IAppMenu, LeftPanelModel, NodesFactory, LeftPaletteComponent, CompositionCiNodeBase, ComponentInstance} from "app/models";
import {CompositionGraphGeneralUtils} from "../composition-graph/utils/composition-graph-general-utils";
import {EventListenerService} from "app/services";
import {ResourceType, GRAPH_EVENTS, EVENTS, ComponentInstanceFactory, ModalsHandler} from "app/utils";
import 'sdc-angular-dragdrop';
import {LeftPaletteLoaderService} from "../../../services/components/utils/composition-left-palette-service";
+import {Resource} from "app/models/components/resource";
+import {ComponentType} from "app/utils/constants";
interface IPaletteScope {
components:Array<LeftPaletteComponent>;
el.append(this.nodeHtmlSubstitute);
this.registerEventListenerForLeftPalette(scope);
// this.LeftPaletteLoaderService.loadLeftPanel(scope.currentComponent.componentType);
-
+
this.initComponents(scope);
this.initEvents(scope);
this.initDragEvents(scope);
});
};
- private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
- if (scope.currentComponent.isResource()) {
- this.EventListenerService.registerObserverCallback(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT, () => {
- this.updateLeftPanelDisplay(scope);
- });
- }
- if (scope.currentComponent.isService()) {
- this.EventListenerService.registerObserverCallback(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT, () => {
- this.updateLeftPanelDisplay(scope);
- });
- }
- if (scope.currentComponent.isProduct()) {
- this.EventListenerService.registerObserverCallback(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT, () => {
- this.updateLeftPanelDisplay(scope);
- });
+ private getUpdateLeftPaletteEventName = (component:Component):string => {
+ switch (component.componentType) {
+ case ComponentType.SERVICE:
+ return EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT;
+ case ComponentType.RESOURCE:
+ if((<Resource>component).resourceType == ResourceType.PNF){
+ return EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT;
+ }else{
+ return EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT;
+ }
+ default:
+ console.log('ERROR: Component type '+ component.componentType + ' is not exists');
}
};
+ private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
+ let updateEventName:string = this.getUpdateLeftPaletteEventName(scope.currentComponent);
+ this.EventListenerService.registerObserverCallback(updateEventName, () => {
+ this.updateLeftPanelDisplay(scope);
+ });
+ };
+
private unRegisterEventListenerForLeftPalette = (scope:IPaletteScope):void => {
- if (scope.currentComponent.isResource()) {
- this.EventListenerService.unRegisterObserver(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
- }
- if (scope.currentComponent.isService()) {
- this.EventListenerService.unRegisterObserver(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
- }
- if (scope.currentComponent.isProduct()) {
- this.EventListenerService.unRegisterObserver(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT);
- }
+ let updateEventName:string = this.getUpdateLeftPaletteEventName(scope.currentComponent);
+ this.EventListenerService.unRegisterObserver(updateEventName);
};
private leftPanelResourceFilter(resourcesNotAbstract:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):Array<LeftPaletteComponent> {
private updateLeftPanelDisplay(scope:IPaletteScope) {
let entityType:string = scope.currentComponent.componentType.toLowerCase();
let resourceFilterTypes:Array<string> = this.sdcConfig.resourceTypesFilter[entityType];
- scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType);
+ scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent);
scope.model = this.initLeftPanel(scope.components, resourceFilterTypes);
scope.displaySortedCategories = angular.copy(scope.model.sortedCategories);
};
return;
}
- let component = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType), (componentFullData:LeftPaletteComponent) => {
+ let component = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent), (componentFullData:LeftPaletteComponent) => {
return displayComponent.uniqueId === componentFullData.uniqueId;
});
this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, scope.dragElement, component);
this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, event);
};
scope.setElementTemplate = (e) => {
- let dragComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType),
+ let dragComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent),
(fullComponent:LeftPaletteComponent) => {
return (<any>angular.element(e.currentTarget).scope()).component.uniqueId === fullComponent.uniqueId;
});
</div>
<div data-ng-if="isSchemaTypeDataType" class="i-sdc-form-item map-item-field">
<label class="i-sdc-form-label">Value</label>
- <fields-structure value-obj-ref="valueObjRef[mapKeys[$index]]"
+ <fields-structure value-obj-ref="valueObjRef[mapKeysStatic[$index]]"
type-name="schemaProperty.type"
parent-form-obj="parentFormObj"
fields-prefix-name="'mapValue'+fieldsPrefixName+''+$index"
isSchemaTypeDataType:boolean;
valueObjRef:any;
mapKeys:Array<string>;//array of map keys
+ mapKeysStatic:Array<string>;
MapKeyValidationPattern:RegExp;
fieldsPrefixName:string;
readOnly:boolean;
scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty);
if (scope.valueObjRef) {
scope.mapKeys = Object.keys(scope.valueObjRef);
+ //keeping another copy of the keys, as the mapKeys gets overridden sometimes
+ scope.mapKeysStatic = Object.keys(scope.valueObjRef);
}
});
scope.valueObjRef = {};
}
scope.mapKeys = Object.keys(scope.valueObjRef);
+ //keeping another copy of the keys, as the mapKeys gets overridden sometimes
+ scope.mapKeysStatic = Object.keys(scope.valueObjRef);
if ($attr.defaultValue) {
scope.mapDefaultValue = JSON.parse($attr.defaultValue);
<ul>
<li data-ng-repeat="firstLevelResourcesInstances in structureTree.serviceRoot.resourceInstancesList">
<div class="component-container">
- <div class="small {{firstLevelResourcesInstances.icon}}" ng-class="{'sprite-resource-icons': !component.isProduct(), 'sprite-services-icons': component.isProduct()}">
+ <div class="small sprite-resource-icons {{firstLevelResourcesInstances.icon}}">
<div data-ng-class="{'non-certified':!firstLevelResourcesInstances.certified}"
tooltips tooltip-side="top" tooltip-content="Not certified">
</div>
.tags-box {
- height: 297px;
+ height: 100px;
.bg_c;
.perfect-scrollbar {
- height: 265px;
+ height: 70px;
}
.new-tag-input {
export * from './models/comments';
export * from './models/components/component';
export * from './models/components/displayComponent';
-export * from './models/components/product';
export * from './models/components/resource';
export * from './models/components/service';
export * from './models/componentsInstances/componentInstance';
-export * from './models/componentsInstances/productInstance';
export * from './models/componentsInstances/resourceInstance';
export * from './models/componentsInstances/serviceInstance';
export * from './models/csar-component';
export * from './models/user';
export * from './models/validate';
export * from './models/component-metadata';
-
+export * from './models/modal';
export * from './models/button';
export * from './models/filter-properties-assignment-data'
export * from './models/properties-inputs/input-be-model'
GET_activity_log:string;
GET_configuration_ui:string;
GET_service:string;
- PUT_product:string;
- GET_product:string;
GET_ecomp_menu_items:string;
- GET_product_validate_name:string;
GET_service_validate_name:string;
GET_service_distributions:string;
GET_service_distributions_components:string;
GET_onboarding:string;
GET_component_from_csar_uuid:string;
kibana:string;
-
- //Added by Ikram -- starts
- GET_product_category:string;
- GET_product_category_temp:string;
- GET_product_sub_category:string;
- //Added by Ikram -- ends
-
}
export interface ILogConfig {
TESTER:IConfigRole;
OPS:IConfigRole;
GOVERNOR:IConfigRole;
- PRODUCT_MANAGER:IConfigRole;
- PRODUCT_STRATEGIST:IConfigRole;
}
export interface IConfigRole {
export class Categories {
resourceCategories:Array<IMainCategory>;
- productCategories:Array<IMainCategory>;
serviceCategories:Array<IMainCategory>;
}
public vendorName:string;
public vendorRelease:string;
public derivedFrom: Array<string>;
+ public resourceVendorModelNumber:string;
//Service only
public projectCode:string;
public distributionStatus:string;
public ecompGeneratedNaming: boolean;
public namingPolicy: string;
+ public serviceType:string;
+ public serviceRole:string;
//backend lifecycleState
this.ecompGeneratedNaming = response.ecompGeneratedNaming;
this.namingPolicy = response.namingPolicy;
this.derivedFrom = response.derivedFrom;
+ this.resourceVendorModelNumber = response.resourceVendorModelNumber;
+ this.serviceType = response.serviceType;
+ this.serviceRole = response.serviceRole;
return this;
}
import {AsdcComment, ArtifactModel, ArtifactGroupModel, IFileDownload, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
InputModel, DisplayModule, Module, IValidate, RelationshipModel, IMainCategory, RequirementsGroup, CapabilitiesGroup, AdditionalInformationModel,
- Resource, IAppMenu, Product, Service} from "../../models";
+ Resource, IAppMenu, Service} from "../../models";
import {IComponentService} from "../../services/components/component-service";
import {CommonUtils} from "../../utils/common-utils";
getComponentSubType():string;
isAlreadyCertified():boolean;
- isProduct():boolean;
isService():boolean;
isResource():boolean;
isComplex():boolean;
//------------------------------------------ Help Functions ----------------------------------------------------------------//
- public isProduct = ():boolean => {
- return this instanceof Product;
- };
-
public isService = ():boolean => {
return this instanceof Service;
};
case ComponentType.SERVICE:
this.iconClass = "sprite-services-icons " + icon;
break;
- case ComponentType.PRODUCT:
- this.iconClass = "sprite-product-icons " + icon;
- break;
default:
this.iconClass = "sprite-resource-icons " + icon;
}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/**
- * Created by obarda on 2/4/2016.
- */
-'use strict';
-import {Component} from "./component";
-import {IProductService} from "../../services/components/product-service";
-import {IGroup, ISubCategory, IMainCategory, ICategoryBase} from "../category";
-import {ComponentMetadata} from "../component-metadata";
-
-export class Product extends Component {
-
- public contacts:Array<string>;
- public componentService:IProductService;
- public fullName:string;
-
- constructor(componentService:IProductService, $q:ng.IQService, component?:Product) {
- super(componentService, $q, component);
-
- if (component) {
- this.fullName = component.fullName;
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
- this.contacts = component.contacts;
- }
- this.componentService = componentService;
- this.iconSprite = "sprite-product-icons";
- }
-
- public deleteGroup = (uniqueId:string):void => {
- _.forEach(this.categories, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- subcategory.groupings = _.reject(subcategory.groupings, (group:IGroup) => {
- return group.uniqueId === uniqueId;
- });
- if (subcategory.groupings.length == 0) { // if there is no groups, delete the subcategory
- category.subcategories = _.reject(category.subcategories, (subcategoryObj:ISubCategory) => {
- return subcategoryObj.uniqueId === subcategory.uniqueId;
- });
- if (category.subcategories.length == 0) { // if there is no subcategory, delete the category
- this.categories = _.reject(this.categories, (categoryObj:IMainCategory) => {
- return categoryObj.uniqueId === category.uniqueId;
- });
- }
- }
- });
- });
- };
-
- private getCategoryObjectById = (categoriesArray:Array<ICategoryBase>, categoryUniqueId:string):ICategoryBase => {
- let categorySelected = _.find(categoriesArray, (category) => {
- return category.uniqueId === categoryUniqueId;
- });
- return categorySelected;
- };
-
- public addGroup = (category:IMainCategory, subcategory:ISubCategory, group:IGroup):void => {
- if (!this.categories) {
- this.categories = new Array<IMainCategory>();
- }
- let existingCategory:IMainCategory = <IMainCategory>this.getCategoryObjectById(this.categories, category.uniqueId);
- let newGroup = angular.copy(group);
- newGroup.filterTerms = undefined;
- newGroup.isDisabled = undefined;
- if (!existingCategory) {
- let newCategory:IMainCategory = angular.copy(category);
- newCategory.filteredGroup = undefined;
- newCategory.subcategories = [];
- let newSubcategory:ISubCategory = angular.copy(subcategory);
- newSubcategory.groupings = [];
- newSubcategory.groupings.push(newGroup);
- newCategory.subcategories.push(newSubcategory);
- this.categories.push(newCategory);
- }
- else {
- let existingSubcategory:ISubCategory = <ISubCategory> this.getCategoryObjectById(existingCategory.subcategories, subcategory.uniqueId);
- if (!existingSubcategory) {
- let newSubcategory:ISubCategory = angular.copy(subcategory);
- newSubcategory.groupings = [];
- newSubcategory.groupings.push(newGroup);
- existingCategory.subcategories.push(newSubcategory);
-
- } else {
- let existingGroup:IGroup = <IGroup> this.getCategoryObjectById(existingSubcategory.groupings, group.uniqueId);
- if (!existingGroup) {
- existingSubcategory.groupings.push(newGroup);
- }
- }
- }
- };
-
- getTypeUrl():string {
- return 'products/';
- }
-
- public setComponentMetadata(componentMetadata:ComponentMetadata) {
- super.setComponentMetadata(componentMetadata);
- this.setComponentDisplayData();
- };
-
- setComponentDisplayData():void {
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
- this.iconSprite = "sprite-product-icons";
- }
-}
-
-
public payloadData:string;
public payloadName:string;
public importedFile:FileUploadModel;
+ public resourceVendorModelNumber:string;
// Onboarding parameters
public csarUUID:string;
this.resourceType = component.resourceType;
this.csarUUID = component.csarUUID;
this.csarVersion = component.csarVersion;
+ this.resourceVendorModelNumber = component.resourceVendorModelNumber;
this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version + ' ' + this.resourceType;
if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
component.mainCategory = component.categories[0].name;
this.csarUUID = componentMetadata.csarUUID;
this.csarVersion = componentMetadata.csarVersion;
this.derivedFrom = componentMetadata.derivedFrom;
+ this.resourceVendorModelNumber = componentMetadata.resourceVendorModelNumber;
this.setComponentDisplayData();
};
};
public isComplex = ():boolean => {
- return this.resourceType === ResourceType.VF;
+ return this.resourceType === ResourceType.VF || this.resourceType === ResourceType.PNF || this.resourceType === ResourceType.CVFC;
};
public isVl = ():boolean => {
public componentService:IServiceService;
public ecompGeneratedNaming:boolean;
public namingPolicy:string;
+ public serviceType:string;
+ public serviceRole:string;
constructor(componentService:IServiceService, $q:ng.IQService, component?:Service) {
super(componentService, $q, component);
this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
this.ecompGeneratedNaming = component.ecompGeneratedNaming;
this.namingPolicy = component.namingPolicy;
+ this.serviceType = component.serviceType;
+ this.serviceRole = component.serviceRole;
if (component.categories && component.categories[0]) {
this.mainCategory = component.categories[0].name;
this.selectedCategory = this.mainCategory;
super.setComponentMetadata(componentMetadata);
this.ecompGeneratedNaming = componentMetadata.ecompGeneratedNaming;
this.namingPolicy = componentMetadata.namingPolicy;
+ this.serviceType = componentMetadata.serviceType;
+ this.serviceRole = componentMetadata.serviceRole;
this.setComponentDisplayData();
}
public inputs:Array<InputModel>;
public properties:Array<PropertyModel>;
public groupInstances:Array<Module>;
+ public invariantName:string;
constructor(componentInstance?:ComponentInstance) {
this.customizationUUID = componentInstance.customizationUUID;
this.updatePosition(componentInstance.posX, componentInstance.posY);
this.groupInstances = componentInstance.groupInstances;
+ this.invariantName = componentInstance.invariantName;
}
}
};
public isComplex = () : boolean => {
- return this.originType === ResourceType.VF;
+ return this.originType === ResourceType.VF || this.originType === ResourceType.PNF || this.originType === ResourceType.CVFC ;
}
public setInstanceRC = ():void=> {
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/**
- * Created by obarda on 2/4/2016.
- */
-'use strict';
-import {ComponentInstance} from "./componentInstance";
-
-export class ProductInstance extends ComponentInstance {
-
- constructor(componentInstance?:ProductInstance) {
- super(componentInstance);
- this.iconSprite = "sprite-product-icons";
- }
-}
--- /dev/null
+import { ButtonModel } from 'app/models';
+
+export class ModalModel {
+ size: string; 'xl|l|md|sm|xsm'
+ title: string;
+ content: any;
+ buttons: Array<ButtonModel>;
+
+ constructor(size?: string, title?: string, content?: any, buttons?: Array<ButtonModel>) {
+ this.size = size;
+ this.title = title;
+ this.content = content;
+ this.buttons = buttons;
+ }
+}
+
}
}
-}
+}
\ No newline at end of file
} catch (e){}
}
- return (this.derivedDataType == DerivedPropertyType.SIMPLE) ? this.valueObj : JSON.stringify(this.valueObj);
+ return (this.derivedDataType == DerivedPropertyType.SIMPLE) ? this.valueObj : JSON.stringify(this.valueObj);
}
public setNonDeclared = (childPath?: string): void => {
// this.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName)
// }
- /* Updates parent valueObj when a child prop's value has changed */
- public childPropUpdated = (childProp: DerivedFEProperty): void => {
+ /* Updates parent valueObj when a child prop's value has changed */
+ public childPropUpdated = (childProp: DerivedFEProperty): void => {
let parentNames = this.getParentNamesArray(childProp.propertiesName, []);
if (parentNames.length) {
_.set(this.valueObj, parentNames.join('.'), childProp.valueObj);
}
};
- /* Returns array of individual parents for given prop path, with list/map UUIDs replaced with index/mapkey */
- private getParentNamesArray = (parentPropName: string, parentNames?: Array<string>): Array<string> => {
+ /* Returns array of individual parents for given prop path, with list/map UUIDs replaced with index/mapkey */
+ public getParentNamesArray = (parentPropName: string, parentNames?: Array<string>): Array<string> => {
if (parentPropName.indexOf("#") == -1) { return parentNames; } //finished recursing parents. return
let parentProp: DerivedFEProperty = this.flattenedChildren.find(prop => prop.propertiesName === parentPropName);
DESIGNER,
TESTER,
GOVERNOR,
- OPS,
- PRODUCT_MANAGER,
- PRODUCT_STRATEGIST
+ OPS
}
export interface IUserManager {
case UserRole.OPS:
role = UserRole.OPS;
break;
- case UserRole.PRODUCT_MANAGER:
- role = UserRole.PRODUCT_MANAGER;
- break;
- case UserRole.PRODUCT_STRATEGIST:
- role = UserRole.PRODUCT_STRATEGIST;
- break;
}
return role;
}
import {ComponentService} from "../services/components/component-service";
import {ServiceService} from "../services/components/service-service";
import {ResourceService} from "../services/components/resource-service";
-import {ProductService} from "../services/components/product-service";
import {LeftPaletteLoaderService} from "../services/components/utils/composition-left-palette-service";
import {EventListenerService} from "../services/event-listener-service";
import {ProgressService} from "../services/progress-service";
serviceModule.service('Sdc.Services.Components.ComponentService', ComponentService);
serviceModule.service('Sdc.Services.Components.ServiceService',ServiceService);
serviceModule.service('Sdc.Services.Components.ResourceService', ResourceService);
-serviceModule.service('Sdc.Services.Components.ProductService', ProductService);
serviceModule.service('LeftPaletteLoaderService', LeftPaletteLoaderService);
serviceModule.service('EventListenerService', EventListenerService);
serviceModule.service('Sdc.Services.ProgressService', ProgressService);
import {DistributionStatusModalViewModel} from "../view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model";
import {DcaeAppViewModel} from "../view-models/dcae-app/dcae-app-view-model";
import {GeneralViewModel} from "../view-models/workspace/tabs/general/general-view-model";
-import {IconsViewModel} from "../view-models/workspace/tabs/icons/icons-view-model";
+import {IconsModalViewModel} from "../view-models/modals/icons-modal/icons-modal-view";
import {DeploymentArtifactsViewModel} from "../view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model";
import {InformationArtifactsViewModel} from "../view-models/workspace/tabs/information-artifacts/information-artifacts-view-model";
import {ToscaArtifactsViewModel} from "../view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model";
import {PropertiesViewModel} from "../view-models/workspace/tabs/properties/properties-view-model";
import {AttributesViewModel} from "../view-models/workspace/tabs/attributes/attributes-view-model";
-import {ProductHierarchyViewModel} from "../view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model";
import {ActivityLogViewModel} from "../view-models/workspace/tabs/activity-log/activity-log";
import {ManagementWorkflowViewModel} from "../view-models/workspace/tabs/management-workflow/management-workflow-view-model";
import {NetworkCallFlowViewModel} from "../view-models/workspace/tabs/network-call-flow/network-call-flow-view-model";
.controller(moduleName + '.UserManagementViewModel', UserManagementViewModel)
.controller(moduleName + '.CategoryManagementViewModel', CategoryManagementViewModel)
.controller(moduleName + '.OnboardingModalViewModel', OnboardingModalViewModel)
+ .controller(moduleName + '.IconsModalViewModel', IconsModalViewModel)
.controller(moduleName + '.DistributionStatusModalViewModel', DistributionStatusModalViewModel)
.controller(moduleName + '.DcaeAppViewModel', DcaeAppViewModel)
//
.controller(moduleName + '.ConformanceLevelModalViewModel', ConformanceLevelModalViewModel)
.controller(moduleName + '.CompositionViewModel', CompositionViewModel)
.controller(moduleName + '.GeneralViewModel', GeneralViewModel)
- .controller(moduleName + '.IconsViewModel', IconsViewModel)
.controller(moduleName + '.DeploymentArtifactsViewModel', DeploymentArtifactsViewModel)
.controller(moduleName + '.InformationArtifactsViewModel', InformationArtifactsViewModel)
.controller(moduleName + '.ToscaArtifactsViewModel', ToscaArtifactsViewModel)
.controller(moduleName + '.PropertiesViewModel', PropertiesViewModel)
.controller(moduleName + '.AttributesViewModel', AttributesViewModel)
- .controller(moduleName + '.ProductHierarchyViewModel', ProductHierarchyViewModel)
.controller(moduleName + '.ActivityLogViewModel', ActivityLogViewModel)
.controller(moduleName + '.ManagementWorkflowViewModel', ManagementWorkflowViewModel)
.controller(moduleName + '.NetworkCallFlowViewModel', NetworkCallFlowViewModel)
* ============LICENSE_END=========================================================
*/
-import { Component, Inject } from '@angular/core';
+import { Component, Inject, ViewContainerRef } from '@angular/core';
import { AuthenticationService } from './services/authentication.service';
@Component({
})
export class AppComponent {
- constructor(auth:AuthenticationService){
+ constructor(auth:AuthenticationService, public viewContainerRef:ViewContainerRef){
}
+++ /dev/null
-<modal #confirmationModal title="Delete Input" size="sm" [buttons]="footerButtons">
- Are you sure you want to delete this input?
-</modal>
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/**
- * Created by rc2122 on 6/1/2017.
- */
-import {Component, Output, EventEmitter, ViewChild} from "@angular/core";
-import {ButtonsModelMap, ButtonModel} from "app/models/button";
-import {ModalComponent} from "app/ng2/components/modal/modal.component";
-
-@Component({
- selector: 'confirm-delete-input',
- templateUrl: './confirmation-delete-input.component.html'
-})
-export class ConfirmationDeleteInputComponent {
-
- @Output() deleteInput: EventEmitter<any> = new EventEmitter<any>();
- @ViewChild ('confirmationModal') confirmationModal:ModalComponent;
- footerButtons:ButtonsModelMap = {};
-
- constructor (){
- }
-
- ngOnInit() {
- this.footerButtons['Delete'] = new ButtonModel('Delete', 'blue', this.onDeleteInput);
- this.footerButtons['Close'] = new ButtonModel('Close', 'grey', this.closeModal);
- }
-
- onDeleteInput = (input) => {
- this.deleteInput.emit(input);
- this.closeModal();
- };
-
- openModal = () => {
- this.confirmationModal.open();
- }
-
- closeModal = () => {
- this.confirmationModal.close();
- }
-}
</div>
</div>
</div>
-<confirm-delete-input #deleteInputConfirmation (deleteInput)="onDeleteInput()"></confirm-delete-input>
*/
import {Component, Input, Output, EventEmitter, ViewChild} from "@angular/core";
import {InputFEModel} from "app/models";
-import {ConfirmationDeleteInputComponent} from "./confirmation-delete-input/confirmation-delete-input.component";
+import { ModalService } from 'app/ng2/services/modal.service';
+
+
@Component({
selector: 'inputs-table',
@Input() isLoading:boolean;
@Output() inputValueChanged: EventEmitter<any> = new EventEmitter<any>();
@Output() deleteInput: EventEmitter<any> = new EventEmitter<any>();
- @ViewChild ('deleteInputConfirmation') deleteInputConfirmation:ConfirmationDeleteInputComponent;
selectedInputToDelete:InputFEModel;
- constructor (){
+ constructor(private modalService: ModalService){
}
onInputValueChanged = (input) => {
onDeleteInput = () => {
this.deleteInput.emit(this.selectedInputToDelete);
+ this.modalService.closeCurrentModal();
};
openDeleteModal = (input:InputFEModel) => {
this.selectedInputToDelete = input;
- this.deleteInputConfirmation.openModal();
+ this.modalService.openActionModal("Delete Input", "Are you sure you want to delete this input?", "Delete", this.onDeleteInput, "Close");
}
}
-<div class="custom-modal {{size}}">
+<div class="custom-modal {{input.size}}">
<div class="ng2-modal-content">
<div class="ng2-modal-header">
- <span class="title">{{ title }}</span>
+ <span class="title">{{ input.title }}</span>
<span class="close-button" (click)="close()"></span>
</div>
- <div class="ng2-modal-body">
- <ng-content></ng-content>
- </div>
+ <div class="ng2-modal-body" >{{input.content}}</div>
<div class="ng2-modal-footer">
- <button *ngFor="let buttonName of buttonsNames"
- class="tlv-btn {{buttons[buttonName].cssClass}}"
- [disabled] = "buttons[buttonName].getDisabled && buttons[buttonName].getDisabled()"
- (click) = "buttons[buttonName].callback()">{{buttons[buttonName].text}}</button>
+ <button *ngFor="let button of input.buttons"
+ class="tlv-btn {{button.cssClass}}"
+ [disabled] = "button.getDisabled && button.getDisabled()"
+ (click) = "button.callback()">{{button.text}}</button>
</div>
</div>
</div>
* Created by rc2122 on 6/1/2017.
*/
import { Component, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
+//import {ViewContainerRef, ViewChild} from '@angular/core';
import * as $ from 'jquery';
-import {ButtonsModelMap} from "app/models/button";
+import { ButtonsModelMap, ModalModel } from 'app/models';
@Component({
selector: 'modal',
})
export class ModalComponent implements OnInit, OnDestroy {
- @Input() size: string; 'xl|l|md|sm|xsm'
- @Input() title: string;
- @Input() public buttons:ButtonsModelMap;
+ @Input() input: ModalModel;
private modalElement: JQuery;
- private buttonsNames:Array<string>;
+ //@ViewChild('modalBody', { read: ViewContainerRef }) modalContainer: ViewContainerRef; //TODO: allow for custom component as body instead of simple message
+
constructor( el: ElementRef ) {
this.modalElement = $(el.nativeElement);
}
ngOnInit(): void {
- let modal = this;
this.modalElement.appendTo('body');
- if(this.buttons){
- this.buttonsNames = Object.keys(this.buttons);
- }
}
ngOnDestroy(): void {
--- /dev/null
+import { NgModule } from "@angular/core";
+import { CommonModule } from '@angular/common';
+import { ModalService } from 'app/ng2/services/modal.service';
+import { ModalComponent } from "app/ng2/components/modal/modal.component"
+
+@NgModule({
+ declarations: [
+ ModalComponent,
+ ],
+ imports: [CommonModule],
+ exports: [],
+ entryComponents: [
+ ModalComponent
+ ],
+ providers: [ModalService]
+})
+export class ModalModule {
+
+}
\ No newline at end of file
<!-- LEFT CELL -->
<ng-container *ngIf="!isPropertyFEModel">
<div class="table-cell" *ngIf="canBeDeclared" [ngClass]="{'filtered':property.name === propertyNameSearchText}" [class.round-checkbox]="property.isDeclared"> <!-- simple children of complex type [@checkEffect]="property.isDeclared"-->
- <checkbox [(checked)]="property.isSelected" [disabled]="property.isDisabled ||property.isDeclared || readonly" (checkedChange)="checkProperty.emit(property.propertiesName)" ></checkbox>
+ <checkbox [(checked)]="property.isSelected" [disabled]="property.isDisabled ||property.isDeclared || readonly" (checkedChange)="checkProperty.emit(property.propertiesName)" ></checkbox>
<div class="inner-cell-div" tooltip="{{property.name}}"><span>{{property.name}}</span></div>
</div>
<div class="table-cell" *ngIf="!canBeDeclared && !property.isChildOfListOrMap">{{property.name}}</div> <!-- simple children of complex type within map or list -->
<div class="table-cell map-entry" *ngIf="property.isChildOfListOrMap && propType == derivedPropertyTypes.MAP"><!-- map left cell -->
- <input [value]="property.mapKey" #mapKey (change)="mapKeyChanged.emit(mapKey.value)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly}" />
+ <input [value]="property.mapKey" #mapKey (change)="mapKeyChanged.emit(mapKey)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly, 'error':!mapKey.validity.valid}" />
</div>
</ng-container>
<!-- RIGHT CELL OR FULL WIDTH CELL-->
</ng-container>
<!-- ICONS: add, delete, and expand -->
<ng-container *ngIf="!property.isDeclared">
- <a *ngIf="(propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && !property.isChildOfListOrMap" class="property-icon add-item" (click)="createNewChildProperty();" [ngClass]="{'disabled':readonly}">Add value to list</a>
+ <a *ngIf="(propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && !property.isChildOfListOrMap" class="property-icon add-item" (click)="createNewChildProperty();" [ngClass]="{'disabled':readonly || preventInsertItem(property)}">Add value to list</a>
<span *ngIf="property.isChildOfListOrMap" (click)="deleteItem.emit(property);" class="property-icon sprite-new delete-item-icon" [ngClass]="{'disabled':readonly}"></span>
<span *ngIf="!isPropertyFEModel && (propType == derivedPropertyTypes.COMPLEX || ((propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && hasChildren()))" (click)="expandChildById(propPath)" class="property-icon sprite-new round-expand-icon" [class.open]="expandedChildId.indexOf(propPath) == 0"></span>
</ng-container>
+@import '../../../../../assets/styles/variables.less';
.flat-children-container {
.dynamic-property-row {
/*create nested left border classes for up to 10 levels of nesting*/
overflow: hidden;
display: inline;
padding-left: 8px;
-}
\ No newline at end of file
+}
+.error {
+ border: solid 1px @func_color_q;
+ color: @func_color_q;
+ outline: none;
+ box-sizing: border-box;
+}
}
createNewChildProperty = (): void => {
-
+
let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, "", undefined);
if (this.property instanceof PropertyFEModel) {
this.addChildProps(newProps, this.property.name);
}
addChildProps = (newProps: Array<DerivedFEProperty>, childPropName: string) => {
-
+
if (this.property instanceof PropertyFEModel) {
- let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
- this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
+ let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
+ this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
this.expandChildById(newProps[0].propertiesName);
+
+
+ if(!newProps[0].schema.property.isSimpleType){
+ angular.forEach(newProps, (prop:DerivedFEProperty):void => { //Update parent PropertyFEModel with value for each child, including nested props
+ (<PropertyFEModel>this.property).childPropUpdated(prop);
+ },this);
+ //grab the cumulative value for the new item from parent PropertyFEModel and assign that value to DerivedFEProp[0] (which is the list or map parent with UUID of the set we just added)
+ let parentNames = (<PropertyFEModel>this.property).getParentNamesArray(newProps[0].propertiesName, []);
+ newProps[0].valueObj = _.get(this.property.valueObj, parentNames.join('.'));
+ this.valueChanged.emit(this.property.name);
+ }
}
}
this.dataTypeService.checkForCustomBehavior(this.property);
this.valueChanged.emit(this.property.name);
}
- }
+ }
deleteListOrMapItem = (item: DerivedFEProperty) => {
if (this.property instanceof PropertyFEModel) {
}
}
- removeValueFromParent = (item: DerivedFEProperty, replaceKey?: string) => {
+ removeValueFromParent = (item: DerivedFEProperty, target?: any) => {
if (this.property instanceof PropertyFEModel) {
let itemParent = (item.parentName == this.property.name) ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
if (item.derivedDataType == DerivedPropertyType.MAP) {
let oldKey = item.mapKey;
- if (typeof replaceKey == 'string') { //allow saving empty string
- _.set(itemParent.valueObj, replaceKey, itemParent.valueObj[oldKey]);
- item.mapKey = replaceKey;
+ if (target && typeof target.value == 'string') { //allow saving empty string
+ let replaceKey:string = target.value;
+ if(Object.keys(itemParent.valueObj).indexOf(replaceKey) > -1){//the key is exists
+ target.setCustomValidity('This key is already exists.');
+ return;
+ }else {
+ target.setCustomValidity('');
+ _.set(itemParent.valueObj, replaceKey, itemParent.valueObj[oldKey]);
+ item.mapKey = replaceKey;
+ }
}
delete itemParent.valueObj[oldKey];
} else {
}
}
+ preventInsertItem = (property:DerivedFEProperty):boolean => {
+ if(property.type == PROPERTY_TYPES.MAP && Object.keys(property.valueObj).indexOf('') > -1 ){
+ return true;
+ }
+ return false;
+ }
+
}
import { PropertiesUtils } from './properties.utils';
import { DynamicElementModule } from 'app/ng2/components/dynamic-element/dynamic-element.module';
import { DynamicPropertyComponent } from './../../components/properties-table/dynamic-property/dynamic-property.component';
-import {ConfirmationDeleteInputComponent} from "app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component"
-import { PopoverModule } from "../../components/popover/popover.module"
+import { PopoverModule } from "../../components/popover/popover.module";
+import { ModalModule } from "../../components/modal/modal.module";
import { FilterPropertiesAssignmentComponent } from "./../../components/filter-properties-assignment/filter-properties-assignment.component";
import { GroupByPipe } from 'app/ng2/pipes/groupBy.pipe';
import { KeysPipe } from 'app/ng2/pipes/keys.pipe';
import {TooltipModule} from "../../components/tooltip/tooltip.module";
import { ComponentModeService } from "app/ng2/services/component-mode.service"
-import { ModalComponent } from "app/ng2/components/modal/modal.component"
import {LoaderComponent} from "app/ng2/components/loader/loader.component"
import {HttpInterceptor} from "../../services/http.interceptor.service";
// PopoverContentComponent,
// PopoverComponent,
FilterPropertiesAssignmentComponent,
- ModalComponent,
- ConfirmationDeleteInputComponent,
LoaderComponent
],
imports: [
CheckboxModule,
DynamicElementModule,
PopoverModule,
- TooltipModule
+ TooltipModule,
+ ModalModule
],
entryComponents: [PropertiesAssignmentComponent],
exports: [
.left-column {
flex: 1 0 500px;
position: relative;
- margin: 0 0 1em 0;
/deep/ .tabs {
width:33%;
display:flex;
flex:0 0 350px;
flex-direction:column;
- margin: 45px 0 1em 1em;
+ margin: 45px 0 0 1em;
overflow-x:auto;
/deep/ .tabs {
});
}
+ if(resourceInstance.componentName === "vnfConfiguration") {
+ this.isReadonly = true;
+ }
+
if( this.searchPropertyName ){
this.clearSearch();
}
angular.forEach(instancesIds, (instanceId: string): void => {
let selectedInstanceData: ResourceInstance = this.instances.find(instance => instance.uniqueId == instanceId);
- let originType: string = (selectedInstanceData) ? selectedInstanceData.originType : this.selectedInstanceType;
+ let originType: string = (selectedInstanceData) ? selectedInstanceData.originType : this.selectedInstanceType;
if (!this.isInput(originType)) {
selectedProperties[instanceId] = this.propertiesService.getCheckedProperties(this.instanceFePropertiesMap[instanceId]);
} else {
};
private isInput = (instanceType:string):boolean =>{
- return instanceType === ResourceType.VF || instanceType === ResourceType.PNF;
+ return instanceType === ResourceType.VF || instanceType === ResourceType.PNF || instanceType === ResourceType.CVFC;
}
}
let propNameInObj = prop.propertiesName.substring(prop.propertiesName.indexOf(parentName) + parentName.length + 1).split('#').join('.'); //extract everything after parent name
prop.valueObj = _.get(parentValueJSON, propNameInObj, prop.value || prop.defaultValue); //assign value -first value of parent if exists. If not, prop.value if not, prop.defaultvalue
- if ((prop.derivedDataType == DerivedPropertyType.SIMPLE || prop.isDeclared) && typeof prop.valueObj == 'object') { //Stringify objects that should be strings
+ if ( prop.isDeclared && typeof prop.valueObj == 'object') { //Stringify objects of items that are declared
prop.valueObj = JSON.stringify(prop.valueObj);
+ } else if(typeof prop.valueObj == PROPERTY_TYPES.STRING
+ && (prop.type == PROPERTY_TYPES.INTEGER || prop.type == PROPERTY_TYPES.FLOAT || prop.type == PROPERTY_TYPES.BOOLEAN)){ //parse ints and non-string simple types
+ prop.valueObj = JSON.parse(prop.valueObj);
} else { //parse strings that should be objects
if (prop.derivedDataType == DerivedPropertyType.COMPLEX && typeof prop.valueObj != 'object') {
prop.valueObj = JSON.parse(prop.valueObj || '{}');
private getServerTypeUrl = (componentType:string):string => {
switch (componentType) {
- case ComponentType.PRODUCT:
- return ServerTypeUrl.PRODUCTS;
case ComponentType.SERVICE:
return ServerTypeUrl.SERVICES;
default:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
-import { sdc2Config } from './../../../main';
-import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';
+import {sdc2Config} from './../../../main';
+import {Interceptor, InterceptedRequest, InterceptedResponse} from 'ng2-interceptors';
import {SharingService} from "../../services/sharing-service";
import {ReflectiveInjector} from '@angular/core';
import {Cookie2Service} from "./cookie.service";
import {SEVERITY} from "../../utils/constants";
import {IServerMessageModalModel} from "../../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model";
+
export class HttpInterceptor implements Interceptor {
- private cookieService: Cookie2Service;
+ private cookieService:Cookie2Service;
private sharingService:SharingService;
+
constructor() {
- let injector = ReflectiveInjector.resolveAndCreate([Cookie2Service,SharingService]);
+ let injector = ReflectiveInjector.resolveAndCreate([Cookie2Service, SharingService]);
this.cookieService = injector.get(Cookie2Service);
this.sharingService = injector.get(SharingService);
}
- public interceptBefore(request: InterceptedRequest): InterceptedRequest {
-
+ public interceptBefore(request:InterceptedRequest):InterceptedRequest {
/**
* For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
* Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
*/
-
request.options.headers.append(this.cookieService.getUserIdSuffix(), this.cookieService.getUserId());
request.options.withCredentials = true;
var uuidValue = this.getUuidValue(request.url);
}
request.options.headers.set('X-ECOMP-RequestID', UUID.UUID());
return request;
-
}
public interceptAfter(response:InterceptedResponse):InterceptedResponse {
//console.log("Error from BE:",response);
}
return response;
-
}
- private getUuidValue = (url: string) :string => {
+ private getUuidValue = (url:string):string => {
let map:Dictionary<string, string> = this.sharingService.getUuidMap();
if (map && url.indexOf(sdc2Config.api.root) > 0) {
map.forEach((key:string) => {
severity: SEVERITY.ERROR
};
}
- // let modalsHandler = this.$injector.get('ModalsHandler');
- // this.modalsHandler.openServerMessageModal(data);
console.error('ERROR data',data);
}
}
--- /dev/null
+import { Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef } from '@angular/core';
+import { ModalModel, ButtonModel } from 'app/models';
+import { ModalComponent } from 'app/ng2/components/modal/modal.component';
+
+
+@Injectable()
+export class ModalService {
+ currentModal: ComponentRef<any>;
+
+
+ constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
+
+
+ /* Shortcut method to open a simple modal with title, message, and close button that simply closes the modal. */
+ public openAlertModal(title: string, message: string, closeButtonText?:string) {
+ let closeButton: ButtonModel = new ButtonModel(closeButtonText || 'Close', 'grey', this.closeCurrentModal);
+ let modalModel: ModalModel = new ModalModel('sm', title, message, [closeButton]);
+ this.createCustomModal(modalModel).instance.open();
+ }
+
+
+ /**
+ * Shortcut method to open a basic modal with title, message, and an action button with callback, as well as close button.
+ * NOTE: To close the modal from within the callback, use modalService.closeCurrentModal() //if you run into zone issues with callbacks see:https://stackoverflow.com/questions/36566698/how-to-dynamically-create-bootstrap-modals-as-angular2-components
+ * @param title Heading for modal
+ * @param message Message for modal
+ * @param actionButtonText Blue call to action button
+ * @param actionButtonCallback function to invoke when button is clicked
+ * @param cancelButtonText text for close/cancel button
+ */
+ public openActionModal = (title:string, message:string, actionButtonText:string, actionButtonCallback:Function, cancelButtonText:string) => {
+ let actionButton: ButtonModel = new ButtonModel(actionButtonText, 'blue', actionButtonCallback);
+ let cancelButton: ButtonModel = new ButtonModel(cancelButtonText, 'grey', this.closeCurrentModal);
+ let modalModel: ModalModel = new ModalModel('sm', title, message, [actionButton, cancelButton]);
+ this.createCustomModal(modalModel).instance.open();
+ }
+
+
+ /* Use this method to create a modal with title, message, and completely custom buttons. Use response.instance.open() to open */
+ public createCustomModal = (customModalData: ModalModel): ComponentRef<ModalComponent> => {
+ let customModal: ComponentRef<ModalComponent> = this.createDynamicComponent(ModalComponent);
+ customModal.instance.input = customModalData;
+ this.currentModal = customModal;
+
+ return customModal;
+ }
+
+
+ public closeCurrentModal = () => {
+ if (!this.currentModal) return;
+ this.currentModal.instance.close();
+ this.currentModal.destroy();
+ }
+
+
+ //Creates a component dynamically (aka during runtime). If a view container is not specified, it will append the new component to the app root.
+ //To subscribe to an event from invoking component: componentRef.instance.clicked.subscribe((m) => console.log(m.name));
+ private createDynamicComponent<T>(componentType: Type<T>, viewContainerRef?:ViewContainerRef): ComponentRef<any> {
+
+ viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
+ viewContainerRef.clear();
+
+ let factory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
+ let componentRef = viewContainerRef.createComponent(factory);
+
+ return componentRef;
+ }
+
+
+ private getRootViewContainerRef(): ViewContainerRef {
+ return this.applicationRef.components[0].instance.viewContainerRef;
+ }
+}
\ No newline at end of file
export * from './services/configuration-ui-service';
export * from './services/category-resource-service';
export * from './services/components/component-service';
-export * from './services/components/product-service';
export * from './services/components/resource-service';
export * from './services/components/service-service';
export * from './services/components/resource-service';
'firewall'
];
break;
-
- case ComponentType.PRODUCT:
- icons = [
- 'vfw',
- 'network',
- 'security',
- 'cloud',
- 'setting',
- 'orphan',
- 'wanx',
- 'vrouter',
- 'ucpe',
- 'mobility'
-
- ];
- break;
-
}
return icons;
}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/**
- * Created by obarda on 2/8/2016.
- */
-'use strict';
-import {IComponentService, ComponentService} from "./component-service";
-import {SharingService} from "../sharing-service";
-import {Product, Component, IAppConfigurtaion} from "../../models";
-
-export interface IProductService extends IComponentService {
-
-}
-
-export class ProductService extends ComponentService implements IProductService {
-
- static '$inject' = [
- 'Restangular',
- 'sdcConfig',
- 'Sdc.Services.SharingService',
- '$q',
- '$base64'
- ];
-
- constructor(protected restangular:restangular.IElement,
- protected sdcConfig:IAppConfigurtaion,
- protected sharingService:SharingService,
- protected $q:ng.IQService,
- protected $base64:any) {
- super(restangular, sdcConfig, sharingService, $q, $base64);
- this.restangular = restangular.one("products");
- }
-
- createComponentObject = (component:Component):Component => {
- return new Product(this, this.$q, <Product>component);
- };
-}
import {IAppConfigurtaion} from "../../../models/app-config";
import {ResourceType, ComponentType, EVENTS} from "../../../utils/constants";
import {ComponentMetadata} from "../../../models/component-metadata";
+import {Resource} from "app/models/components/resource";
export class LeftPaletteDataObject {
displayLeftPanelComponents:Array<LeftPaletteComponent>;
protected EventListenerService:EventListenerService) {
this.restangular.setBaseUrl(sdcConfig.api.root + sdcConfig.api.component_api_root);
-
+
}
private serviceLeftPaletteData:LeftPaletteDataObject;
private resourceLeftPaletteData:LeftPaletteDataObject;
- private productLeftPaletteData:LeftPaletteDataObject;
+ private resourcePNFLeftPaletteData:LeftPaletteDataObject;
private vlData:LeftPaletteDataObject;
- public loadLeftPanel = (componentType: string):void => {
+ public loadLeftPanel = (component:Component):void => {
this.serviceLeftPaletteData = new LeftPaletteDataObject(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
this.resourceLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
- this.updateComponentLeftPalette(componentType);
+ this.resourcePNFLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT);
+ this.updateComponentLeftPalette(component);
}
-
- private getTypeUrl = (componentType:string):string => {
- return ComponentType.PRODUCT === componentType ? "services" : "resources";
- };
+ private getResourceLeftPaletteDataByResourceType = (resourceType:string):LeftPaletteDataObject => {
+ if(resourceType == ResourceType.PNF) {
+ return this.resourcePNFLeftPaletteData;
+ }
+ return this.resourceLeftPaletteData;
+ }
private onFinishLoading = (componentType:string, leftPaletteData:LeftPaletteDataObject):void => {
this.EventListenerService.notifyObservers(leftPaletteData.onFinishLoadingEvent);
private updateLeftPalette = (componentType, componentInternalType:string, leftPaletteData:LeftPaletteDataObject):void => {
- this.restangular.one(this.getTypeUrl(componentType)).one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
+ this.restangular.one("resources").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
_.forEach(leftPaletteComponentMetadata, (componentMetadata:ComponentMetadata) => {
leftPaletteData.displayLeftPanelComponents.push(new LeftPaletteComponent(componentMetadata));
});
});
};
- public getLeftPanelComponentsForDisplay = (componentType:string):Array<LeftPaletteComponent> => {
- switch (componentType) {
+ public getLeftPanelComponentsForDisplay = (component:Component):Array<LeftPaletteComponent> => {
+ switch (component.componentType) {
case ComponentType.SERVICE:
return this.serviceLeftPaletteData.displayLeftPanelComponents;
- case ComponentType.PRODUCT:
- return this.productLeftPaletteData.displayLeftPanelComponents;
- default:
- return this.resourceLeftPaletteData.displayLeftPanelComponents;
+ default://resource
+ return this.getResourceLeftPaletteDataByResourceType((<Resource>component).resourceType).displayLeftPanelComponents;
}
};
- public updateComponentLeftPalette = (componentType):void => {
- switch (componentType) {
- case ResourceType.VL:
- this.updateLeftPalette(ComponentType.RESOURCE, ResourceType.VL, this.vlData);
- break;
+ public updateComponentLeftPalette = (component:Component):void => {
+ switch (component.componentType) {
case ComponentType.SERVICE:
this.updateLeftPalette(ComponentType.SERVICE, ComponentType.SERVICE, this.serviceLeftPaletteData);
break;
- case ComponentType.PRODUCT:
- this.updateLeftPalette(ComponentType.PRODUCT, ComponentType.SERVICE, this.productLeftPaletteData);
+ case ComponentType.RESOURCE:
+ this.updateLeftPalette(ComponentType.RESOURCE, (<Resource>component).resourceType, this.getResourceLeftPaletteDataByResourceType((<Resource>component).resourceType));
break;
default:
- this.updateLeftPalette(ComponentType.RESOURCE, ResourceType.VF, this.resourceLeftPaletteData);
+ console.log('ERROR: Component type '+ component.componentType + ' is not exists');
}
};
}
public isDataTypeForDataTypePropertyType = (property:DataTypePropertyModel):boolean=> {
property.simpleType = "";
- if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
+ let isScalarForNFoD:boolean = property.type === 'scalar-unit.size';
+ if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1 || isScalarForNFoD) {
return false;
}
let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
*/
'use strict';
-import {Product, Service, IApi, IAppConfigurtaion, Resource, Component} from "../models";
+import { Service, IApi, IAppConfigurtaion, Resource, Component} from "../models";
import {SharingService} from "./sharing-service";
import {ComponentFactory} from "../utils/component-factory";
import {CacheService} from "./cache-service";
interface IComponentsArray {
services:Array<Service>;
resources:Array<Resource>;
- products:Array<Product>;
}
export class EntityService implements IEntityService {
this.sharingService.addUuidValue(component.uniqueId, component.uuid);
});
- followedResponse.products.forEach((productResponse:Product) => {
-
- let component:Product = this.ComponentFactory.createProduct(productResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
this.cacheService.set('breadcrumbsComponents', componentsList);
defer.resolve(componentsList);
},(responce) => {
componentsList.push(component);
this.sharingService.addUuidValue(component.uniqueId, component.uuid);
});
-
- componentResponse.products && componentResponse.products.forEach((productsResponse:Product) => {
- let component:Product = this.ComponentFactory.createProduct(productsResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
+
this.cacheService.set('breadcrumbsComponents', componentsList);
defer.resolve(componentsList);
});
'use strict';
import {DEFAULT_ICON, ResourceType, ComponentType} from "./constants";
-import {ServiceService, CacheService, ResourceService, ProductService} from "app/services";
-import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service, Product} from "app/models";
+import {ServiceService, CacheService, ResourceService} from "app/services";
+import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service} from "app/models";
import {ComponentMetadata} from "../models/component-metadata";
import {ComponentServiceNg2} from "../ng2/services/component-services/component.service";
import {ComponentGenericResponse} from "../ng2/services/responses/component-generic-response";
static '$inject' = [
'Sdc.Services.Components.ResourceService',
'Sdc.Services.Components.ServiceService',
- 'Sdc.Services.Components.ProductService',
'Sdc.Services.CacheService',
'$q',
'ComponentServiceNg2'
constructor(private ResourceService:ResourceService,
private ServiceService:ServiceService,
- private ProductService:ProductService,
private cacheService:CacheService,
private $q:ng.IQService,
private ComponentServiceNg2: ComponentServiceNg2) {
newComponent = new Resource(this.ResourceService, this.$q, <Resource> component);
break;
- case 'PRODUCT':
- newComponent = new Product(this.ProductService, this.$q, <Product> component);
- break;
}
return newComponent;
};
- public createProduct = (product:Product):Product => {
- let newProduct:Product = new Product(this.ProductService, this.$q, <Product> product);
- return newProduct;
- };
-
public createService = (service:Service):Service => {
let newService:Service = new Service(this.ServiceService, this.$q, <Service> service);
return newService;
case ResourceType.VL:
case ResourceType.VFC:
case ResourceType.CP:
+ case ResourceType.PNF:
+ case ResourceType.CVFC:
newComponent = new Resource(this.ResourceService, this.$q);
break;
-
- case ComponentType.PRODUCT:
- newComponent = new Product(this.ProductService, this.$q);
- break;
}
newComponent.componentType = componentType;
newComponent.tags = [];
* Created by obarda on 3/7/2016.
*/
'use strict';
-import {ComponentInstance, ServiceInstance, ProductInstance, ResourceInstance, Component} from "../models";
+import {ComponentInstance, ServiceInstance, ResourceInstance, Component} from "../models";
import {LeftPaletteComponent} from "../models/components/displayComponent";
export class ComponentInstanceFactory {
newComponentInstance = new ServiceInstance(componentInstance);
break;
- case 'PRODUCT':
- newComponentInstance = new ProductInstance(componentInstance);
- break;
-
default :
newComponentInstance = new ResourceInstance(componentInstance);
break;
newComponentInstance = new ServiceInstance();
break;
- case 'PRODUCT':
- newComponentInstance = new ProductInstance();
- break;
-
default :
newComponentInstance = new ResourceInstance();
break;
export class ComponentType {
static SERVICE = 'SERVICE';
static RESOURCE = 'RESOURCE';
- static PRODUCT = 'PRODUCT';
}
export class ServerTypeUrl {
static RESOURCES = 'resources/';
static SERVICES = 'services/';
- static PRODUCTS = 'product/';
}
export class ResourceType {
static VFC = 'VFC';
static VFCMT = 'VFCMT';
static PNF = 'PNF';
+ static CVFC = 'CVFC';
}
export class ComponentState {
export class Role {
public static ADMIN = 'ADMIN';
public static DESIGNER = 'DESIGNER';
- public static PRODUCT_STRATEGIST = 'PRODUCT_STRATEGIST';
- public static PRODUCT_MANAGER = 'PRODUCT_MANAGER';
public static TESTER = 'TESTER';
public static OPS = 'OPS';
public static GOVERNOR = 'GOVERNOR';
export class States {
public static WORKSPACE_GENERAL = 'workspace.general';
- public static WORKSPACE_ICONS = 'workspace.icons';
public static WORKSPACE_ACTIVITY_LOG = 'workspace.activity_log';
public static WORKSPACE_DEPLOYMENT_ARTIFACTS = 'workspace.deployment_artifacts';
public static WORKSPACE_PROPERTIES = 'workspace.properties';
public static WORKSPACE_SERVICE_INPUTS = 'workspace.service_inputs';
public static WORKSPACE_RESOURCE_INPUTS = 'workspace.resource_inputs';
public static WORKSPACE_ATTRIBUTES = 'workspace.attributes';
- public static WORKSPACE_HIERARCHY = 'workspace.hierarchy';
public static WORKSPACE_INFORMATION_ARTIFACTS = 'workspace.information_artifacts';
public static WORKSPACE_TOSCA_ARTIFACTS = 'workspace.tosca_artifacts';
public static WORKSPACE_COMPOSITION = 'workspace.composition';
static RESOURCE_LEFT_PALETTE_UPDATE_EVENT = "resourceLeftPanelUpdateEvent";
static RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT = "resourcePNFLeftPanelUpdateEvent";
static SERVICE_LEFT_PALETTE_UPDATE_EVENT = "serviceLeftPanelUpdateEvent";
- static PRODUCT_LEFT_PALETTE_UPDATE_EVENT = "productLeftPanelUdateEvent";
static VL_LEFT_PALETTE_UPDATE_EVENT = "vlLeftPanelUdateEvent";
static ON_CSAR_LOADING = "onCsarLoading";
static DOWNLOAD_ARTIFACT_FINISH_EVENT = "downloadArtifactFinishEvent";
return deferred.promise;
};
+ openUpdateIconModal = (component: Component):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/icons-modal/icons-modal-view.html',
+ controller: 'Sdc.ViewModels.IconsModalViewModel',
+ size: 'sdc-auto',
+ backdrop: 'static',
+ resolve: {
+ component: ():Component => {
+ return component;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
openEditEnvParametersModal = (artifactResource:ArtifactModel, component?:Component):ng.IPromise<any> => {
let deferred = this.$q.defer();
let modalOptions:ng.ui.bootstrap.IModalSettings = {
let onSuccess = (followedResponse:Array<Component>):void => {
this.$scope.catalogFilterdItems = followedResponse;
this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
- this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')).concat(this.cacheService.get('productCategories'));
+ this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories'));
this.$scope.gui.isLoading = false;
};
//this.$scope.categories = this.cacheService.get('categoriesMap');
this.$scope.sdcMenu = this.sdcMenu;
this.$scope.confStatus = this.sdcMenu.statuses;
- this.$scope.expandedSection = ["type", "category", "product-category", "status"];
+ this.$scope.expandedSection = ["type", "category", "status"];
this.$scope.user = this.userResourceService.getLoggedinUser();
this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;
this.$scope.version = this.cacheService.get('version');
// Checklist init
this.$scope.checkboxes = <Checkboxes>{};
- this.$scope.checkboxes.componentTypes = ['Resource', 'Service', 'Product'];
- this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CP', 'VL'];
+ this.$scope.checkboxes.componentTypes = ['Resource', 'Service'];
+ this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'PNF', 'CP', 'VL'];
// Checkboxes filter init
this.$scope.checkboxesFilter = <CheckboxesFilter>{};
//text-indent: -10px;
}
- /*Added by - Ikram */
- .i-sdc-product-input,
- .i-sdc-product-select {
- border: 1px solid @border_color_f;
- min-height: 30px;
- padding: 0;
- width: 100%;
- margin: 1px 0;
- background-color: #F2F2F2;
- outline: none;
-
- &:disabled {
- .disabled;
- }
- optgroup{
- color: @color_u;
- option{
- color: @color_b;
- }
- }
- }
-
.i-sdc-categories-list-item-icon {
display: inline-block;
float: right;
};
+ this.$scope.createPNF = ():void => {
+ this.$state.go('workspace.general', {
+ type: ComponentType.RESOURCE.toLowerCase(),
+ resourceType: ResourceType.PNF
+ });
+ };
+
this.$scope.entitiesCount = (folderItem:FoldersItemsMenu):any => {
let self = this;
let total:number = 0;
<div class='w-sdc-row-flex-items'>
<!-- ADD Component -->
- <div ng-if="user.role === 'DESIGNER' || user.role === 'PRODUCT_MANAGER'" class="w-sdc-dashboard-card-new"
+ <div ng-if="user.role === 'DESIGNER'" class="w-sdc-dashboard-card-new"
data-ng-mouseleave="displayActions = false"
data-ng-mouseover="displayActions = true"
data-ng-init="displayActions = false">
<div class="w-sdc-dashboard-card-new-content" data-tests-id="AddButtonsArea">
<div class="w-sdc-dashboard-card-new-content-plus" data-ng-show="!displayActions"></div>
<div class="sdc-dashboard-create-element-container" data-ng-show="displayActions">
- <button data-ng-if="roles[user.role].dashboard.showCreateNewProduct" data-tests-id="createProductButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('PRODUCT')">Create Product</button>
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createResourceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('RESOURCE')">Add VF</button>
+ <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createPNFButton" class="tlv-btn outline blue" data-ng-click="createPNF()">Add PNF</button>
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createServiceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('SERVICE')">Add Service</button>
</div>
</div>
</div>
</div>
</div>
- </div>
-
+ </div>
+
<!-- Tile new -->
<div class="sdc-tile-catalog sdc-tile-fix-width" data-ng-repeat="component in components | filter:{resourceType:('!'+vfcmtType)} | entityFilter:checkboxesFilter | filter:search">
data-tests-id="{{component.name}}"></div>
</div>
<div class='sdc-tile-content-info'>
- <div class="sdc-tile-content-info-item-name" data-tests-id="{{component.name | resourceName}}" sdc-smart-tooltip>{{component.name | resourceName}}</div>
+ <div class="sdc-tile-content-info-item-name" data-tests-id="{{component.name | resourceName}}" sdc-smart-tooltip>{{component.name | resourceName}}</div>
<div class="sdc-tile-content-info-version-info">
<div class="sdc-tile-content-info-version-info-text" data-tests-id="{{component.name}}Version">V {{component.version}}</div>
</div>
</div>
<div class='sdc-tile-footer'>
<div class='sdc-tile-footer-text'>{{component.getStatus(sdcMenu)}}</div>
- </div>
+ </div>
</div>
<!-- Tile new -->
-
+
</div>
</perfect-scrollbar>
}
}
- &.PRODUCT {
- .b_14_m;
- &::before {
- content: 'P';
- }
- }
-
&.green {
.d_12;
&::before {
//text-indent: -10px;
}
- /*Added by - Ikram */
- .i-sdc-product-input,
- .i-sdc-product-select {
- border: 1px solid @border_color_f;
- min-height: 30px;
- padding: 0;
- width: 100%;
- margin: 1px 0;
- background-color: #F2F2F2;
- outline: none;
-
- &:disabled {
- .disabled;
- }
- optgroup{
- color: @color_u;
- option{
- color: @color_b;
- }
- }
- }
-
.i-sdc-categories-list-item-icon {
display: inline-block;
float: right;
PROPERTY_TYPES, ModalsHandler, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA} from "app/utils";
import {DataTypesService} from "app/services";
import {PropertyModel, DataTypesMap, Component} from "app/models";
+import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance";
export interface IEditPropertyModel {
property:PropertyModel;
isTypeDataType:boolean;
maxLength:number;
isPropertyValueOwner:boolean;
+ isVnfConfiguration:boolean;
validateJson(json:string):boolean;
save(doNotCloseModal?:boolean):void;
this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
this.initEditPropertyModel();
+ //check if property of VnfConfiguration
+ this.$scope.isVnfConfiguration = false;
+ if(angular.isArray(this.component.componentInstances)) {
+ var componentPropertyOwner:ComponentInstance = this.component.componentInstances.find((ci:ComponentInstance) => {
+ return ci.uniqueId === this.property.resourceInstanceUniqueId;
+ });
+ if (componentPropertyOwner.componentName === 'vnfConfiguration') {
+ this.$scope.isVnfConfiguration = true;
+ }
+ }
+
this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
return this.$scope.editPropertyModel.types.indexOf(type) == -1;
});
schema-property="editPropertyModel.property.schema.property"
parent-form-obj="forms.editForm"
fields-prefix-name="currentPropertyIndex"
- read-only="editPropertyModel.property.readonly && !isPropertyValueOwner"
+ read-only="(editPropertyModel.property.readonly && !isPropertyValueOwner) || isVnfConfiguration"
default-value="{{getDefaultValue()}}"
max-length="maxLength"></type-map>
</div>
--- /dev/null
+<sdc-modal modal="modalIcons" type="classic" class="w-sdc-modal-icons" buttons="footerButtons" header="Choose Icon" show-close-button="true">
+
+ <div class="suggested-icons-container">
+ <div class ="suggested-icon-wrapper" data-ng-class="{'selected': selectedIcon == iconSrc}" data-ng-repeat="iconSrc in icons track by $index">
+ <div class="i-sdc-form-item-suggested-icon large hand {{iconSprite}} {{iconSrc}}"
+ data-tests-id="{{iconSrc}} iconBox"
+ data-ng-click="changeIcon(iconSrc)"
+ tooltips tooltip-content='{{iconSrc | translate}}'
+ >
+ </div>
+ </div>
+ </div>
+
+ <div class="w-sdc-modal-footer classic">
+ <button class="tlv-btn blue" data-tests-id="OK" data-ng-click="updateIcon()">OK</button>
+ <button class="tlv-btn grey" data-tests-id="Cancel" data-ng-click="cancel()" >Cancel</button>
+ </div>
+</sdc-modal>
--- /dev/null
+.suggested-icons-container {
+ text-align: left;
+ width: 370px;
+ margin-bottom: 20px;
+ position: relative;
+
+ .suggested-icon-wrapper {
+ padding: 5px;
+ margin: 14px 0 14px 28px;
+ display: inline-block;
+ height: 71px;
+ width: 71px;
+
+ &.selected {
+ border: 2px solid @main_color_a;
+ border-radius: 35px;
+ display: inline-block;
+ line-height: 0px;
+ padding: 3px;
+ }
+
+ }
+ .i-sdc-form-item-suggested-icon {
+ opacity: 0.8;
+ &:hover{
+ opacity: 1;
+ }
+ }
+ .suggested-icon-wrapper:nth-child(4n+1) {
+ margin-left: 0;
+ }
+}
+
*/
/**
- * Created by obarda on 4/4/2016.
+ * Created by rc2122 on 7/4/2017.
*/
'use strict';
import {ComponentFactory} from "app/utils";
import {AvailableIconsService} from "app/services";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {IMainCategory, ISubCategory} from "app/models";
-
-export interface IIconsScope extends IWorkspaceViewModelScope {
- icons:Array<string>;
- iconSprite:string;
- setComponentIcon(iconSrc:string):void;
+import {Component} from "app/models";
+import {ResourceType} from "app/utils/constants";
+
+interface IIconsModalViewModelScope {
+ modalIcons:ng.ui.bootstrap.IModalServiceInstance;
+ icons:Array<string>,
+ iconSprite:string,
+ selectedIcon:string,
+ changeIcon(icon:string):void,
+ cancel():void
+ updateIcon():void;
}
-export class IconsViewModel {
-
+export class IconsModalViewModel {
static '$inject' = [
'$scope',
'Sdc.Services.AvailableIconsService',
'ComponentFactory',
- '$state'
+ '$state',
+ '$uibModalInstance',
+ 'component'
];
- constructor(private $scope:IIconsScope,
+ constructor(private $scope:IIconsModalViewModelScope,
private availableIconsService:AvailableIconsService,
private ComponentFactory:ComponentFactory,
- private $state:ng.ui.IStateService) {
-
-
+ private $state:ng.ui.IStateService,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private component: Component) {
this.initScope();
- this.initIcons();
- this.$scope.updateSelectedMenuItem();
- this.$scope.iconSprite = this.$scope.component.iconSprite;
+ this._initIcons();
+ this.$scope.iconSprite = this.component.iconSprite;
+ this.$scope.selectedIcon = this.component.icon;
- if (this.$scope.component.isResource()) {
+ if (this.component.isResource()) {
this.initVendor();
}
+
}
- private initialIcon:string = this.$scope.component.icon;
- private initIcons = ():void => {
+ private _initIcons = ():void => {
// For subcategories that where created by admin, there is no icons
this.$scope.icons = new Array<string>();
- if (this.$scope.component.categories && this.$scope.component.categories.length > 0) {
+ if (this.component.categories && this.component.categories.length > 0) {
- _.forEach(this.$scope.component.categories, (category:IMainCategory):void => {
+ _.forEach(this.component.categories, (category:IMainCategory):void => {
if (category.icons) {
this.$scope.icons = this.$scope.icons.concat(category.icons);
}
});
}
- if (this.$scope.component.isResource()) {
- let resourceType:string = this.$scope.component.getComponentSubType();
- if (resourceType === 'VL') {
+ if (this.component.isResource()) {
+ let resourceType:string = this.component.getComponentSubType();
+ if (resourceType === ResourceType.VL) {
this.$scope.icons = ['vl'];
}
- if (resourceType === 'CP') {
+ if (resourceType === ResourceType.CP) {
this.$scope.icons = ['cp'];
}
}
if (this.$scope.icons.length === 0) {
- this.$scope.icons = this.availableIconsService.getIcons(this.$scope.component.componentType);
+ this.$scope.icons = this.availableIconsService.getIcons(this.component.componentType);
}
//we always add the defual icon to the list
this.$scope.icons.push('defaulticon');
};
private initVendor = ():void => {
- let vendors:Array<string> = this.availableIconsService.getIcons(this.$scope.component.componentType).slice(5, 19);
- let vendorName = this.$scope.component.vendorName.toLowerCase();
+ let vendors:Array<string> = this.availableIconsService.getIcons(this.component.componentType).slice(5, 19);
+ let vendorName = this.component.vendorName.toLowerCase();
if ('at&t' === vendorName) {
vendorName = 'att';
}
};
private initScope():void {
+ this.$scope.modalIcons = this.$uibModalInstance;
this.$scope.icons = [];
- this.$scope.setValidState(true);
- //if(this.$scope.component.icon === DEFAULT_ICON){
- // //this.$scope.setValidState(false);
- //}
-
- this.$scope.setComponentIcon = (iconSrc:string):void => {
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode() && (iconSrc != this.initialIcon);
- this.$scope.component.icon = iconSrc;
- // this.$scope.setValidState(true);
+ this.$scope.changeIcon = (icon:string):void => {
+ this.$scope.selectedIcon = icon;
};
-
+ this.$scope.cancel = ():void => {
+ this.$uibModalInstance.dismiss();
+ };
+ this.$scope.updateIcon = ():void => {
+ let isDirty:boolean = this.component.icon != this.$scope.selectedIcon;
+ this.component.icon = this.$scope.selectedIcon;
+ this.$uibModalInstance.close(isDirty);
+ }
}
+
}
+
+
+
//text-indent: -10px;
}
- /*Added by - Ikram */
- .i-sdc-product-input,
- .i-sdc-product-select {
- border: 1px solid @border_color_f;
- min-height: 30px;
- padding: 0;
- width: 100%;
- margin: 1px 0;
- background-color: #F2F2F2;
- outline: none;
-
- &:disabled {
- .disabled;
- }
- optgroup{
- color: @color_u;
- option{
- color: @color_b;
- }
- }
- }
-
.i-sdc-categories-list-item-icon {
display: inline-block;
float: right;
.activity-log {
-
- margin-top: 30px;
-
.title-wrapper {
display: flex;
justify-content: flex-end;
.table-container-flex .table .body .scrollbar-container {
max-height: 448px;
}
-
+
.view-mode {
background-color: @main_color_p;
}
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.text{
overflow: hidden;
* ============LICENSE_END=========================================================
*/
'use strict';
-import {Component, Product, ComponentInstance, IAppMenu} from "app/models";
+import {Component, ComponentInstance, IAppMenu} from "app/models";
import {SharingService, CacheService, EventListenerService, LeftPaletteLoaderService} from "app/services";
import {ModalsHandler, GRAPH_EVENTS, ComponentFactory, ChangeLifecycleStateHandler, MenuHandler, EVENTS} from "app/utils";
import {IWorkspaceViewModelScope} from "../../workspace-view-model";
import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
+import {Resource} from "app/models/components/resource";
+import {ResourceType} from "../../../../utils/constants";
export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
if (this.$state.current.name === 'workspace.composition.api') {
this.$state.go('workspace.composition.details');
}
- if (this.$state.current.name === 'workspace.composition.relations' && this.$scope.currentComponent.isProduct()) {
- this.$state.go('workspace.composition.details');
- }
};
this.$scope.onBackgroundClick = ():void => {
this.ModalsHandler.openAlertModal(title, message).then(onOk);
};
- this.$scope.onComponentInstanceVersionChange = (component:Product):void => {
+ this.$scope.onComponentInstanceVersionChange = (component:Component):void => {
this.$scope.currentComponent = component;
this.$scope.setComponent(this.$scope.currentComponent);
this.$scope.updateSelectedComponent();
<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"
data-ui-sref="workspace.composition.deployment"
tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Deployment Artifacts"
- data-tests-id="deployment-artifact-tab">
+ data-tests-id="deployment-artifact-tab"
+ data-ng-if="!isPNF()">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new deployment-artifacts"></div>
</button>
<button tooltips tooltip-class="tooltip-custom tab-tooltip"
</div>
</div>
- <div class="w-sdc-designer-sidebar-section-footer" data-ng-if="!isViewMode() && artifactType!=='api' && (!isComponentInstanceSelected()||selectedComponent.resourceType=='VF') && !currentComponent.isProduct() && ('deployment' != artifactType || selectedComponent.isComplex())">
+ <div class="w-sdc-designer-sidebar-section-footer" data-ng-if="!isViewMode() && artifactType!=='api' && (!isComponentInstanceSelected()||selectedComponent.resourceType=='VF') && ('deployment' != artifactType || selectedComponent.isComplex())">
<button class="w-sdc-designer-sidebar-section-footer-action tlv-btn blue" data-tests-id="add_Artifact_Button" data-ng-click="addOrUpdate({})" type="button">Add Artifact</button>
</div>
</div>
let highestVersion = _.last(Object.keys(this.$scope.selectedComponent.allVersions));
if (parseFloat(highestVersion) % 1) { //if highest is minor, make sure it is the latest checked in -
- let latestVersionComponent:LeftPaletteComponent = _.maxBy(_.filter(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent.componentType), (component:LeftPaletteComponent) => { //latest checked in
+ let latestVersionComponent:LeftPaletteComponent = _.maxBy(_.filter(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent), (component:LeftPaletteComponent) => { //latest checked in
return (component.systemName === this.$scope.selectedComponent.systemName
|| component.uuid === this.$scope.selectedComponent.uuid);
}),(component)=>{return component.version});
data-tests-id="rightTab_vendorRelease">
</span>
</div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="selectedComponent.isResource()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_RESOURCE_MODEL_NUMBER"></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-value vendor-model-number" data-ng-bind="selectedComponent.resourceVendorModelNumber"
+ tooltips tooltip-class="tooltip-custom break-word-tooltip" tooltip-content="​{{selectedComponent.resourceVendorModelNumber}}"
+ data-tests-id="rightTab_resourceVendorModelNumber">
+ </span>
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="selectedComponent.isService()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_SERVICE_TYPE"></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.serviceType"
+ tooltips tooltip-class="tooltip-custom break-word-tooltip" tooltip-content="​{{selectedComponent.serviceType}}"
+ data-tests-id="rightTab_serviceType">
+ </span>
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="selectedComponent.isService()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_SERVICE_ROLE"></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.serviceRole"
+ tooltips tooltip-class="tooltip-custom break-word-tooltip" tooltip-content="​{{selectedComponent.serviceRole}}"
+ data-tests-id="rightTab_serviceRole">
+ </span>
+ </div>
<div class="i-sdc-designer-sidebar-section-content-item">
<span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CONTACT_ID"></span>
<span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.contactId"
max-width: 160px;
vertical-align:bottom;
font-weight: normal;
+ &.vendor-model-number{
+ max-width: 110px;
+ }
&.additional-information{
max-width:160px;
display: inline-block;
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.text{
overflow: hidden;
import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
ResourceType} from "app/utils";
import {CacheService, EventListenerService, ProgressService} from "app/services";
-import {IAppConfigurtaion, Product, IValidate, IMainCategory, Resource, ISubCategory,Service} from "app/models";
+import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service} from "app/models";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
export class Validation {
componentNameValidationPattern:RegExp;
contactIdValidationPattern:RegExp;
tagValidationPattern:RegExp;
- vendorValidationPattern:RegExp;
+ VendorReleaseValidationPattern:RegExp;
+ VendorNameValidationPattern:RegExp;
+ VendorModelNumberValidationPattern:RegExp;
commentValidationPattern:RegExp;
projectCodeValidationPattern:RegExp;
}
onEcompGeneratedNamingChange():void;
openOnBoardingModal():void;
initCategoreis():void;
+ updateIcon():void;
+ possibleToUpdateIcon():boolean;
}
export class GeneralViewModel {
'ComponentNameValidationPattern',
'ContactIdValidationPattern',
'TagValidationPattern',
- 'VendorValidationPattern',
+ 'VendorReleaseValidationPattern',
+ 'VendorNameValidationPattern',
+ 'VendorModelNumberValidationPattern',
'CommentValidationPattern',
'ValidationUtils',
'sdcConfig',
private ComponentNameValidationPattern:RegExp,
private ContactIdValidationPattern:RegExp,
private TagValidationPattern:RegExp,
- private VendorValidationPattern:RegExp,
+ private VendorReleaseValidationPattern:RegExp,
+ private VendorNameValidationPattern:RegExp,
+ private VendorModelNumberValidationPattern:RegExp,
private CommentValidationPattern:RegExp,
private ValidationUtils:ValidationUtils,
private sdcConfig:IAppConfigurtaion,
this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
- this.$scope.validation.vendorValidationPattern = this.VendorValidationPattern;
+ this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
+ this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
+ this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
};
this.$scope.componentCategories = new componentCategories();
this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
- // Workaround to short vendor name to 25 chars
- // Amdocs send 27 chars, and the validation pattern is 25 chars.
- if (this.$scope.component.vendorName) {
- this.$scope.component.vendorName = this.$scope.component.vendorName.substr(0, 25);
- }
-
// Init UIModel
this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
};
//TODO remove this after handling contact in UI
- if (this.$scope.component.isProduct() && this.$scope.isCreateMode()) {
- (<Product>this.$scope.component).contacts = [];
- (<Product>this.$scope.component).contacts.push(this.cacheService.get("user").userId);
- } else if (this.$scope.isCreateMode()) {
+ if (this.$scope.isCreateMode()) {
this.$scope.component.contactId = this.cacheService.get("user").userId;
}
});
};
+ this.$scope.updateIcon = ():void => {
+ this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
+ if(!this.$scope.isCreateMode()){
+ this.$state.current.data.unsavedChanges = this.$state.current.data.unsavedChanges || isDirty;
+ }
+ }, ()=> {
+ // ERROR
+ });
+ };
+
+ this.$scope.possibleToUpdateIcon = ():boolean => {
+ if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName)){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
this.$scope.validateName = (isInit:boolean):void => {
if (isInit === undefined) {
isInit = false;
<div class="w-sdc-form-section-container">
- <!--------------------- IMPORT TOSCA FILE USING BROWSE (ALSO VFC) -------------------->
- <div class="i-sdc-form-item" ng-if="isShowFileBrowse">
- <label class="i-sdc-form-label" data-ng-class="{'required':isCreateMode()}">{{browseFileLabel}}</label>
- <file-upload id="fileUploadElement"
- class="i-sdc-form-input"
- element-name="fileElement"
- element-disabled="{{!isCreateMode()&&!(isEditMode()&&component.resourceType=='VF')}} || {{isViewMode()}}"
- form-element="editForm"
- file-model="component.importedFile"
- on-file-changed-in-directive="uploadFileChangedInGeneralTab"
- extensions="{{importedFileExtension}}"
- default-text="'Browse to select file'"
- data-ng-class="{'error':!(isEditMode()&&component.resourceType=='VF') && (!editForm.fileElement.$valid || !component.importedFile.filename)}"></file-upload>
- </div>
-
- <!--------------------- IMPORT TOSCA FILE USING ONBOARDING -------------------->
- <div class="i-sdc-form-item" ng-if="isShowOnboardingSelectionBrowse">
- <label class="i-sdc-form-label required">Select VSP</label>
- <div class="i-sdc-form-file-upload i-sdc-form-input">
- <span class="i-sdc-form-file-name" data-tests-id="filename">{{(fileModel && fileModel.filename) || importedToscaBrowseFileText}}</span>
- <div class="i-sdc-form-file-upload-x-btn" ng-click="cancel()" data-ng-show="fileModel.filename && fileModel.filename!=='' && elementDisabled!=='true'"></div>
- <input type="button" name="fileElement"/>
- <div class="file-upload-browse-btn" data-ng-click="openOnBoardingModal()" data-tests-id="browseButton">Browse</div>
- </div>
- </div>
-
- <div class="input-error-file-upload" data-ng-show="component.importedFile && (!editForm.fileElement.$valid || !component.importedFile.filename)">
- <!-- editForm.fileElement.$error.required <== Can not use this, because the browse is done from outside for the first time -->
- <span ng-show="!(isEditMode()&&component.resourceType=='VF')&&!component.importedFile.filename" translate="NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED"></span><!-- Required -->
- <span ng-show="editForm.fileElement.$error.maxsize" translate="VALIDATION_ERROR_MAX_FILE_SIZE"></span>
- <span ng-show="editForm.fileElement.$error.filetype" translate="NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS" translate-values="{'extensions': '{{importedFileExtension}}' }"></span>
- <span ng-show="editForm.fileElement.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
- </div>
- <!--------------------- IMPORT TOSCA FILE -------------------->
-
<div class="w-sdc-form-columns-wrapper">
<div class="w-sdc-form-column">
-
- <!--------------------- NAME -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.componentName)}">
- <label class="i-sdc-form-label required">Name</label>
- <input class="i-sdc-form-input"
- data-ng-class="{'view-mode': isViewMode()}"
- name="componentName"
- data-ng-init="isCreateMode() && validateName(true)"
- data-ng-maxlength="{{component.isProduct()?'25':'50'}}"
- maxlength="{{component.isProduct()?'25':'50'}}"
- data-ng-minlength="{{component.isProduct()?'4':'0'}}"
- minlength="{{component.isProduct()?'4':'0'}}"
- data-ng-model="component.name"
- type="text"
- data-required
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.componentNameValidationPattern"
- data-ng-disabled="component.isAlreadyCertified()"
- data-tests-id="name"
- autofocus
- ng-readonly="isViewMode()"
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.componentName)">
- <span ng-show="editForm.componentName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
- <span ng-show="editForm.componentName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
- <span ng-show="editForm.componentName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
- <span ng-show="editForm.componentName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_INVALID_NAME"></span>
+ <div class="upper-general-fields">
+ <div class="selected-icon-container" data-ng-class="{'show-only-on-over':'defaulticon'!=component.icon && !isViewMode()}">
+ <div class="selected-icon-inner-container">
+ <div class="sprite-new update-component-icon" data-ng-click="updateIcon()" data-ng-if="!isViewMode() && possibleToUpdateIcon()"></div>
+ <div class="i-sdc-form-item-suggested-icon large selected-icon {{component.iconSprite}} {{component.icon}}"
+ data-ng-class="{ 'disable': isViewMode() || !possibleToUpdateIcon() }"
+ ng-model="component.icon"
+ tooltips tooltip-content='{{component.icon | translate}}'
+ >
+ </div>
+ </div>
+ </div>
+ <div class="name-and-category-fields">
+ <!--------------------- NAME -------------------->
+ <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.componentName)}">
+ <label class="i-sdc-form-label required">Name</label>
+ <input class="i-sdc-form-input"
+ data-ng-class="{'view-mode': isViewMode()}"
+ name="componentName"
+ data-ng-init="isCreateMode() && validateName(true)"
+ data-ng-maxlength="50"
+ maxlength="50"
+ data-ng-model="component.name"
+ type="text"
+ data-required
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.componentNameValidationPattern"
+ data-ng-disabled="component.isAlreadyCertified()"
+ data-tests-id="name"
+ autofocus
+ ng-readonly="isViewMode()"
+ />
+
+ <div class="input-error" data-ng-show="validateField(editForm.componentName)">
+ <span ng-show="editForm.componentName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
+ <span ng-show="editForm.componentName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
+ <span ng-show="editForm.componentName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
+ <span ng-show="editForm.componentName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
+ <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_INVALID_NAME"></span>
+ </div>
+ </div>
+ <!--------------------- NAME -------------------->
+
+
+
+ <!--------------------- CATEGORIES -------------------->
+ <div class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.category)}">
+ <loader data-display="!categories && !initCategoreis()" relative="true"></loader>
+ <label class="i-sdc-form-label required">Category</label>
+ <select class="i-sdc-form-select"
+ data-required
+ name="category"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-change="onCategoryChange()"
+ data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.selectedCategory && component.selectedCategory!=='')"
+ data-ng-model="componentCategories.selectedCategory"
+ data-tests-id="selectGeneralCategory"
+ >
+ <option value="">Select category</option>
+ <optgroup ng-if="component.isResource()" data-ng-repeat="mainCategory in categories | orderBy:['name']" label="{{mainCategory.name}}" data-tests-id="{{mainCategory.name}}">
+ <option data-ng-repeat="subCategory in mainCategory.subcategories track by $index"
+ data-ng-selected="componentCategories.selectedCategory === calculateUnique(mainCategory.name,subCategory.name)"
+ data-tests-id="{{subCategory.name}}"
+ value="{{calculateUnique(mainCategory.name, subCategory.name)}}">{{subCategory.name}}
+
+ </option>
+ </optgroup>
+ <option ng-if="component.isService()" data-ng-repeat="mainCategory in categories | orderBy:['name']"
+ data-ng-selected="component.selectedCategory===mainCategory.name"
+ value="{{mainCategory.name}}"
+ data-tests-id="{{mainCategory.name}}">{{mainCategory.name}}</option>
+ </select>
+
+ <div class="input-error" data-ng-show="validateField(editForm.category)">
+ <span ng-show="editForm.category.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CATEGORY_REQUIRED"></span>
+ </div>
+ </div>
+ <!--------------------- CATEGORIES -------------------->
+ </div>
</div>
- </div>
- <!--------------------- NAME -------------------->
+ <!--------------------- RESOURCE TAGS -------------------->
+ <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.tags)}">
+ <label class="i-sdc-form-label">Tags</label>
- <!--------------------- FULL NAME -------------------->
- <div ng-if="component.isProduct()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.fullName)}">
- <label class="i-sdc-form-label required">Full Name</label>
- <input class="i-sdc-form-input"
- name="fullName"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-change="validateName()"
- data-ng-maxlength="100"
- maxlength="100"
- data-ng-minlength="4"
- minlength="4"
- data-ng-model="component.fullName"
- type="text"
- data-required
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- data-tests-id="fullName"
- autofocus
- ng-readonly="isViewMode()"
- />
+ <sdc-tags form-element="editForm" element-name="tags" max-tags="20" class="i-sdc-form-item-tags"
+ sdc-disabled="isViewMode()"
+ tags="component.tags"
+ pattern="validation.tagValidationPattern"
+ special-tag="component.name"></sdc-tags>
- <div class="input-error" data-ng-show="validateField(editForm.fullName)">
- <span ng-show="editForm.fullName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
- <span ng-show="editForm.fullName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
- <span ng-show="editForm.fullName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
- <span ng-show="editForm.fullName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.fullName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <div class="input-error" data-ng-show="validateField(editForm.tags)">
+ <span ng-show="editForm.tags.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <span ng-show="editForm.tags.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_TAG_NAME_EXIST"></span>
</div>
</div>
- <!--------------------- NAME -------------------->
+ <!--------------------- RESOURCE TAGS -------------------->
<!--------------------- DESCRIPTION -------------------->
- <div class="i-sdc-form-item"
+ <div class="i-sdc-form-item description-field"
data-ng-class="{'error': validateField(editForm.description)}">
<label class="i-sdc-form-label required">Description</label>
- <textarea class="description"
- name="description"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-maxlength="1024"
- data-required
- data-ng-model="component.description"
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- maxlength="1024"
- data-tests-id="description"></textarea>
+ <textarea class="description"
+ name="description"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-maxlength="1024"
+ data-required
+ data-ng-model="component.description"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.commentValidationPattern"
+ maxlength="1024"
+ data-tests-id="description"></textarea>
<!-- placeholder="Description here..." -->
<div class="input-error" data-ng-show="validateField(editForm.description)">
</div>
<!--------------------- DESCRIPTION -------------------->
- <!--------------------- CATEGORIES -------------------->
- <div class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.category)}"
- data-ng-if="!component.isProduct()">
- <loader data-display="!categories && !initCategoreis()" relative="true"></loader>
- <label class="i-sdc-form-label required">Category</label>
- <select class="i-sdc-form-select"
- data-required
- name="category"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-change="onCategoryChange()"
- data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.selectedCategory && component.selectedCategory!=='')"
- data-ng-model="componentCategories.selectedCategory"
- data-tests-id="selectGeneralCategory"
- >
- <option value="">Select category</option>
- <optgroup ng-if="component.isResource()" data-ng-repeat="mainCategory in categories | orderBy:['name']" label="{{mainCategory.name}}" data-tests-id="{{mainCategory.name}}">
- <option data-ng-repeat="subCategory in mainCategory.subcategories track by $index"
- data-ng-selected="componentCategories.selectedCategory === calculateUnique(mainCategory.name,subCategory.name)"
- data-tests-id="{{subCategory.name}}"
- value="{{calculateUnique(mainCategory.name, subCategory.name)}}">{{subCategory.name}}
-
- </option>
- </optgroup>
- <option ng-if="component.isService()" data-ng-repeat="mainCategory in categories | orderBy:['name']"
- data-ng-selected="component.selectedCategory===mainCategory.name"
- value="{{mainCategory.name}}"
- data-tests-id="{{mainCategory.name}}">{{mainCategory.name}}</option>
- </select>
-
- <div class="input-error" data-ng-show="validateField(editForm.category)">
- <span ng-show="editForm.category.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CATEGORY_REQUIRED"></span>
- </div>
- </div>
- <!--------------------- CATEGORIES -------------------->
-
- <!--------------------- PROJECT CODE -------------------->
- <div class="i-sdc-form-item" data-ng-if="!component.isResource()"
- data-ng-class="{'error': validateField(editForm.projectCode)}">
- <label class="i-sdc-form-label required" translate="GENERAL_LABEL_PROJECT_CODE"></label>
- <input class="i-sdc-form-input" type="text"
- data-ng-model="component.projectCode"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-model-options="{ debounce: 500 }"
- maxlength="50"
- data-required
- name="projectCode"
- data-ng-pattern="validation.projectCodeValidationPattern"
- data-tests-id="projectCode"
- />
+ </div><!-- Close w-sdc-form-column -->
- <div class="input-error" data-ng-show="validateField(editForm.projectCode)">
- <span ng-show="editForm.projectCode.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED"></span>
- <span ng-show="editForm.projectCode.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID"></span>
+ <div class="w-sdc-form-column">
+ <!--------------------- IMPORT TOSCA FILE USING BROWSE (ALSO VFC) -------------------->
+ <div class="i-sdc-form-item" ng-if="isShowFileBrowse">
+ <label class="i-sdc-form-label" data-ng-class="{'required':isCreateMode()}">{{browseFileLabel}}</label>
+ <file-upload id="fileUploadElement"
+ class="i-sdc-form-input"
+ element-name="fileElement"
+ element-disabled="{{!isCreateMode()&&!(isEditMode()&&component.resourceType=='VF')}} || {{isViewMode()}}"
+ form-element="editForm"
+ file-model="component.importedFile"
+ on-file-changed-in-directive="uploadFileChangedInGeneralTab"
+ extensions="{{importedFileExtension}}"
+ default-text="'Browse to select file'"
+ data-ng-class="{'error':!(isEditMode()&&component.resourceType=='VF') && (!editForm.fileElement.$valid || !component.importedFile.filename)}"></file-upload>
</div>
- </div>
+ <!--------------------- IMPORT TOSCA FILE USING ONBOARDING -------------------->
+ <div class="i-sdc-form-item" ng-if="isShowOnboardingSelectionBrowse">
+ <label class="i-sdc-form-label required">Select VSP</label>
+ <div class="i-sdc-form-file-upload i-sdc-form-input">
+ <span class="i-sdc-form-file-name" data-tests-id="filename">{{(fileModel && fileModel.filename) || importedToscaBrowseFileText}}</span>
+ <div class="i-sdc-form-file-upload-x-btn" ng-click="cancel()" data-ng-show="fileModel.filename && fileModel.filename!=='' && elementDisabled!=='true'"></div>
+ <input type="button" name="fileElement"/>
+ <div class="file-upload-browse-btn" data-ng-click="openOnBoardingModal()" data-tests-id="browseButton">Browse</div>
+ </div>
+ </div>
- <!--------------------- ECOMPGENERATEDNAMING -------------------->
+ <div class="input-error-file-upload" data-ng-show="component.importedFile && (!editForm.fileElement.$valid || !component.importedFile.filename)">
+ <!-- editForm.fileElement.$error.required <== Can not use this, because the browse is done from outside for the first time -->
+ <span ng-show="!(isEditMode()&&component.resourceType=='VF')&&!component.importedFile.filename" translate="NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED"></span><!-- Required -->
+ <span ng-show="editForm.fileElement.$error.maxsize" translate="VALIDATION_ERROR_MAX_FILE_SIZE"></span>
+ <span ng-show="editForm.fileElement.$error.filetype" translate="NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS" translate-values="{'extensions': '{{importedFileExtension}}' }"></span>
+ <span ng-show="editForm.fileElement.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
+ </div>
+ <!--------------------- IMPORT TOSCA FILE -------------------->
- <div class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.ecompGeneratedNaming)}"
- data-ng-if="component.isService()">
- <label class="i-sdc-form-label">Ecomp Generated Naming</label>
- <select class="i-sdc-form-select"
- data-required
- name="ecompGeneratedNaming"
- data-ng-change="onEcompGeneratedNamingChange()"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-model="component.ecompGeneratedNaming"
- data-tests-id="ecompGeneratedNaming">
- <option ng-value="true">true</option>
- <option ng-value="false">false</option>
- </select>
- <div class="input-error" data-ng-show="validateField(editForm.ecompGeneratedNaming)">
+ <!--------------------- USER ID -------------------->
+ <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.contactId)}">
+ <label class="i-sdc-form-label required" translate="GENERAL_LABEL_CONTACT_ID"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-model="component.contactId"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-required="true"
+ name="contactId"
+ data-ng-pattern="validation.contactIdValidationPattern"
+ data-ng-model-options="{ debounce: 500 }"
+ data-tests-id="contactId"
+ maxlength="50"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.contactId)">
+ <span ng-show="editForm.contactId.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED"></span>
+ <span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
</div>
</div>
- <!--------------------- CATEGORIES -------------------->
-
- <!--------------------- NAMING POLICY -------------------->
- <div ng-if="component.isService()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.namingPolicy)}">
- <label class="i-sdc-form-label">Naming policy</label>
- <input class="i-sdc-form-input"
- name="fullName"
- data-ng-class="{'view-mode': isViewMode() || !component.ecompGeneratedNaming}"
- data-ng-maxlength="100"
- maxlength="100"
- data-ng-model="component.namingPolicy"
- type="text"
+ <!--------------------- USER ID -------------------->
+
+ <!--------------------- PROJECT CODE -------------------->
+ <div class="i-sdc-form-item" data-ng-if="!component.isResource()"
+ data-ng-class="{'error': validateField(editForm.projectCode)}">
+ <label class="i-sdc-form-label required" translate="GENERAL_LABEL_PROJECT_CODE"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-model="component.projectCode"
+ data-ng-class="{'view-mode': isViewMode()}"
data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- data-tests-id="namingPolicy"
- autofocus
- ng-readonly="isViewMode() || !component.ecompGeneratedNaming"
+ maxlength="50"
+ data-required
+ name="projectCode"
+ data-ng-pattern="validation.projectCodeValidationPattern"
+ data-tests-id="projectCode"
/>
- <div class="input-error" data-ng-show="validateField(editForm.namingPolicy)">
- <span ng-show="editForm.namingPolicy.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '100' }"></span>
- <span ng-show="editForm.namingPolicy.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <div class="input-error" data-ng-show="validateField(editForm.projectCode)">
+ <span ng-show="editForm.projectCode.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED"></span>
+ <span ng-show="editForm.projectCode.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID"></span>
</div>
</div>
- <!--------------------- NAMING POLICY -------------------->
-
<!--------------------- VENDOR NAME -------------------->
<div ng-if="component.isResource()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.vendorName)}">
data-ng-class="{'view-mode': isViewMode()}"
data-ng-model="component.vendorName"
data-ng-model-options="{ debounce: 500 }"
- data-ng-maxlength="25"
+ data-ng-maxlength="60"
data-required
ng-click="oldValue = component.vendorName"
name="vendorName"
data-ng-change="onVendorNameChange(oldValue)"
- data-ng-pattern="validation.vendorValidationPattern"
- maxlength="25"
+ data-ng-pattern="validation.VendorNameValidationPattern"
+ maxlength="60"
data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.vendorName && component.vendorName!=='')"
data-tests-id="vendorName"
- />
+ />
<div class="input-error" data-ng-show="validateField(editForm.vendorName)">
<span ng-show="editForm.vendorName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_VENDOR_NAME_REQUIRED"></span>
- <span ng-show="editForm.vendorName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.vendorName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '60' }"></span>
<span ng-show="editForm.vendorName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
data-ng-maxlength="25"
data-required
name="vendorRelease"
- data-ng-pattern="validation.vendorValidationPattern"
+ data-ng-pattern="validation.VendorReleaseValidationPattern"
maxlength="25"
data-ng-disabled="component.isCsarComponent() && component.vendorRelease && component.vendorRelease!==''"
data-tests-id="vendorRelease"
- />
+ />
<div class="input-error" data-ng-show="validateField(editForm.vendorRelease)">
<span ng-show="editForm.vendorRelease.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_VENDOR_RELEASE_REQUIRED"></span>
- <span ng-show="editForm.vendorRelease.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '128' }"></span>
+ <span ng-show="editForm.vendorRelease.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
<span ng-show="editForm.vendorRelease.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
</div>
<!--------------------- VENDOR RELEASE -------------------->
+ <!--------------------- Resource Model Number -------------------->
+ <div ng-if="component.isResource()"
+ class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.resourceVendorModelNumber)}">
+ <label class="i-sdc-form-label" translate="GENERAL_TAB_LABEL_RESOURCE_MODEL_NUMBER"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.resourceVendorModelNumber"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-maxlength="65"
+ name="resourceVendorModelNumber"
+ data-ng-pattern="validation.VendorModelNumberValidationPattern"
+ maxlength="65"
+ data-tests-id="resourceVendorModelNumber"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.resourceVendorModelNumber)">
+ <span ng-show="editForm.resourceVendorModelNumber.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '65' }"></span>
+ <span ng-show="editForm.resourceVendorModelNumber.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- Resource Model Number -------------------->
- </div><!-- Close w-sdc-form-column -->
-
- <div class="w-sdc-form-column">
-
- <!--------------------- RESOURCE TAGS -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.tags)}">
- <label class="i-sdc-form-label">Tags</label>
+ <!--------------------- ECOMPGENERATEDNAMING -------------------->
- <sdc-tags form-element="editForm" element-name="tags" max-tags="20" class="i-sdc-form-item-tags"
- sdc-disabled="isViewMode()"
- tags="component.tags"
- pattern="validation.tagValidationPattern"
- special-tag="component.name"></sdc-tags>
+ <div class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.ecompGeneratedNaming)}"
+ data-ng-if="component.isService()">
+ <label class="i-sdc-form-label">Ecomp Generated Naming</label>
+ <select class="i-sdc-form-select"
+ data-required
+ name="ecompGeneratedNaming"
+ data-ng-change="onEcompGeneratedNamingChange()"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.ecompGeneratedNaming"
+ data-tests-id="ecompGeneratedNaming">
+ <option ng-value="true">true</option>
+ <option ng-value="false">false</option>
+ </select>
+ <div class="input-error" data-ng-show="validateField(editForm.ecompGeneratedNaming)">
- <div class="input-error" data-ng-show="validateField(editForm.tags)">
- <span ng-show="editForm.tags.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="editForm.tags.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_TAG_NAME_EXIST"></span>
+ </div>
</div>
- </div>
- <!--------------------- RESOURCE TAGS -------------------->
+ <!--------------------- CATEGORIES -------------------->
- <!--------------------- USER ID -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.contactId)}">
- <label class="i-sdc-form-label " data-ng-class="{'required':!component.isProduct()}" translate="GENERAL_LABEL_CONTACT_ID"></label>
- <input class="i-sdc-form-input" type="text" data-ng-if="!component.isProduct()"
- data-ng-model="component.contactId"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-required="!component.isProduct()"
- name="contactId"
- data-ng-pattern="validation.contactIdValidationPattern"
- data-ng-model-options="{ debounce: 500 }"
- data-tests-id="contactId"
- maxlength="50"
+ <!--------------------- NAMING POLICY -------------------->
+ <div ng-if="component.isService()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.namingPolicy)}">
+ <label class="i-sdc-form-label">Naming policy</label>
+ <input class="i-sdc-form-input"
+ name="fullName"
+ data-ng-class="{'view-mode': isViewMode() || !component.ecompGeneratedNaming}"
+ data-ng-maxlength="100"
+ maxlength="100"
+ data-ng-model="component.namingPolicy"
+ type="text"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.commentValidationPattern"
+ data-tests-id="namingPolicy"
+ autofocus
+ ng-readonly="isViewMode() || !component.ecompGeneratedNaming"
/>
- <input class="i-sdc-form-input" type="text" data-ng-if="component.isProduct()"
- data-ng-model="component.contacts[0]"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-required="!component.isProduct()"
- name="contactId"
- data-ng-pattern="validation.contactIdValidationPattern"
- data-ng-model-options="{ debounce: 500 }"
- data-tests-id="contactId"
- maxlength="50"
- />
- <div class="input-error" data-ng-show="validateField(editForm.contactId)">
- <span ng-show="editForm.contactId.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED"></span>
- <span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
+ <div class="input-error" data-ng-show="validateField(editForm.namingPolicy)">
+ <span ng-show="editForm.namingPolicy.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '100' }"></span>
+ <span ng-show="editForm.namingPolicy.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
</div>
- </div>
- <!--------------------- USER ID -------------------->
-
+ <!--------------------- NAMING POLICY -------------------->
+ <!--------------------- Service Type -------------------->
+ <div ng-if="component.isService()"
+ class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.serviceType)}">
+ <label class="i-sdc-form-label" translate="GENERAL_TAB_LABEL_SERVICE_TYPE"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.serviceType"
+ data-ng-model-options="{ debounce: 500 }"
+ name="serviceType"
+ data-tests-id="serviceType"
+ data-ng-maxlength="25"
+ data-ng-pattern="validation.VendorReleaseValidationPattern"
+ maxlength="25"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.serviceType)">
+ <span ng-show="editForm.serviceType.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.serviceType.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- Service Type -------------------->
+
+ <!--------------------- Service Role -------------------->
+ <div ng-if="component.isService()"
+ class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.serviceRole)}">
+ <label class="i-sdc-form-label" translate="GENERAL_TAB_LABEL_SERVICE_ROLE"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.serviceRole"
+ data-ng-model-options="{ debounce: 500 }"
+ name="serviceRole"
+ data-tests-id="serviceRole"
+ data-ng-maxlength="25"
+ data-ng-pattern="validation.VendorReleaseValidationPattern"
+ maxlength="25"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.serviceRole)">
+ <span ng-show="editForm.serviceRole.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.serviceRole.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- Service Role -------------------->
+ <div class="meta-data" data-ng-if="component.creationDate">
+ <div>
+ <b>Created:</b>
+ </div>
+ <div class="meta-data-item-value">{{component.creationDate | date:'MM/dd/yyyy'}}, {{component.creatorFullName}}</div>
+ <div>
+ <b>Modifed:</b>
+ </div>
+ <div class="meta-data-item-value">
+ {{component.lastUpdateDate | date:'MM/dd/yyyy'}}
+ </div>
+ <div>
+ <b>UUID:</b>
+ </div>
+ <div class="meta-data-item-value">
+ {{component.uuid}}
+ </div>
+ <div>
+ <b>Invariant UUID:</b>
+ </div>
+ <div class="meta-data-item-value">
+ {{component.invariantUUID}}
+ </div>
+ </div>
</div><!-- Close w-sdc-form-column -->
</div>
</div><!-- Close w-sdc-form-section-container -->
</form>
-
</div>
.sdc-workspace-general-step {
-
+ display: flex;
.w-sdc-form {
padding: 0;
-
+ flex-grow: 10;
.i-sdc-form-file-upload{
input[type="button"] {
cursor: pointer;
}
}
+ .description{
+ height: 300px;
+ }
+
+ .i-sdc-form-item.description-field{
+ margin-bottom: 0;
+ }
+
.w-sdc-form-section-container {
text-align: center;
}
width: auto;
padding: 10px;
}
+ margin-bottom: 15px;
}
.i-sdc-form-label {
}
+ .w-sdc-form-column {
+ position: relative;
+ }
+
+ .meta-data{
+ padding: 8px 0 2px 20px;
+ text-align: left;
+ background-color: @tlv_color_t;
+ position: absolute;
+ bottom: 0;
+ width: 100%;
+ .meta-data-item-value{
+ padding-bottom: 6px;
+ }
+ }
+
+ .upper-general-fields{
+ display: flex;
+ }
+
+ .selected-icon-container{
+ flex-grow: 1;
+ display: flex;
+ align-items: center;
+ .selected-icon-inner-container{
+ height: 64px;
+ width: 64px;
+ margin: 0 auto;
+ }
+ .update-component-icon{
+ position: relative;
+ float: right;
+ cursor: pointer;
+ }
+ .selected-icon{
+ position: relative;
+ top: -20px;
+ z-index: -1;
+ &.disable{
+ position: inherit;
+ }
+ }
+ &.show-only-on-over{
+ .update-component-icon{
+ display: none;
+ }
+ .selected-icon{
+ position: inherit;
+ }
+ &:hover{
+ .update-component-icon{
+ display: inline-block;
+ }
+ .selected-icon{
+ position: relative;
+ }
+ }
+ }
+ }
+
+ .name-and-category-fields{
+ flex-grow: 5;
+ }
+
+
+
+
}
+++ /dev/null
-<div class="workspace-icons">
-
- <form novalidate class="w-sdc-form" name="iconForm">
- <label class="i-sdc-form-label icons-label required">Icons</label>
- <div class="selected-icon-container" data-ng-class="{'view-mode': isViewMode()}">
- <div class="i-sdc-form-item-suggested-icon large selected-icon {{iconSprite}} {{component.icon}}"
- data-ng-class="{ 'disable': isViewMode() }"
- ng-model="component.icon"
- tooltips tooltip-content='{{component.icon | translate}}'
- >
- </div>
- </div>
- <div data-ng-class="{'view-mode': isViewMode()}" class="icons-text">Select one of the icons below for the asset</div>
- <div class="i-sdc-form-item suggested-icons-container" data-ng-class="{'view-mode no-pointer-events' : isViewMode()}">
- <div class ="suggested-icon-wrapper" ng-class="component.icon==='{{iconSrc}}' ? 'selected' : '' " data-ng-repeat="iconSrc in icons track by $index">
- <div class="i-sdc-form-item-suggested-icon large {{iconSprite}} {{iconSrc}}" data-ng-class="component.isAlreadyCertified() || isViewMode() ? 'disable':'hand'"
- ng-model="component.icon"
- data-tests-id="{{iconSrc}} iconBox"
- data-ng-click="!component.isAlreadyCertified() && setComponentIcon(iconSrc)"
- tooltips tooltip-content='{{iconSrc | translate}}'
- >
- </div>
- </div>
- </div>
- </form>
-</div>
+++ /dev/null
-.workspace-icons {
-
- width: 89%;
- display: inline-block;
- text-align: center;
- align-items: center;
-
- .w-sdc-form {
- padding-top: 0px;
- padding-bottom: 0px;
- .selected-icon-container {
- text-align: left;
- border: 1px solid #cfcfcf;
- clear: both;
- margin-bottom: 30px;
- padding: 2px 0px 5px 5px;
- .selected-icon {
- margin: 8px 5px 0px 6px;
- }
- }
-
- .suggested-icons-container {
- text-align: left;
- border: 1px solid #cfcfcf;
- clear: both;
- padding: 2px 0px 5px 5px;
- height: 340px;
- margin-bottom: 0px;
-
- .suggested-icon-wrapper {
- margin: 8px 5px 0px 6px;
- display: inline-block;
-
- &.selected {
- border: 2px solid @main_color_a;
- border-radius: 35px;
- display: inline-block;
- line-height: 0px;
- padding: 3px;
- }
-
- }
- .suggested-icon {
- // margin: 8px 5px 0px 6px;
- display: inline-block;
- &.disable{
- opacity: 0.4;
- }
- }
- }
-
- .icons-label {
- float: left;
- }
-
- .icons-text {
- text-align: left;
- line-height: 32px;
- padding-left: 10px;
- width: 100%;
- border: 1px solid #cfcfcf;
- border-bottom: none;
- }
- }
-}
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.item-opened{
word-wrap: break-word;
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
width: 46%;
min-width: 46%;
display: inline-block;
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-'use strict';
-import {ComponentFactory} from "app/utils";
-import {Product, IGroup, ISubCategory, IMainCategory} from "app/models";
-import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
-import {CacheService} from "app/services";
-
-export interface IProductHierarchyScope extends IWorkspaceViewModelScope {
-
- categoriesOptions:Array<IMainCategory>;
- product:Product;
- isLoading:boolean;
- showDropDown:boolean;
-
- onInputTextClicked():void;
- onGroupSelected(category:IMainCategory, subcategory:ISubCategory, group:IGroup):void;
- clickOutside():void;
- deleteGroup(uniqueId:string):void;
-}
-
-export class ProductHierarchyViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'ComponentFactory',
- '$state'
- ];
-
- constructor(private $scope:IProductHierarchyScope,
- private cacheService:CacheService,
- private ComponentFactory:ComponentFactory,
- private $state:ng.ui.IStateService) {
-
-
- this.$scope.product = <Product>this.$scope.getComponent();
- this.$scope.setValidState(true);
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private initCategories = () => {
- this.$scope.categoriesOptions = angular.copy(this.cacheService.get('productCategories'));
- let selectedGroup:Array<IGroup> = [];
- _.forEach(this.$scope.product.categories, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- selectedGroup = selectedGroup.concat(subcategory.groupings);
- });
- });
- _.forEach(this.$scope.categoriesOptions, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- _.forEach(subcategory.groupings, (group:ISubCategory) => {
- let componentGroup:IGroup = _.find(selectedGroup, (componentGroupObj) => {
- return componentGroupObj.uniqueId == group.uniqueId;
- });
- if (componentGroup) {
- group.isDisabled = true;
- }
- });
- });
- });
- };
-
- private setFormValidation = ():void => {
-
- this.$scope.setValidState(true);
-
- };
-
- private initScope = ():void => {
- this.$scope.isLoading = false;
- this.$scope.showDropDown = false;
- this.initCategories();
- this.setFormValidation();
-
- this.$scope.onGroupSelected = (category:IMainCategory, subcategory:ISubCategory, group:IGroup):void => {
- this.$scope.product.addGroup(category, subcategory, group);
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
- group.isDisabled = true;
- this.$scope.showDropDown = false;
- this.setFormValidation();
- };
-
- this.$scope.onInputTextClicked = ():void => {//just edit the component in place, no pop up nor server update ?
- this.$scope.showDropDown = !this.$scope.showDropDown;
- };
-
- this.$scope.clickOutside = ():any => {
- this.$scope.showDropDown = false;
- };
-
- this.$scope.deleteGroup = (uniqueId:string):void => {
- //delete group from component
- this.$scope.product.deleteGroup(uniqueId);
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
- this.setFormValidation();
- //enabled group
- _.forEach(this.$scope.categoriesOptions, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- let groupObj:IGroup = _.find(subcategory.groupings, (group) => {
- return group.uniqueId === uniqueId;
- });
- if (groupObj) {
- groupObj.isDisabled = false;
- }
- });
- });
- }
- };
-}
+++ /dev/null
-<div class="workspace-hierarchy">
- <div class="dropdown-container" clicked-outside="{onClickedOutside: 'clickOutside()', clickedOutsideEnable: 'true'}" >
- <input placeholder="Add Group" data-ng-click="onInputTextClicked()" class="dropdown-input-text" data-ng-model="search.filterTerms" data-ng-disabled="isViewMode()" data-ng-class="{'view-mode': isViewMode()}" data-ng-model-options="{debounce: 200}"/>
- <div data-ng-class="{'show': showDropDown}" class="dropdown-content" >
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="false" class="scrollbar-container">
- <div ng-repeat="category in categoriesOptions track by $index">
- <div ng-repeat="subcategory in category.subcategories track by $index">
- <div class="dropdown-option" ng-show="!category.filteredGroup || category.filteredGroup.length > 0">
- <div class="category-container">
- <div class="category">{{category.name}}</div>
- <div class="subcategory">{{subcategory.name}}</div>
- </div>
- <div class="groupings-container">
- <div ng-init="group.filterTerms = group.name + ' ' + category.name + ' ' + subcategory.name"
- ng-repeat="group in (category.filteredGroup = (subcategory.groupings | filter:search )) track by $index">
- <div class="group" data-ng-disabled="group.isDisabled" data-ng-class="{'disabled-group': group.isDisabled}" ng-click="onGroupSelected(category, subcategory, group)">
- <span >{{group.name}}</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
- </div>
- <div class="hierarchy-groups-container no-border-top" data-ng-class="{'view-mode': isViewMode()}">
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <div ng-if="!product.categories.length || product.categories.length === 0" class="no-groups-text" translate="NEW_PRODUCT_NO_CATEGORIES_TO_DISPLAY"></div>
- <div ng-repeat="category in product.categories track by $index">
- <div ng-repeat="subcategory in category.subcategories track by $index">
- <div class="group-tag" ng-repeat="group in subcategory.groupings track by $index"
- data-ng-init="tooltip = '<b>' + category.name + '</b><br />' + subcategory.name">
- <sdc-tag sdc-disable="isViewMode()" data-on-delete="deleteGroup(uniqueId)" data-tag-data="{tag: group.name, tooltip: tooltip, id: group.uniqueId }"></sdc-tag>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
-</div>
+++ /dev/null
-.workspace-hierarchy {
- display: inline-block;
- width: 93%;
-
- .scrollbar-container{
- max-height:400px;
- .perfect-scrollbar;
- }
-
- .dropdown-container {
- position: relative;
- display: inline-block;
- width: 100%;
-
- &:after{
- top: 47%;
- right: 1%;
- border: solid transparent;
- content: " ";
- height: 0;
- width: 0;
- position: absolute;
- pointer-events: none;
- border-color: rgba(0, 0, 0, 0);
- border-top-color: black;
- border-width: 4px;
- margin-left: -4px;
- }
-
- .dropdown-input-text {
- width: 100%;
- padding: 4px 10px;
- }
-
- .dropdown-content {
- .perfect-scrollbar;
- border: 1px solid #d8d8d8;
- display: none;
- position: absolute;
- overflow: hidden;
- width: 100%;
- .bg_c;
- max-height: 400px;
- z-index: 999999;
-
- .dropdown-option {
- border-bottom: 1px solid #d8d8d8;
- display: inline-block;
- width: 100%;
- }
-
- .category-container{
- width: 250px;
- float: left;
- padding-left: 5px;
-
- .category {
- .bold;
- padding: 3px 3px 2px 3px;
- &:after{
- .sprite;
- .arrow-left;
- content: '';
- margin-left: 5px;
- transform: rotate(180deg);
- }
- }
- .subcategory {
- padding-left: 3px;
- }
- }
-
- .groupings-container{
- display: inline-block;
- width: 424px;
- border-left: 1px solid #d8d8d8;
- min-height: 55px;
- .group{
- padding: 3px 3px 3px 10px;
- &:hover{
- .hand;
- .bg_n;
- }
- &.disabled-group {
- opacity: 0.5;
- &:hover{
- cursor: auto;
- .bg_c;
- }
- }
- }
- }
-
- .seperator {
- height: 1px;
- width: 100%;
- .bg_j;
- margin: 5px 0px;
- }
- }
- .show {
- display: block;
- }
- }
-
- .hierarchy-groups-container{
- .b_9;
- width: 100%;
- border: 1px solid #d8d8d8;
- height: 425px;
- padding: 15px;
- text-align: center;
-
- .scrollbar-container {
- z-index: 0;
- }
-
- .no-group-text{
- text-align: center;
- margin-top:25px;
- a {
- cursor: pointer;
- }
- }
- .group-tag{
- display: inline-block;
- float: left;
- }
- }
-}
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.text{
overflow: hidden;
.workspace-tosca-artifact {
- width: 93%;
+ width: 100%;
display: inline-block;
.w-sdc-classic-btn {
float: right;
.table-container-flex {
- margin-top: 27px;
-
+ margin-top: 0;
.item-opened{
word-wrap: break-word;
}
changeLifecycleState(state:string):void;
enabledTabs():void
isDesigner():boolean;
- isProductManager():boolean;
isViewMode():boolean;
isEditMode():boolean;
isCreateMode():boolean;
updateSelectedMenuItem():void;
uploadFileChangedInGeneralTab():void;
updateMenuComponentName(ComponentName:string):void;
+ getTabTitle():string;
reload(component:Component):void;
}
} else {
if (this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT &&
this.$scope.component.lastUpdaterUserId === this.cacheService.get("user").userId) {
- if (this.$scope.component.isProduct() && this.role == Role.PRODUCT_MANAGER) {
- mode = WorkspaceMode.EDIT;
- }
if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role == Role.DESIGNER) {
mode = WorkspaceMode.EDIT;
}
};
private initLeftPalette = ():void => {
- this.LeftPaletteLoaderService.loadLeftPanel(this.$scope.component.componentType);
+ this.LeftPaletteLoaderService.loadLeftPanel(this.$scope.component);
};
private initScope = ():void => {
this.$scope.$state = this.$state;
this.$scope.isLoading = false;
this.$scope.isComposition = (this.$state.current.name.indexOf(States.WORKSPACE_COMPOSITION) > -1);
- this.$scope.isDeployment = (this.$state.current.name.indexOf(States.WORKSPACE_DEPLOYMENT) > -1);
+ this.$scope.isDeployment = this.$state.current.name == States.WORKSPACE_DEPLOYMENT;
this.$scope.progressService = this.progressService;
this.$scope.getComponent = ():Component => {
type: this.$scope.componentType.toLowerCase(),
mode: WorkspaceMode.VIEW,
components: this.$state.params['components']
- },{reload: true});
+ }, {reload: true});
};
switch (url) {
case 'lifecycleState/CHECKOUT':
// only checkOut get the full component from server
- // this.$scope.component = component;
+ // this.$scope.component = component;
// Work around to change the csar version
if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
(<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
return this.role == Role.DESIGNER;
};
- this.$scope.isProductManager = ():boolean => {
- return this.role == Role.PRODUCT_MANAGER;
- };
-
this.$scope.isDisableMode = ():boolean => {
return this.$scope.mode === WorkspaceMode.VIEW && this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKIN;
};
this.$scope.showFullIcons = ():boolean => {
- //we show revert and save icons only in general\icon view
- return this.$state.current.name === States.WORKSPACE_GENERAL ||
- this.$state.current.name === States.WORKSPACE_ICONS;
+ //we show revert and save icons only in general view
+ return this.$state.current.name === States.WORKSPACE_GENERAL;
};
this.$scope.isCreateMode = ():boolean => {
};
this.$scope.showLifecycleIcon = ():boolean => {
- return this.role == Role.DESIGNER ||
- this.role == Role.PRODUCT_MANAGER;
+ return this.role == Role.DESIGNER;
};
this.$scope.getStatus = ():string => {
if (!this.$scope.component.isLatestVersion() && Role.OPS != this.role && Role.GOVERNOR != this.role) {
result = false;
}
- if (this.role === Role.PRODUCT_MANAGER && !this.$scope.component.isProduct()) {
- result = false;
- }
- if ((this.role === Role.DESIGNER || this.role === Role.TESTER)
- && this.$scope.component.isProduct()) {
- result = false;
- }
if (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState && this.$scope.isViewMode()) {
result = false;
}
this.$scope.$watch('$state.current.name', (newVal:string):void => {
if (newVal) {
this.$scope.isComposition = (newVal.indexOf(States.WORKSPACE_COMPOSITION) > -1);
- this.$scope.isDeployment = (newVal.indexOf(States.WORKSPACE_DEPLOYMENT) > -1);
+ this.$scope.isDeployment = newVal == States.WORKSPACE_DEPLOYMENT;
}
});
+ this.$scope.getTabTitle = ():string => {
+ return this.$scope.leftBarTabs.menuItems.find((menuItem:MenuItem)=>{
+ return menuItem.state == this.$scope.$state.current.name;
+ }).text;
+ };
+
this.$scope.reload = (component:Component):void => {
this.$state.go(this.$state.current.name,{id:component.uniqueId},{reload:true});
};
private initVersionObject = ():void => {
this.$scope.versionsList = (this.$scope.component.getAllVersionsAsSortedArray()).reverse();
- this.$scope.changeVersion = {selectedVersion: _.find(this.$scope.versionsList, {versionId: this.$scope.component.uniqueId})};
+ this.$scope.changeVersion = {
+ selectedVersion: _.find(this.$scope.versionsList, (versionObj)=> {
+ return versionObj.versionId === this.$scope.component.uniqueId;
+ })
+ };
};
private getNewComponentBreadcrumbItem = ():MenuItem => {
<div class="w-sdc-main-container">
<div class="w-sdc-left-sidebar" data-ng-if="!isComposition">
- <div class="i-sdc-left-sidebar-item">
- <expand-collapse-menu-box menu-items-group="leftBarTabs" menu-title="{{menuComponentTitle}}" parent-scope="this"> </expand-collapse-menu-box>
+ <div class="menu-header" tooltips tooltip-content="{{menuComponentTitle}}">
+ {{menuComponentTitle}}
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" ng-class="{'selected': menuItem.state == $state.current.name}" ng-repeat="menuItem in leftBarTabs.menuItems track by $index">
+ <div class="expand-collapse-menu-box-item-text" ng-click="onMenuItemPressed(menuItem.state)" ng-class="{'disabled': menuItem.isDisabled }" data-tests-id="{{menuItem.text}}">{{menuItem.text}}</div>
</div>
</div>
<button ng-if="!isViewMode() && isCreateMode()" data-ng-disabled="!isValidForm || isDisableMode() || isLoading" ng-click="save()" class="tlv-btn outline green" data-tests-id="create/save">Create</button>
- <span data-ng-if="(isDesigner() || isProductManager()) && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
+ <span data-ng-if="isDesigner() && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
data-ng-class="{'disabled' : !isValidForm || isDisableMode() || isViewMode()}" ng-click="changeLifecycleState('deleteVersion')"
class="sprite-new delete-btn" data-tests-id="delete_version" sdc-smart-tooltip="">Delete</span>
<span data-ng-if="isDesigner()" data-ng-class="{'disabled' :isDisableMode() || isViewMode()}" ng-click="revert()" class="sprite-new revert-btn" data-tests-id="revert"
data-ng-show="showFullIcons()" sdc-smart-tooltip="">Revert</span>
- <span data-ng-if="isComposition && !component.isProduct()" class="sprite-new print-screen-btn" entity="component" print-graph-screen data-tests-id="printScreen"></span>
+ <span data-ng-if="isComposition" class="sprite-new print-screen-btn" entity="component" print-graph-screen data-tests-id="printScreen"></span>
<span class="delimiter"></span>
<span class="sprite-new x-btn" data-ng-click="goToBreadcrumbHome()" sdc-smart-tooltip="">Close</span>
</div>
</div>
-
- <div data-ng-if="component.creationDate && (!isComposition && !isDeployment)" class="sdc-asset-creation-info"><b>Created:</b> {{component.creationDate | date:'MM/dd/yyyy'}}, {{component.creatorFullName}} | <b>Modifed:</b> {{component.lastUpdateDate | date:'MM/dd/yyyy'}} | <b>UUID:</b> {{component.uuid}}<b> Invariant UUID:</b> {{component.invariantUUID}}</div>
-
+ <div class="tab-title" data-ng-if="!isComposition && !isDeployment">
+ {{getTabTitle()}}
+ </div>
<div class="w-sdc-main-container-body-content" data-ng-class="{'third-party':thirdParty}" data-ui-view></div>
</div>
</div>
}
.w-sdc-left-sidebar {
- padding: 3px 3px 0px 0px;
- background-color: @main_color_p;
- box-shadow: 7px -3px 6px -8px @main_color_n;
+ padding: 0px;
+ background-color: @tlv_color_t;
+ box-shadow: none;
z-index: 2;
+ border-right: 1px solid @main_color_o;
+ .menu-header{
+ border-bottom: 1px solid @main_color_o;
+ height: 53px;
+ .f-type._16_m;
+ font-weight: 700;
+ line-height: 53px;
+ padding-left: 40px;
+ padding-right: 10px;
+ width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: inline-block;
+ white-space: nowrap;
+ }
+ .i-sdc-designer-sidebar-section-content-item{
+ .f-type._13_m;
+ color: @main_color_m;
+ margin-left: 20px;
+ padding-left: 20px;
+ margin-top: 20px;
+ height: 17px;
+ .hand;
+ &:hover{
+ color: @func_color_s;
+ font-weight: 600;
+ }
+ &.selected{
+ border-left: 4px solid @main_color_a;
+ color: @main_color_a;
+ margin-left: 18px;
+ padding-left: 18px;
+ font-weight: 600;
+
+ }
+ }
}
.sdc-asset-creation-info {
margin-top: 6px;
}
}
+ .tab-title{
+ height: 110px;
+ padding-left: 100px;
+ line-height: 110px;
+ .f-type ._28;
+ }
.w-sdc-main-container-body-content {
- height:calc(~'100% - @{action_nav_height}');
-
- text-align: center;
+ height:calc(~'100% - @{action_nav_height} - @{tab_title}');
align-items: center;
- padding: 40px 14% 20px 14%;
+ padding: 0 100px 20px 100px;
&.third-party {
text-align: left;
padding: 0;
position: absolute;
- top: @action_nav_height;
+ top: @action_nav_height + @tab_title;
left: 0;
right: 0;
bottom: 0;
}
}
-
-.properties-assignment .sdc-workspace-container .w-sdc-main-right-container .w-sdc-main-container-body-content{
- padding: 80px 2% 40px 2%;
-}
"=========== NEW RESOURCE SERVICE ===========": "",
"NEW_SERVICE_RESOURCE_WRAPPER_TAB_GENERAL_INFORMATION": "General Information",
- "NEW_SERVICE_RESOURCE_WRAPPER_TAB_ASSIGN_PRODUCT_HIERARCHY": "Assign Product Hierarchy",
"NEW_SERVICE_RESOURCE_WRAPPER_TAB_ADDITIONAL_INFO": "Additional Information",
"NEW_SERVICE_RESOURCE_WRAPPER_TAB_BILLING_AND_ORDERING": "Order Attributes & Rules",
- "NEW_SERVICE_RESOURCE_WRAPPER_TAB_PRODUCT_COMPOSITION": "Bill Attributes & Rules",
"NEW_SERVICE_RESOURCE_SAVE_BUTTON": "Save",
"NEW_SERVICE_RESOURCE_DONE_BUTTON": "Done",
"NEW_SERVICE_RESOURCE_ERROR_SERVICE_ICON": "Icon required.",
"NEW_SERVICE_RESOURCE_ERROR_RESOURCE_ICON": "Icon required.",
"NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED": "Name is required.",
- "NEW_SERVICE_RESOURCE_ERROR_PRODUCT_NAME_REQUIRED": "Name is required.",
"NEW_SERVICE_RESOURCE_ERROR_RESOURCE_DESCRIPTION_REQUIRED": "Description is required.",
- "NEW_SERVICE_RESOURCE_ERROR_PRODUCT_DESCRIPTION_REQUIRED": "Description is required.",
"NEW_SERVICE_RESOURCE_ERROR_VENDOR_NAME_REQUIRED": "Vendor name is required.",
"NEW_SERVICE_RESOURCE_ERROR_VENDOR_RELEASE_REQUIRED": "Vendor Release is required.",
"NEW_SERVICE_RESOURCE_ERROR_TEMPLATE_REQUIRED": "Template is required.",
"NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED": "Tosca file is required.",
"NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE": "Invalid csar file",
"NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS": "File extension should be {{extensions}}.",
- "NEW_PRODUCT_NO_CATEGORIES_TO_DISPLAY": "Your product is not assigned to any group yet. <br> To select/find a group, begin typing above and select group to add",
"=========== SUGGESTED ICONS TOOLTIP ===========": "",
"call_controll": "Call Control",
@import 'sprite-old.less';
@import 'sprite.less';
-@import 'sprite-product-icons.less';
@import 'sprite-resource-icons.less';
@import 'sprite-services-icons.less';
@import '../../app/view-models/modals/message-modal/message-client-modal/client-message-modal.less';
@import '../../app/view-models/modals/message-modal/message-server-modal/server-message-modal.less';
@import '../../app/view-models/modals/onboarding-modal/onboarding-modal.less';
+@import '../../app/view-models/modals/icons-modal/icons-modal-view.less';
@import '../../app/view-models/onboard-vendor/onboard-vendor.less';
@import '../../app/view-models/support/support.less';
@import '../../app/view-models/tabs/general-tab.less';
@import '../../app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less';
@import '../../app/view-models/workspace/tabs/distribution/distribution.less';
@import '../../app/view-models/workspace/tabs/general/general.less';
-@import '../../app/view-models/workspace/tabs/icons/icons.less';
@import '../../app/view-models/workspace/tabs/information-artifacts/information-artifacts.less';
@import '../../app/view-models/workspace/tabs/inputs/inputs.less';
@import '../../app/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less';
@import '../../app/view-models/workspace/tabs/inputs/service-input/service-inputs.less';
-@import '../../app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less';
@import '../../app/view-models/workspace/tabs/properties/properties.less';
@import '../../app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less';
@import '../../app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less';
font-family: @font-opensans-light;
font-size: 36px;
}
+ ._28 {
+ font-family: @font-opensans-light;
+ font-size: 28px;
+ }
._24 {
font-family: @font-opensans-light;
font-size: 24px;
width: 552px;
}
+.modal-dialog.modal-sdc-auto {
+ width: auto;
+}
+
.modal-dialog.modal-sdc-xsm {
width: 432px;
}
.modal-sdc-l,
.modal-sdc-md,
.modal-sdc-sm,
-.modal-sdc-xsm {
+.modal-sdc-xsm,
+.modal-sdc-auto {
.w-sdc-classic-top-line-modal {
padding: 0 30px;
+++ /dev/null
-.sprite-product-icons {
- background-image: url('images/sprites/sprite-product-icons.png');
- display: inline-block;
-}
-
-.sprite-product-icons.disable { opacity:0.5;}
-
-.sprite-product-icons.setting { background-position: -291px -102px; width: 61px; height: 67px;}
-.sprite-product-icons.setting.small { background-position: -217px -142px; width: 29px; height: 28px;}
-.sprite-product-icons.setting.medium { background-position: -148px -130px; width: 41px; height: 40px;}
-.sprite-product-icons.setting.large { background-position: -77px -110px; width: 60px; height: 60px;}
-
-.sprite-product-icons.cloud { background-position: -290px -215px; width: 64px; height: 43px;}
-.sprite-product-icons.cloud.small { background-position: -217px -232px; width: 29px; height: 28px;}
-.sprite-product-icons.cloud.medium { background-position: -148px -220px; width: 41px; height: 40px;}
-.sprite-product-icons.cloud.large { background-position: -77px -200px; width: 60px; height: 60px;}
-
-.sprite-product-icons.security { background-position: -289px -293px; width: 50px; height: 57px;}
-.sprite-product-icons.security.small { background-position: -217px -321px; width: 29px; height: 28px;}
-.sprite-product-icons.security.medium { background-position: -148px -310px; width: 41px; height: 40px;}
-.sprite-product-icons.security.large { background-position: -77px -290px; width: 60px; height: 60px;}
-
-.sprite-product-icons.network { background-position: -290px -383px; width: 56px; height: 57px;}
-.sprite-product-icons.network.small { background-position: -217px -411px; width: 29px; height: 29px;}
-.sprite-product-icons.network.medium { background-position: -148px -399px; width: 41px; height: 41px;}
-.sprite-product-icons.network.large { background-position: -77px -380px; width: 60px; height: 60px;}
-
-.sprite-product-icons.orphan { background-position: -290px -478px; width: 52px; height: 52px;}
-.sprite-product-icons.orphan.small { background-position: -217px -500px; width: 29px; height: 29px;}
-.sprite-product-icons.orphan.medium { background-position: -148px -488px; width: 41px; height: 41px;}
-.sprite-product-icons.orphan.large { background-position: -77px -470px; width: 60px; height: 60px;}
-
-.sprite-product-icons.defaulticon { background-position: -290px -478px; width: 52px; height: 52px;}
-.sprite-product-icons.defaulticon.small { background-position: -217px -500px; width: 29px; height: 29px;}
-.sprite-product-icons.defaulticon.medium { background-position: -148px -488px; width: 41px; height: 41px;}
-.sprite-product-icons.defaulticon.large { background-position: -77px -470px; width: 60px; height: 60px;}
-
-.sprite-product-icons.vfw { background-position: -289px -548px; width: 73px; height: 73px;}
-.sprite-product-icons.vfw.small { background-position: -217px -591px; width: 29px; height: 29px;}
-.sprite-product-icons.vfw.medium { background-position: -148px -580px; width: 41px; height: 41px;}
-.sprite-product-icons.vfw.large { background-position: -77px -560px; width: 60px; height: 61px;}
-
-.sprite-product-icons.wanx { background-position: -290px -664px; width: 59px; height: 47px;}
-.sprite-product-icons.wanx.small { background-position: -217px -681px; width: 30px; height: 30px;}
-.sprite-product-icons.wanx.medium { background-position: -148px -670px; width: 41px; height: 41px;}
-.sprite-product-icons.wanx.large { background-position: -77px -651px; width: 60px; height: 60px;}
-
-.sprite-product-icons.vrouter { background-position: -289px -758px; width: 69px; height: 43px;}
-.sprite-product-icons.vrouter.small { background-position: -217px -772px; width: 29px; height: 29px;}
-.sprite-product-icons.vrouter.medium { background-position: -148px -760px; width: 41px; height: 41px;}
-.sprite-product-icons.vrouter.large { background-position: -77px -741px; width: 60px; height: 60px;}
-
-.sprite-product-icons.ucpe { background-position: -289px -832px; width: 59px; height: 60px;}
-.sprite-product-icons.ucpe.small { background-position: -217px -862px; width: 28px; height: 29px;}
-.sprite-product-icons.ucpe.medium { background-position: -148px -849px; width: 41px; height: 41px;}
-.sprite-product-icons.ucpe.large { background-position: -77px -831px; width: 60px; height: 61px;}
-
-.sprite-product-icons.mobility { background-position: -288px -919px; width: 64px; height: 62px;}
-.sprite-product-icons.mobility.small { background-position: -216px -952px; width: 29px; height: 29px;}
-.sprite-product-icons.mobility.medium { background-position: -147px -940px; width: 41px; height: 41px;}
-.sprite-product-icons.mobility.large { background-position: -76px -921px; width: 60px; height: 60px;}
-
-.sprite-product-icons.wanx_customer_managed { background-position: -290px -1024px; width: 58px; height: 62px;}
-.sprite-product-icons.wanx.small_customer_managed { background-position: -217px -1041px; width: 30px; height: 38px;}
-.sprite-product-icons.wanx.medium_customer_managed { background-position: -148px -1030px; width: 42px; height: 47px;}
-.sprite-product-icons.wanx.large_customer_managed { background-position: -77px -1011px; width: 61px; height: 66px;}
-
-.sprite-product-icons.wanx_attr_managed { background-position: -290px -1114px; width: 59px; height: 62px;}
-.sprite-product-icons.wanx.small_att_managed { background-position: -218px -1131px; width: 31px; height: 36px;}
-.sprite-product-icons.wanx.medium_att_managed { background-position: -149px -1120px; width: 42px; height: 47px;}
-.sprite-product-icons.wanx.large_att_managed { background-position: -77px -1101px; width: 60px; height: 67px;}
.sprite-resource-icons.allotted_resource.medium { background-position: -141px -4898px; width: 41px; height: 41px;}
.sprite-resource-icons.allotted_resource.large { background-position: -70px -4879px; width: 60px; height: 60px;}
+.sprite-resource-icons.vnfconfiguration.large { background-position: -70px -4959px; width: 60px; height: 60px;}
.round-expand-icon:hover { background-position: -100px -1188px; width: 15px; height: 15px; }
.round-expand-icon.open { background-position: -50px -1216px; width: 15px; height: 15px; }
.round-expand-icon.open:hover { background-position: -100px -1216px; width: 15px; height: 15px; }
+.update-component-icon { background-position: -140px -1183px; width: 20px; height: 20px;}
+.update-component-icon:hover { background-position: -170px -1183px; width: 20px; height: 20px;}
/*
.sprite-new.expand-asset-icon { background-position: -740px -590px; width: 40px; height: 40px; }
.sprite-new.view-info-icon { background-position: -739px -621px; width: 40px; height: 40px; }
@images: "images";
/* Colors */
-@color_a: #3b7b9b; // product category
+@color_a: #3b7b9b;
@color_b: #666666;
@color_c: #ffffff;
@color_d: #1d9a95; // dashboard service (S at the top left of the card)
@top_nav_height: 50px;
@top_nav_admin_height: 44px;
@action_nav_height: 53px;
+@tab_title: 110px;
@footer_height: 89px;
@border_color_view-mode: #ededed;
private List<String> resourceTypes;
private List<String> excludeResourceCategory;
+ private List<String> excludeResourceType;
private Map<String, Object> deploymentResourceArtifacts;
private Map<String, Object> deploymentResourceInstanceArtifacts;
private Map<String, Object> toscaArtifacts;
public void setExcludeResourceCategory(List<String> excludeResourceCategory) {
this.excludeResourceCategory = excludeResourceCategory;
}
+
+ public List<String> getExcludeResourceType() {
+ return excludeResourceType;
+ }
+
+ public void setExcludeResourceType(List<String> excludeResourceType) {
+ this.excludeResourceType = excludeResourceType;
+ }
+
public Map<String, Object> getToscaArtifacts() {
return toscaArtifacts;
String host;
Integer port;
String downloadCsarUri;
+ String healthCheckUri;
public String getProtocol() {
return protocol;
this.downloadCsarUri = downloadCsarUri;
}
+ public String getHealthCheckUri() {
+ return healthCheckUri;
+ }
+
+ public void setHealthCheckUri(String healthCheckUri) {
+ this.healthCheckUri = healthCheckUri;
+ }
+
@Override
public String toString() {
return "OnboardingConfig [protocol=" + protocol + ", host=" + host + ", port=" + port + ", downloadCsarUri="
public static final String VF_LICENSE_DESCRIPTION = "VF license file";
public static final String GET_INPUT = "get_input";
public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml";
+ public static final String SERVICE_TEMPLATES_CONTAINING_FOLDER = "Definitions/";
public static final String UNBOUNDED = "unbounded";
}
package org.openecomp.sdc.common.api;
+import java.lang.reflect.Type;
+import java.util.List;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
public class HealthCheckInfo {
private HealthCheckComponent healthCheckComponent;
private HealthCheckStatus healthCheckStatus;
private String version;
private String description;
+ private List<HealthCheckInfo> componentsInfo;
public HealthCheckInfo(HealthCheckComponent healthCheckComponent, HealthCheckStatus healthCheckStatus,
String version, String description) {
this.description = description;
}
+ public HealthCheckInfo(HealthCheckComponent healthCheckComponent, HealthCheckStatus healthCheckStatus,
+ String version, String description, List<HealthCheckInfo> componentsInfo) {
+ super();
+ this.healthCheckComponent = healthCheckComponent;
+ this.healthCheckStatus = healthCheckStatus;
+ this.version = version;
+ this.description = description;
+ this.componentsInfo = componentsInfo;
+ }
+
public HealthCheckInfo() {
super();
}
return healthCheckStatus;
}
+ public List<HealthCheckInfo> getComponentsInfo() {
+ return componentsInfo;
+ }
+
+ public void setComponentsInfo(List<HealthCheckInfo> componentsInfo) {
+ this.componentsInfo = componentsInfo;
+ }
+
public String getVersion() {
return version;
}
}
public enum HealthCheckComponent {
- FE, BE, TITAN, ES, DE;
+ FE, BE, TITAN, DE, ON_BOARDING, CASSANDRA,
+ CAS, ZU;//Amdocs components
}
public enum HealthCheckStatus {
@Override
public String toString() {
return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus="
- + healthCheckStatus + ", version=" + version + ", description=" + description + "]";
+ + healthCheckStatus + ", version=" + version + ", description=" + description + ", componentsInfo="
+ + componentsInfo + "]";
+ }
+
+ public static void main(String[] args) {
+ String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]";
+ Type listType = new TypeToken<List<HealthCheckInfo>>(){}.getType();
+ List<HealthCheckInfo> componentsInfo = new Gson().fromJson(des.toString(), listType);
+ System.out.println(componentsInfo.toString());
}
}
"An Authentication failure occured during access to UEB server. Please check that UEB keys are configured correctly in ASDC BE distribution configuration."), E_199(
"Internal authentication problem. Description: %s"),
- E_200("ASDC Backend probably lost connectivity to either one of the following components: Titan DB, Elasticsearch, UEB Cluster. Please check the logs for more information."), E_201(
+ E_200("ASDC Backend probably lost connectivity to either one of the following components: Titan DB, Cassandra, Onboarding, UEB Cluster. Please check the logs for more information."), E_201(
"ASDC Backend probably lost connectivity to Titan DB. Please check the logs for more information."), E_202(
"ASDC Backend probably lost connectivity to ElasticSearch. Please check the logs for more information."), E_203(
"ASDC Backend probably lost connectivity to UEB Cluster. Please check the logs for more information.",
"Unable to connect to a valid ASDC Backend Server",
"Please check connectivity from this FE instance towards BE or BE Load Balancer. Please check that parameters in FE configuration.yaml: beHost, beHttpPort and beSslPort point to a valid host and port values."),
- E_205("ASDC Backend Recovery to either one of the following components: Titan DB, Elasticsearch, UEB Cluster."), E_206(
+ E_205("ASDC Backend Recovery to either one of the following components: Titan DB, Cassandra, Onboarding, UEB Cluster."), E_206(
"ASDC Backend connection recovery to Titan DB."), E_207(
"ASDC Backend connection recovery to ElasticSearch."), E_208(
"ASDC Backend connection recovery to UEB Cluster."), E_209(
byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
return new String(encodeBase64);
}
+
+
+ /**
+ *
+ * @param String
+ * @return String is null or Empty
+ */
+ public static boolean isEmptyString(String str) {
+ return str == null || str.trim().isEmpty();
+ }
}
public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$");
public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024;
+ public final static Integer SERVICE_TYPE_MAX_LENGTH = 400;
+ public final static Integer SERVICE_ROLE_MAX_LENGTH = 400;
+
public final static Integer TAG_MAX_LENGTH = 1024;
public final static Integer TAG_LIST_MAX_LENGTH = 1024;
- public final static Integer VENDOR_NAME_MAX_LENGTH = 25;
+ public final static Integer VENDOR_NAME_MAX_LENGTH = 60;
public final static Pattern VENDOR_NAME_PATTERN = Pattern
.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25;
public final static Pattern VENDOR_RELEASE_PATTERN = Pattern
.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
+ public final static Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65;
public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+");
return true;
}
- public static boolean validateVendorName(String ventorName) {
- return VENDOR_NAME_PATTERN.matcher(ventorName).matches();
+ public static boolean validateVendorName(String vendorName) {
+ return VENDOR_NAME_PATTERN.matcher(vendorName).matches();
}
- public static boolean validateVendorNameLength(String ventorName) {
- return ventorName.length() <= VENDOR_NAME_MAX_LENGTH;
+ public static boolean validateVendorNameLength(String vendorName) {
+ return vendorName.length() <= VENDOR_NAME_MAX_LENGTH;
}
+ public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) {
+ return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH;
+ }
+
public static boolean validateVendorRelease(String vendorRelease) {
return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches();
}
public static boolean validateVendorReleaseLength(String vendorRelease) {
return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH;
}
+
+ public static boolean validateServiceTypeLength(String serviceType) {
+ return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH;
+ }
+
+ public static boolean validateServiceRoleLength(String serviceRole) {
+ return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH;
+ }
+
+
public static boolean hasBeenCertified(String version) {
return NumberUtils.toDouble(version) >= 1;
String stripped = HtmlCleaner.stripHtml(htmlText, false);
return stripped;
}
-
+
}
@Test
public void validateVendorNameLengthTest() {
assertTrue(ValidationUtils.validateVendorNameLength("fsdlfsdlk.sdsd;"));
- assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddsdfs"));
+ assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsdfs"));
}
@Test
@Test
public void validateVendorReleaseLengthTest() {
- assertTrue(ValidationUtils.validateVendorNameLength("fsdlfsdlk.sdsd;"));
- assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddsdfs"));
+ assertTrue(ValidationUtils.validateVendorReleaseLength("fsdlfsdlk.sdsd;"));
+ assertFalse(ValidationUtils.validateVendorReleaseLength("ddddddddddddddddddddddsdfs"));
}
@Test
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinition implements Serializable {
*
*/
private static final long serialVersionUID = -9114770126086263552L;
-
+ private static final Logger log = LoggerFactory.getLogger(ComponentMetadataDataDefinition.class.getName());
+
private String uniqueId;
private String name; // archiveName
this.lastUpdateDate = other.getLastUpdateDate();
this.description = other.getDescription();
this.state = other.getState();
- this.tags = new ArrayList<String>(other.getTags());
+ this.tags = new ArrayList<>(other.getTags());
this.icon = other.getIcon();
this.contactId = other.getContactId();
this.UUID = other.getUUID();
this.normalizedName = other.getNormalizedName();
this.systemName = other.getSystemName();
- this.allVersions = new HashMap<String, String>(other.getAllVersions());
+ this.allVersions = new HashMap<>(other.getAllVersions());
this.isDeleted = other.isDeleted();
this.projectCode = other.getProjectCode();
this.csarUUID = other.getCsarUUID();
}
public void setUniqueId(String uniqueId) {
+ if ( this.uniqueId != null && !this.uniqueId.equals( uniqueId ) )
+ log.warn("uniqueId changed more then once -> OLD : {} , NEW: {} ", this.uniqueId ,uniqueId );
this.uniqueId = uniqueId;
}
return UUID;
}
- public void setUUID(String uUID) {
- UUID = uUID;
+ public void setUUID(String UUID) {
+ if ( this.UUID != null && !this.UUID.equals( UUID ) )
+ log.warn("UUID changed more then once -> OLD : {} , NEW: {} ", this.UUID, UUID );
+ this.UUID = UUID;
}
public String getNormalizedName() {
}
public void setInvariantUUID(String invariantUUID) {
+ if ( this.invariantUUID != null && !this.invariantUUID.equals( invariantUUID ) )
+ log.warn("InvariantUUID changed more then once -> OLD : {} , NEW: {} ", this.invariantUUID ,invariantUUID );
this.invariantUUID = invariantUUID;
}
private String vendorName;
private String vendorRelease;
+ private String resourceVendorModelNumber;
private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC; // ResourceType.VFC
// is
// default
public ResourceMetadataDataDefinition() {
super();
+ resourceVendorModelNumber = "";
}
public ResourceMetadataDataDefinition(ResourceMetadataDataDefinition other) {
super(other);
this.vendorName = other.getVendorName();
this.vendorRelease = other.getVendorRelease();
+ this.resourceVendorModelNumber = other.getResourceVendorModelNumber();
this.isAbstract = other.isHighestVersion();
this.resourceType = other.getResourceType();
this.toscaResourceName = other.getToscaResourceName();
public void setVendorRelease(String vendorRelease) {
this.vendorRelease = vendorRelease;
}
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
+
public ResourceTypeEnum getResourceType() {
return resourceType;
@Override
public String toString() {
return "ResourceMetadataDataDefinition [vendorName=" + vendorName + ", vendorRelease=" + vendorRelease
- + ", resourceType=" + resourceType + ", isAbstract=" + isAbstract + super.toString() + "]";
+ + ", resourceVendorModelNumber=" + resourceVendorModelNumber + ", resourceType=" + resourceType +
+ ", isAbstract=" + isAbstract + super.toString() + "]";
}
@Override
result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode());
result = prime * result + ((vendorName == null) ? 0 : vendorName.hashCode());
result = prime * result + ((vendorRelease == null) ? 0 : vendorRelease.hashCode());
+ result = prime * result + ((resourceVendorModelNumber == null)? 0 : resourceVendorModelNumber.hashCode());
return result;
}
return false;
} else if (!vendorRelease.equals(other.vendorRelease))
return false;
+ if (resourceVendorModelNumber == null) {
+ if (other.resourceVendorModelNumber != null)
+ return false;
+ } else if (!resourceVendorModelNumber.equals(other.resourceVendorModelNumber))
+ return false;
return super.equals(obj);
}
public static final String EMPTY_STR = "";
private String distributionStatus;
+ private String serviceType;
+ private String serviceRole;
private Boolean ecompGeneratedNaming = true;
public ServiceMetadataDataDefinition() {
super();
+ serviceType = "";
+ serviceRole = "";
}
public ServiceMetadataDataDefinition(ServiceMetadataDataDefinition other) {
super(other);
+ serviceType = other.getServiceType();
+ serviceRole = other.getServiceRole();
}
public String getDistributionStatus() {
public void setDistributionStatus(String distributionStatus) {
this.distributionStatus = distributionStatus;
}
+
+ public String getServiceType(){
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType){
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole(){
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole){
+ this.serviceRole = serviceRole;
+ }
public Boolean isEcompGeneratedNaming() {
return ecompGeneratedNaming;
@Override
public String toString() {
return "ServiceMetadataDataDefinition [ distributionStatus=" + distributionStatus
- + ", ecompGeneratedNaming=" + ecompGeneratedNaming + ", namingPolicy=" + namingPolicy
- + ", parent=" + super.toString() + "]";
+ + ", serviceType=" + serviceType + ", serviceRole=" + serviceRole + ", ecompGeneratedNaming="
+ + ecompGeneratedNaming + ", namingPolicy=" + namingPolicy + ", parent=" + super.toString() + "]";
}
@Override
result = prime * result + ((distributionStatus == null) ? 0 : distributionStatus.hashCode());
result = prime * result + ((ecompGeneratedNaming == null) ? 0 : ecompGeneratedNaming.hashCode());
result = prime * result + ((namingPolicy == null) ? 0 : namingPolicy.hashCode());
+ result = prime * result + ((serviceType == null) ? 0 : serviceType.hashCode());
+ result = prime * result + ((serviceRole == null) ? 0 : serviceRole.hashCode());
return result;
}
return false;
} else if (!namingPolicy.equals(other.namingPolicy))
return false;
+ if (serviceType == null){
+ if (other.serviceType != null)
+ return false;
+ } else if (!serviceType.equals(other.serviceType))
+ return false;
+ if (serviceRole == null){
+ if (other.serviceRole != null)
+ return false;
+ } else if (!serviceRole.equals(other.serviceRole))
+ return false;
return super.equals(obj);
}
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.codehaus.jackson.annotate.JsonCreator;
((ListDataDefinition)other).listToscaDataDefinition = mapByName.values().stream().collect(Collectors.toList());
return other;
}
-
+
+ @Override
+ public boolean findUidMatch(String uid){
+ return listToscaDataDefinition.stream()
+ .anyMatch(p -> p.findUidMatch(uid));
+ }
}
mapToscaDataDefinition.entrySet().forEach(e -> e.getValue().setOwnerIdIfEmpty(ownerId));
}
}
+
+
+ public String findKeyByItemUidMatch(String uid){
+ if(null == mapToscaDataDefinition)
+ return null;
+ Map.Entry<String, T> entry = mapToscaDataDefinition.entrySet().stream().filter(e ->
+ e.getValue().findUidMatch(uid))
+ .findAny().orElse(null);
+ if(null == entry)
+ return null;
+ return entry.getKey();
+ }
}
this.setModificationTime(cdt.getModificationTime());
this.setCapabilityOwnerId(cdt.getCapabilityOwnerId());
this.setRequirementOwnerId(cdt.getRequirementOwnerId());
- this.setCapabiltyId(cdt.getCapabiltyId());
+ this.setCapabilityId(cdt.getCapabilityId());
this.setRequirementId(cdt.getRequirementId());
this.setFromId(cdt.getFromId());
this.setToId(cdt.getToId());
this.setRequirement(cdt.getRequirement());
- this.setCapability(cdt.getCapabilty());
+ this.setCapability(cdt.getCapability());
}
public String getRequirement() {
return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT);
}
- public void setCapability(String capabilty) {
- setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, capabilty);
+ public void setCapability(String capability) {
+ setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, capability);
}
- public String getCapabilty() {
+ public String getCapability() {
return (String) getToscaPresentationValue(JsonPresentationFields.CAPAPILITY);
}
public void setToId(Object toId) {
setToscaPresentationValue(JsonPresentationFields.REQUIREMENT_ID, requirementId);
}
- public void setCapabiltyId(Object capabiltyId) {
- setToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID, capabiltyId);
+ public void setCapabilityId(Object capabilityId) {
+ setToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID, capabilityId);
}
public String getRequirementId() {
return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT_ID);
}
- public String getCapabiltyId() {
+ public String getCapabilityId() {
return (String) getToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID);
}
public int hashCode() {
final int prime = 31;
int result = 1;
- String name = getUniqueId();
+ String name = getName();
String uniqueId = getUniqueId();
String capability = getCapability();
String node = getNode();
return false;
RequirementDataDefinition other = (RequirementDataDefinition) obj;
- String name = getUniqueId();
+ String name = getName();
String uniqueId = getUniqueId();
String capability = getCapability();
String node = getNode();
@Override
public String toString() {
- String name = getUniqueId();
+ String name = getName();
String uniqueId = getUniqueId();
String capability = getCapability();
String node = getNode();
DERIVED_FROM ("derivedFrom", null),
VENDOR_NAME ("vendorName", null),
VENDOR_RELEASE ("vendorRelease", null),
+ RESOURCE_VENDOR_MODEL_NUMBER ("reourceVendorModelNumber",null),
+ SERVICE_TYPE ("serviceType", null),
+ SERVICE_ROLE ("serviceRole", null),
CONFORMANCE_LEVEL ("conformanceLevel", null),
ICON ("icon", null),
TAGS ("tags", null),
VFC("VFC", "VFC (Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE),
CP("CP", "CP (Connection Point)", "resource instance", ComponentTypeEnum.RESOURCE),
VL("VL", "VL (Virtual Link)", "resource instance", ComponentTypeEnum.RESOURCE),
- VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE);
+ VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE),
+ CVFC("CVFC", "CVFC (Complex Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE),
+ PNF("PNF", "PNF (Physical Network Function)", "resource instance", ComponentTypeEnum.RESOURCE);
private String value;
private String displayValue;
*/
public enum ResourceTypeEnum {
- VFC("VFC (Virtual Function Component)"), VF("VF"/* (Virtual Function)" */), CP("CP (Connection Point)"),
- VL( "VL (Virtual Link)"), VFCMT("VFCMT (VFC Monitoring Template)"), ABSTRACT("Abstract (Generic VFC/VF/Service Type)");
+ VFC("VFC (Virtual Function Component)"),
+ VF("VF"/* (Virtual Function)" */),
+ CP("CP (Connection Point)"),
+ PNF("PNF"/* (Physical Network Function)" */),
+ CVFC("CVFC"/*Complex Virtual Function Component*/),
+ VL( "VL (Virtual Link)"),
+ VFCMT("VFCMT (VFC Monitoring Template)"),
+ ABSTRACT("Abstract (Generic VFC/VF/PNF/Service Type)");
private String value;
return false;
}
/**
- * Checks if enum exist with given type ignare case
+ * Checks if enum exist with given type ignore case
* @param type
* @return
*/
return null == dataList? new HashMap<>() : dataList.stream()
.collect(Collectors.toMap(p -> (String)p.getToscaPresentationValue(JsonPresentationFields.NAME), p -> p));
}
+
+ public boolean findUidMatch(String uid){
+ return uid.equals(getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID));
+ }
}
<!-- ==================== -->
<build.type>-SNAPSHOT</build.type>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <sprint.number>73</sprint.number>
+ <sprint.number>74</sprint.number>
<!-- 3rd parties versions -->
<lang3.version>3.3.2</lang3.version>
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
minToscaConformanceLevel: 3.0
titanCfgFile: /var/lib/jetty/config/catalog-be/titan.properties
- { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
host: <%= @host_ip %>
port: <%= @catalog_port %>
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
+minToscaConformanceLevel: 3.0
titanCfgFile: <%= @titan_Path %>/titan.properties
titanInMemoryGraph: false
- { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>','<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
host: <%= @host_ip %>
port: <%= @catalog_port %>
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
minToscaConformanceLevel: 3.0
titanCfgFile: <%= @titan_Path %>/titan.properties
cassandraConfig:
cassandraHosts: [<%= @cassandra_ip %>]
- localDataCenter:
+ localDataCenter: <%= @dc1 %>
reconnectTimeout : 30000
authenticate: true
username: asdc_user
- { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>', '<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>', '<%= @rep_factor %>', '<%= @dc2 %>', '<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
host: <%= @host_ip %>
port: <%= @catalog_port %>
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
+ CVFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
+ PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
// *****************************************ECOMP User
// URL's*****************************************************
- final String ECOMP_PUSH_USER = "http://%s:%s/api/user";
+ final String ECOMP_PUSH_USER = "http://%s:%s/api/v2/user";
- final String ECOMP_EDIT_USER = "http://%s:%s/api/user/%s";
+ final String ECOMP_EDIT_USER = "http://%s:%s/api/v2/user/%s";
- final String ECOMP_GET_USER = "http://%s:%s/api/user/%s";
+ final String ECOMP_GET_USER = "http://%s:%s/api/v2/user/%s";
- final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/users";
+ final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/v2/users";
- final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/roles";
+ final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/v2/roles";
- final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/user/%s/roles";
+ final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/v2/user/%s/roles";
- final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/user/%s/roles";
+ final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/v2/user/%s/roles";
// *****************************************Elements*************************************************************
final String GET_TAGS_LIST = "http://%s:%s/sdc2/rest/v1/tags";
.filter(att -> att.getName().equals("private_address")).findAny().get();
// update attribute on vfc instance
final Resource vfWithInsatncePreUpdate = swallowException(
- () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
+ () -> (Resource) AtomicOperationUtils.getComponentObject(vf, UserRoleEnum.DESIGNER));
ComponentInstanceProperty attributeOfRI = attributeGetter.apply(vfWithInsatncePreUpdate);
final String newAttValue = "NewValue";
attributeOfRI.setValue(newAttValue);
BaseRestUtils.acceptHeaderData));
// Retrieve updated vf and verify attribute was updated
final Resource vfWithInsatncePostUpdate = swallowException(
- () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
+ () -> (Resource) AtomicOperationUtils.getComponentObject(vf, UserRoleEnum.DESIGNER));
ComponentInstanceProperty updatedAttribute = attributeGetter.apply(vfWithInsatncePostUpdate);
assertEquals(updatedAttribute.getValue(), newAttValue);
public class AndreyTest {
+ private static ToscaDefinition parseToscaYamlToJavaObject;
+
+
public static void main(String[] args) throws Exception {
ToscaDefinition toscaDefinition;
System.out.println("start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
// File path = new File("C:/Data/D2.0/TOSCA_Ex/Definitions/tosca_definition_version.yaml");
// File path = new File("C:/Data/D2.0/TOSCA_Ex/resource-Vl11Vl10-template.yml");
- File path = new File("C:/Data/D2.0/TOSCA_Ex/service-Servicepxtc-template US822998.yml");
- File csarPath = new File("C:/Data/D2.0/TOSCA_Ex/Nested.csar");
+// File path = new File("C:/Data/D2.0/TOSCA_Ex/service-Servicepxtc-template US822998.yml");
+// File path = new File("C:/Data/FileToParse/Definitions/service-Ciservice513e6fa67d07-template.yml");
+ toscaDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File("C:/Data/FileToParse/LDSA/LDSA_amdocs.csar"));
+// File path = new File("C:/Data/FileToParse/Definitions/resource-Civfonboarded2016006VvmVvm301607E2100a9b04-template.yml");
+// File csarPath = new File("C:/Data/D2.0/TOSCA_Ex/Nested.csar");
- toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path);
+
+// toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path);
System.out.println("listTypeHeatMetaDefinition start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
- List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarPath);
+// List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarPath);
System.out.println("get service start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
- System.out.println(listTypeHeatMetaDefinition);
- for(TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition){
- for(GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()){
- List<HeatMetaFirstLevelDefinition> artifactList = groupHeatMetaDefinition.getArtifactList();
- boolean isBase = groupHeatMetaDefinition.getPropertyHeatMetaDefinition().getValue();
- }
-
- }
+// System.out.println(listTypeHeatMetaDefinition);
+// for(TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition){
+// for(GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()){
+// List<HeatMetaFirstLevelDefinition> artifactList = groupHeatMetaDefinition.getArtifactList();
+// boolean isBase = groupHeatMetaDefinition.getPropertyHeatMetaDefinition().getValue();
+// }
+//
+// }
System.out.println("Finished");
System.out.println("get service start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
}
assertTrue(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
List<String> getAuthenticateHeader = restResponse.getHeaderFields().get(WWW_AUTHENTICATE);
assertEquals("www-authenticate header contains more then one value", 1, getAuthenticateHeader.size());
- assertTrue(getAuthenticateHeader.get(0).equals("Basic realm=" + "\"ASDC\""));
+ assertTrue(getAuthenticateHeader.get(0).equals("Basic realm=" + "\"SDC\""));
validateAuditAuthentication("", AUTH_REQUIRED, ComponentTypeEnum.SERVICE);
}
importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
- // DE202329
- @Test(enabled = false)
+ // DE202329 - TDP -154379
+ @Test(enabled = true)
public void requirementWithMissingTypeTest() throws Exception {
String fatherName = "father";
String fatherFileName = "DerivedFromWebApplication_HasNoReqType.yml";
ComponentInstance instanceCP2 = AtomicOperationUtils
.addComponentInstanceToComponentContainer(cp2, vf, UserRoleEnum.DESIGNER, true).left().value();
- vf = (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER);
+ vf = (Resource) AtomicOperationUtils.getComponentObject(vf, UserRoleEnum.DESIGNER);
// Create Vertex(Link/Associate 2 Resource Instances on Canvas)
AtomicOperationUtils.associate2ResourceInstances(vf, instanceCP1, instanceVL, AssocType.LINKABLE.getAssocType(),
typeDescription.putMapPropertyType("metadata", String.class, String.class);
// TODO Andrey imports format
typeDescription.putMapPropertyType("imports", String.class, ToscaImportsDefinition.class);
- typeDescription.putListPropertyType("imports", List.class);
+// typeDescription.putListPropertyType("imports", List.class);
typeDescription.putMapPropertyType("node_types", String.class, ToscaNodeTypesDefinition.class);
return typeDescription;
}
--- /dev/null
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+public interface ToscaParameterConstants {
+
+ public static final String ENTRY_DEFINITION = "Entry-Definitions";
+ public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
+ public static final String HEAT_META_PATH = "Artifacts/HEAT.meta";
+ public static final String IMPORT_STRUCTURE = "importStructure";
+}
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition;
import org.openecomp.sdc.ci.tests.datatypes.PropertyHeatMetaDefinition;
import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaParameterConstants;
import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CsarParserUtils {
private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName());
- public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(File csarUUID) throws Exception {
-
- String artifactHeatMetaLocation = "Artifacts/HEAT.meta";
- JSONParser parser = new JSONParser();
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, artifactHeatMetaLocation);
- if (csarPayload != null) {
- Object parse = parser.parse(csarPayload);
- JSONObject jsonObject = (JSONObject) parse;
- JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure");
- List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
- listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
- return listHeatMetaDefenition;
- }
- return null;
+ public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(File csarFileLocation) throws Exception {
+ String artifactHeatMetaLocation = ToscaParameterConstants.HEAT_META_PATH;
+ String csarPayload = ToscaParserUtils.getYamlPayloadFromCsar(csarFileLocation, artifactHeatMetaLocation);
+ return getListTypeHeatMetaDefinitionByPayload(csarPayload);
}
-
+
public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(String csarUUID) throws Exception {
+
+ String artifactHeatMetaLocation = ToscaParameterConstants.HEAT_META_PATH;
+ String csarPayload = ToscaParserUtils.getCsarPayload(csarUUID, artifactHeatMetaLocation);
+ return getListTypeHeatMetaDefinitionByPayload(csarPayload);
+ }
- String artifactHeatMetaLocation = "Artifacts/HEAT.meta";
+ public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinitionByPayload(String csarPayload) throws ParseException {
JSONParser parser = new JSONParser();
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, artifactHeatMetaLocation);
if (csarPayload != null) {
Object parse = parser.parse(csarPayload);
JSONObject jsonObject = (JSONObject) parse;
- JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure");
+ JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get(ToscaParameterConstants.IMPORT_STRUCTURE);
List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
return listHeatMetaDefenition;
}
return null;
-
}
+
protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure, List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
@SuppressWarnings("unchecked")
package org.openecomp.sdc.ci.tests.utils;
import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.FileInputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaParameterConstants;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaSubstitutionMappingsDefinition;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
+import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
+import org.openecomp.sdc.common.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.TypeDescription;
private static Logger log = LoggerFactory.getLogger(ToscaParserUtils.class.getName());
- public static ToscaDefinition parseToscaYamlToJavaObject(String csarUUID) throws Exception {
+
+ /**method get csarUUID and send GET API request toward BE
+ * @param csarUUID
+ * @return
+ * @throws Exception
+ */
+ public static ToscaDefinition parseToscaYamlToJavaObjectByCsarUuid(String csarUUID) throws Exception {
ToscaDefinition toscaDefinition = null;
- String TOSCAMetaLocation = "TOSCA-Metadata/TOSCA.meta";
+ String TOSCAMetaLocation = ToscaParameterConstants.TOSCA_META_PATH;
Map<?, ?> map = getToscaYamlMap(csarUUID, TOSCAMetaLocation);
assertNotNull("Tosca Entry-Definitions is null", map);
if (map != null) {
- File definitionYamlLocation = (File) map.get("Entry-Definitions");
+ File definitionYamlLocation = (File) map.get(ToscaParameterConstants.ENTRY_DEFINITION);
toscaDefinition = parseToscaYamlToJavaObject(definitionYamlLocation);
}
return toscaDefinition;
}
+ /**method read csar from location
+ * @param csarNameLocation - full path with csar name
+ * @return
+ * @throws Exception
+ */
+ public static ToscaDefinition parseToscaMainYamlToJavaObjectByCsarLocation(File csarNameLocation) throws Exception {
+
+ ToscaDefinition toscaDefinition = null;
+ String TOSCAMetaLocation = ToscaParameterConstants.TOSCA_META_PATH;
+// read file location of main yaml file(location+name) from TOSCA.meta file by
+ Map<?, ?> map = getToscaYamlMap(csarNameLocation, TOSCAMetaLocation);
+
+ assertNotNull("Tosca Entry-Definitions is null", map);
+
+ String definitionYamlLocation = (String) map.get(ToscaParameterConstants.ENTRY_DEFINITION);
+ String csarPayload = getYamlPayloadFromCsar(csarNameLocation, definitionYamlLocation);
+ toscaDefinition = parseToscaYamlPayloadToJavaObject(csarPayload);
+ return toscaDefinition;
+
+ }
+
+ public static ToscaDefinition parseToscaAnyYamlToJavaObjectByCsarLocation(File csarNameLocation, String yamlLocation) throws Exception {
+
+ ToscaDefinition toscaDefinition = null;
+ String csarPayload = getYamlPayloadFromCsar(csarNameLocation, yamlLocation);
+ toscaDefinition = parseToscaYamlPayloadToJavaObject(csarPayload);
+ return toscaDefinition;
+
+ }
+
public static ToscaDefinition parseToscaYamlToJavaObject(File path) throws Exception {
ToscaDefinition toscaDefinition = null;
System.out.println("Exception: " + e);
}
- Constructor constructor = getConstructor();
+ Constructor constructor = initToscaDefinitionObject();
Yaml yaml = new Yaml(constructor);
try {
public static ToscaDefinition parseToscaYamlPayloadToJavaObject(String payload){
ToscaDefinition toscaDefinition = null;
- Constructor constructor = getConstructor();
+ Constructor constructor = initToscaDefinitionObject();
Yaml yaml = new Yaml(constructor);
try {
}
- public static Constructor getConstructor() {
- Constructor constructor = new Constructor(ToscaDefinition.class);
- constructor.addTypeDescription(ToscaDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaTopologyTemplateDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaNodeTemplatesTopologyTemplateDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaGroupsTopologyTemplateDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaSubstitutionMappingsDefinition.getTypeDescription());
+ public static Constructor initToscaDefinitionObject() {
+ Constructor toscaStructure = new Constructor(ToscaDefinition.class);
+ toscaStructure.addTypeDescription(ToscaDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaTopologyTemplateDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaNodeTemplatesTopologyTemplateDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaGroupsTopologyTemplateDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaSubstitutionMappingsDefinition.getTypeDescription());
// Skip properties which are found in YAML, but not found in POJO
PropertyUtils propertyUtils = new PropertyUtils();
propertyUtils.setSkipMissingProperties(true);
- constructor.setPropertyUtils(propertyUtils);
- return constructor;
+ toscaStructure.setPropertyUtils(propertyUtils);
+ return toscaStructure;
}
- public static Map<?, ?> getToscaYamlMap(String csarUUID, String fileLocation) throws Exception {
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation);
+ public static Map<?, ?> getToscaYamlMap(String csarUUID, String yamlFileLocation) throws Exception {
+ String csarPayload = getCsarPayload(csarUUID, yamlFileLocation);
+ if (csarPayload != null) {
+ Yaml yaml = new Yaml();
+ Map<?, ?> map = (Map<?, ?>) yaml.load(csarPayload);
+ return map;
+ }
+ return null;
+ }
+
+ public static Map<?, ?> getToscaYamlMap(File csarPath, String yamlFileLocation) throws Exception {
+ String csarPayload = getYamlPayloadFromCsar(csarPath, yamlFileLocation);
if (csarPayload != null) {
Yaml yaml = new Yaml();
Map<?, ?> map = (Map<?, ?>) yaml.load(csarPayload);
return null;
}
+
+ public static String getCsarPayload(String csarName, String yamlFileLocation) throws Exception {
+
+ RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ byte[] data = csar.getResponse();
+ return getDataFromZipFileByBytes(yamlFileLocation, data);
+
+ }
+
+ public static String getYamlPayloadFromCsar(File csarName, String fileLocation) throws Exception {
+
+ Path path = csarName.toPath();
+ byte[] data = Files.readAllBytes(path);
+ return getDataFromZipFileByBytes(fileLocation, data);
+
+ }
+
+ /** method get file data from zip data by file location in the zip structure
+ * @param fileLocation
+ * @param data
+ * @return
+ */
+ public static String getDataFromZipFileByBytes(String fileLocation, byte[] data) {
+ Map<String, byte[]> readZip = null;
+ if (data != null && data.length > 0) {
+ readZip = ZipUtil.readZip(data);
+
+ }
+ byte[] artifactsBs = readZip.get(fileLocation);
+ String str = new String(artifactsBs, StandardCharsets.UTF_8);
+ return str;
+ }
/* public static Map<?, ?> getToscaYamlMap(String csarUUID, String fileLocation) throws Exception {
String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation);
if (csarPayload != null) {
LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
if (curentCompState == targetState) {
- component = getCompoenntObject(component, userRole);
+ component = getComponentObject(component, userRole);
return Pair.of(component, null);
}
// List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
}
}
- Component componentJavaObject = getCompoenntObject(component, userRole);
+ Component componentJavaObject = getComponentObject(component, userRole);
if (validateState == true && isValidationFailed == true) {
assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false);
Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
return container;
}
+
+ public static Service getServiceObject(String uniqueId) throws Exception {
+ RestResponse serviceResponse = ServiceRestUtils.getService(uniqueId);
+ Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
+ return container;
+ }
public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
User defaultUser = ElementFactory.getDefaultUser(userRole);
return container;
}
- public static Component getCompoenntObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
+ public static Component getComponentObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
User defaultUser = ElementFactory.getDefaultUser(userRole);
switch (containerDetails.getComponentType()) {
if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
- Component compoenntObject = AtomicOperationUtils.getCompoenntObject(containerDetails, userRole);
+ Component compoenntObject = AtomicOperationUtils.getComponentObject(containerDetails, userRole);
ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse());
return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject));
package org.openecomp.sdc.ci.tests.utils.rest;
import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
Config config = Utils.getConfig();
String url = String.format(Urls.CHANGE_COMPONENT_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
- component.getUniqueId(), LifeCycleStatesEnum);
- RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT),
- sdncModifierDetails.getUserId(), acceptHeaderData);
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), LifeCycleStatesEnum);
+ RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), sdncModifierDetails.getUserId(), acceptHeaderData);
if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String productUniqueId = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
+ String productUniqueId = ResponseParser.getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
component.setUniqueId(productUniqueId);
- String productVersion = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
+ String productVersion = ResponseParser.getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
component.setVersion(productVersion);
- String newLifecycleState = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
+ String newLifecycleState = ResponseParser.getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
component.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState));
}
return LifeCycleStatesEnumServiceResponse;
import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.google.gson.Gson;
}
public static RestResponse createService(ServiceReqDetails service, User user) throws Exception {
+
Config config = Utils.getConfig();
String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort());
String serviceBodyJson = gson.toJson(service);
config.getCatalogBePort(), serviceName, serviceVersion);
RestResponse deleteResponse = http.httpSendDelete(url, headersMap);
+ deleteMarkedServices(sdncModifierDetails.getUserId());
return deleteResponse;
}
public class CsarValidationUtils {
- public static String getCsarPayload(String csarName, String fileLocation) throws Exception {
-
- RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- Map<String, byte[]> readZip = null;
- byte[] data = csar.getResponse();
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
-
- }
- byte[] artifactsBs = readZip.get(fileLocation);
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
- return str;
-
- }
-
- public static String getCsarPayload(File csarName, String fileLocation) throws Exception {
-
-// RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
-// assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- Map<String, byte[]> readZip = null;
- Path path = csarName.toPath();
-
- byte[] data = Files.readAllBytes(path);
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
- }
- byte[] artifactsBs = readZip.get(fileLocation);
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
- return str;
-
- }
-
public static void validateCsarVfArtifact(String csarUUID, Resource resource) throws Exception {
List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarUUID);
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.DistributionValidationUtils;
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
component = getComponentWithResourceInstanceInTargetLifeCycleState(chosenLifeCycleState, resourceTypeEnum);
-
restResponse = uploadArtifactOfRIIncludingValiditionOfAuditAndResponseCode(component, component.getComponentInstances().get(0), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200);
- component =AtomicOperationUtils.getCompoenntObject(component, UserRoleEnum.DESIGNER);
-
- if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == chosenLifeCycleState) && (!component.getComponentType().toString().equals(ComponentTypeEnum.RESOURCE.toString()))) {
-// numberOfArtifact = component.getComponentInstances().get(0).getDeploymentArtifacts().size();
- numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size());
- } else {
-// numberOfArtifact = component.getComponentInstances().get(0).getDeploymentArtifacts().size() + 1;
- numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size());
- }
+ component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+ numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size());
} else {
component = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, chosenLifeCycleState, resourceTypeEnum);
-
restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200);
- numberOfArtifact = component.getDeploymentArtifacts().size() + 1;
+ component = updateComponentDetailsByLifeCycleState(chosenLifeCycleState, component);
+ numberOfArtifact = component.getDeploymentArtifacts().size();
}
-
-
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
- component = getNewerVersionOfComponent(component, chosenLifeCycleState);
-
// Get list of deployment artifact + download them via external API
Map<String, ArtifactDefinition> deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
- Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact will be increase by one.");
+ Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifacts will be increase by one.");
// Download the uploaded artifact via external API
downloadResourceDeploymentArtifactExternalAPI(component, deploymentArtifacts.get(responseArtifact.getArtifactLabel()), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentTypeEnum);
-
+ return component;
+ }
+
+ /**
+ * according lifecycle state of component get updated component details
+ * @param chosenLifeCycleState
+ * @param component
+ * @return
+ * @throws Exception
+ */
+ public Component updateComponentDetailsByLifeCycleState(LifeCycleStatesEnum chosenLifeCycleState, Component component) throws Exception {
+ if(LifeCycleStatesEnum.CHECKOUT.equals(chosenLifeCycleState)){
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
+ }else{
+ component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+ }
return component;
}
// Upload artifact via external API + Check auditing for upload operation + Check response of external API
- public RestResponse uploadArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, resourceDetails.getComponentInstances().get(0));
+ public RestResponse uploadArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component component, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, component.getComponentInstances().get(0));
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
return restResponse;
}
-
-
protected Component getComponentWithResourceInstanceInTargetLifeCycleState(LifeCycleStatesEnum lifeCycleStatesEnum, ResourceTypeEnum resourceTypeEnum) throws Exception {
Component component;
if(resourceTypeEnum == ResourceTypeEnum.VF) {
Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, null);
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value();
- // Add artifact to service if asked for certifcationrequest - must be at least one artifact for the flow
- if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == lifeCycleStatesEnum) || (LifeCycleStatesEnum.STARTCERTIFICATION == lifeCycleStatesEnum)) {
- }
+ // Add artifact to service if asked for certification request - must be at least one artifact for the flow
+// if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == lifeCycleStatesEnum) || (LifeCycleStatesEnum.STARTCERTIFICATION == lifeCycleStatesEnum)) {
+// }
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, component, UserRoleEnum.DESIGNER, true, true).left().value();
component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, lifeCycleStatesEnum, true).getLeft();
} else {
// Upload artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails);
+ protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
return restResponse;
// check that this version different for input version
// check that this component uniqueID different from input uniqueID
// Return: that version
- protected Component getNewerVersionOfComponent(Component component, LifeCycleStatesEnum lifeCycleStatesEnum) throws Exception {
+ protected synchronized Component getNewerVersionOfComponent(Component component, LifeCycleStatesEnum lifeCycleStatesEnum) throws Exception {
Component resourceDetails = null;
if((!lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKOUT)) && (!lifeCycleStatesEnum.equals(LifeCycleStatesEnum.STARTCERTIFICATION))) {
System.out.println("Service UniqueID: " + resourceDetails.getUniqueId());
// Checking that new version exist + different from old one by unique id
- Assert.assertNotEquals(resourceVersion, resourceNewVersion, "Expected for diffrent resource version.");
+ Assert.assertNotEquals(resourceVersion, resourceNewVersion, "Expected for different resource version.");
Assert.assertNotEquals(resourceUniqueID, resourceNewUniqueID, "Expected that resource will have new unique ID.");
} else {
if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
// download deployment via external api + check response code for success (200) + get artifactReqDetails and verify payload + verify audit
- protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component resourceDetails, ArtifactDefinition artifactDefinition, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, ComponentTypeEnum componentTypeEnum) throws Exception {
+ protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component component, ArtifactDefinition artifactDefinition, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, ComponentTypeEnum componentTypeEnum) throws Exception {
RestResponse restResponse;
if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
- restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(component.getUUID(), component.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
} else {
- restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(component.getUUID(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
}
Integer responseCode = restResponse.getErrorCode();
Assert.assertEquals(responseCode,expectedCode, "Response code is not correct.");
- // For known artifact/payload - verify payload of downloaded artfaict
+ // For known artifact/payload - verify payload of downloaded artifact
if (artifactReqDetails != null) {
String response = restResponse.getResponse();
String payloadData = artifactReqDetails.getPayload();
}
// download deployment via external api + check response code for success (200) + verify audit
- protected void downloadResourceDeploymentArtifactExternalAPI(Component resourceDetails, ArtifactDefinition artifactDefinition, User sdncModifierDetails) throws Exception {
- downloadResourceDeploymentArtifactExternalAPI(resourceDetails, artifactDefinition, sdncModifierDetails, null, resourceDetails.getComponentType());
+ protected void downloadResourceDeploymentArtifactExternalAPI(Component component, ArtifactDefinition artifactDefinition, User sdncModifierDetails) throws Exception {
+ downloadResourceDeploymentArtifactExternalAPI(component, artifactDefinition, sdncModifierDetails, null, component.getComponentType());
}
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
-// DE306360 {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+ {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
-// DE306360 {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+ {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
-// DE306360 {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidCheckSum"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidCheckSum"},
}
// Upload artifact with invalid type via external API - to long type
- protected void uploadArtifactWithInvalidTypeToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidTypeToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
artifactReqDetails.setArtifactType("dsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfds");
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
List<String> variables = asList(artifactReqDetails.getArtifactType());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid type via external API - empty type
- protected void uploadArtifactWithInvalidTypeEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidTypeEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
artifactReqDetails.setArtifactType("");
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
List<String> variables = asList(artifactReqDetails.getArtifactType());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid checksum via external API
- protected void uploadArtifactWithInvalidCheckSum(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidCheckSum(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_INVALID_MD5.name());
List<String> variables = asList();
- uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables);
}
// Upload artifact with valid type & invalid name via external API - name to long
- protected void uploadArtifactWithInvalidNameToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidNameToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact name", "255");
artifactReqDetails.setArtifactName("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with valid type & invalid name via external API - name is empty
- protected void uploadArtifactWithInvalidNameEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidNameEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_ARTIFACT_NAME.name());
List<String> variables = asList();
artifactReqDetails.setArtifactName("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with valid type & invalid label via external API - label to long
- protected void uploadArtifactWithInvalidLabelToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidLabelToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact label", "255");
artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with valid type & invalid label via external API - label is empty
- protected void uploadArtifactWithInvalidLabelEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidLabelEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
List<String> variables = asList("artifact label");
artifactReqDetails.setArtifactLabel("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid description via external API - to long description
- protected void uploadArtifactWithInvalidDescriptionToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidDescriptionToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact description", "256");
artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid description via external API - empty description
- protected void uploadArtifactWithInvalidDescriptionEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidDescriptionEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
List<String> variables = asList("artifact description");
artifactReqDetails.setDescription("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with same label via external API
- protected void uploadArtifactWithSameLabel(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithSameLabel(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
RestResponse restResponse = null;
if(componentResourceInstanceDetails != null) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
} else {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
}
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_EXIST.name());
List<String> variables = asList(artifactDefinition.getArtifactDisplayName());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
- protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean includeResourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentResourceInstanceDetails != null) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, componentResourceInstanceDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, sdncModifierDetails, artifactReqDetails, componentResourceInstanceDetails);
} else {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails);
}
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA(null);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
if(includeResourceNameInAudit) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
if((lifeCycleStatesEnum == LifeCycleStatesEnum.CHECKIN) || (lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
expectedExternalAudit.setRESOURCE_NAME("");
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
} else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
}
}
- protected RestResponse uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected RestResponse uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables) throws Exception {
RestResponse restResponse;
if(componentResourceInstanceDetails != null) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
} else {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
}
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA(null);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
};
}
-
// Verify that it cannot update VFC/VL/CP artifact on VFCi/VLi/CPi - Failure flow
@Test(dataProvider="updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI")
public void updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI(ResourceTypeEnum resourceTypeEnum) throws Exception {
}
-
-
-
-
@DataProvider(name="updateArtifactOnRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnRIViaExternalAPI() {
return new Object[][] {
};
}
-
-
-
-
@Test(dataProvider="updateArtifactOnRIViaExternalAPI")
public void updateArtifactOnRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception {
getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
}
}
-
-
-
-
-
-
@DataProvider(name="updateArtifactOnVfcVlCpRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVfcVlCpRIViaExternalAPI() {
return new Object[][] {
};
}
-
-
-
-
@Test(dataProvider="updateArtifactOnVfcVlCpRIViaExternalAPI")
public void updateArtifactOnVfcVlCpRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception {
getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
}
}
-
-
-
-
-
-
-
-
-
@DataProvider(name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() {
return new Object[][] {
};
}
-
-
// External API
// Update artifact by diffrent user then creator of asset - Fail
@Test(dataProvider="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
};
}
-
-
// External API
// Upload artifact on VF via external API - happy flow
@Test(dataProvider="updateArtifactOnAssetWhichNotExist")
};
}
-
@Test(dataProvider="updateArtifactOnAssetWhichInInvalidStateForUploading")
public void updateArtifactOnAssetWhichInInvalidStateForUploading(ComponentTypeEnum componentTypeEnum, String artifactType) throws Exception {
getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType));
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
-
-
-
-
-
-
-
// Unhappy flow - get chosen life cycle state, artifact type and asset type
// update artifact via external API + check audit & response code
return component;
}
- protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails,
+ protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails,
Integer expectedResponseCode, ComponentInstance componentInstance, ArtifactReqDetails artifactReqDetails, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentInstance != null) {
- restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, componentInstance, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(component, sdncModifierDetails, artifactReqDetails, componentInstance, artifactUUID);
} else {
- restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails, artifactUUID);
}
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA("");
expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
if((lifeCycleStatesEnum == LifeCycleStatesEnum.CHECKIN) || (lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
if(resourceNameInAudit) {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
// body.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
expectedExternalAudit.setRESOURCE_NAME("");
}
} else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
}
return downloadResourceDeploymentArtifactExternalAPI(component, component.getDeploymentArtifacts().get(artifactName), sdncModifierDetails, artifactReqDetails, componentTypeEnum);
}
- // Get deployment artifact of asset
+ // Get deployment artifact of RI
protected Map<String, ArtifactDefinition> getDeploymentArtifactsOfAsset(Component component, ComponentTypeEnum componentTypeEnum) {
Map<String, ArtifactDefinition> deploymentArtifacts = null;
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
numberOfArtifact = deploymentArtifacts.size();
-
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
- if((chosenLifeCycleState == LifeCycleStatesEnum.CERTIFICATIONREQUEST) && (!component.getComponentType().toString().equals(ComponentTypeEnum.RESOURCE.toString()))) {
- numberOfArtifact = numberOfArtifact - 1;
- }
restResponse = updateArtifactOfRIIncludingValiditionOfAuditAndResponseCode(component, component.getComponentInstances().get(0), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID, 200);
} else {
-
restResponse = updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID, 200);
}
-
-
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
component = getNewerVersionOfComponent(component, chosenLifeCycleState);
// Update artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse updateArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, resourceDetails.getComponentInstances().get(0), artifactUUID);
+ protected RestResponse updateArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component component, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, component.getComponentInstances().get(0), artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
return restResponse;
// Update artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID);
+ protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
};
}
-
-
-
// Delete artifact for Service - Success
@Test(dataProvider="deleteArtifactForServiceViaExternalAPI")
public void deleteArtifactForServiceViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
// External API
- // Delete artifact by diffrent user then creator of asset - Fail
+ // Delete artifact by different user then creator of asset - Fail
@Test(dataProvider="deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
public void deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset(ComponentTypeEnum componentTypeEnum, UserRoleEnum userRoleEnum, LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, userRoleEnum %s, lifeCycleStatesEnum %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType));
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- 409, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- 409, null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
+ errorInfo.getCode(), null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
}
//TODO
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, invalidArtifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, invalidArtifactUUID, errorInfo, variables, null, true);
}
errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER.name());
variables = asList("invalidNormalizedName", ComponentTypeEnum.RESOURCE_INSTANCE.getValue().toLowerCase(), ComponentTypeEnum.SERVICE.getValue(), component.getName());
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
} else {
component.setUUID("invalidComponentUUID");
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) {
}
variables = asList("invalidComponentUUID");
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
+ errorInfo.getCode(), null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
}
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 403, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 403, null, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactUUID, errorInfo, variables, null, true);
}
}
List<String> variables = asList(artifactUUID);
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
}
- protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails,
+ protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails,
Integer expectedResponseCode, ComponentInstance componentInstance, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentInstance != null) {
- restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, componentInstance, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(component, sdncModifierDetails, componentInstance, artifactUUID);
} else {
- restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(component, sdncModifierDetails, artifactUUID);
}
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA(null);
expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
if((errorInfo.getMessageId().equals(ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()).getMessageId())) ||
errorInfo.getMessageId().equals(ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()).getMessageId()) ||
(lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
if(resourceNameInAudit) {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
expectedExternalAudit.setRESOURCE_NAME("");
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
}
} else {
if(resourceNameInAudit) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
expectedExternalAudit.setRESOURCE_NAME("");
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
protected Component deleteArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState) throws Exception {
String artifactName = null;
component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, chosenLifeCycleState, true).getLeft();
-
+ if(!LifeCycleStatesEnum.CHECKOUT.equals(chosenLifeCycleState)){
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
+ }else{
+ component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+ }
// get updated artifact data
String artifactUUID = null;
int moduleTypeArtifact = 0;
break;
}
}
-
String componentVersionBeforeDelete = component.getVersion();
int numberOfArtifact = deploymentArtifacts.size();
-
-
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, 200);
}
-
- component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+
+ component = updateComponentDetailsByLifeCycleState(chosenLifeCycleState, component);
// Get list of deployment artifact + download them via external API
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
} else {
Assert.assertEquals(numberOfArtifact - 1, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact will decrease by one.");
}
-
if(chosenLifeCycleState == LifeCycleStatesEnum.CHECKOUT) {
Assert.assertEquals(componentVersionBeforeDelete, component.getVersion(), "Expected that check-out component will not change version number.");
}
// Delete artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse deleteArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, ComponentInstance componentInstance, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentInstances().get(0), artifactUUID);
+ protected RestResponse deleteArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component component, ComponentInstance componentInstance, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentInstances().get(0), artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
-
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
return restResponse;
}
// Delete artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID);
+ protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
-
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
return restResponse;
}
// download deployment via external api + check response code for success (200) + get artifactReqDetails and verify payload + verify audit
- protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component resourceDetails, User sdncModifierDetails, String artifactUUID, ComponentTypeEnum componentTypeEnum) throws Exception {
+ protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component component, User sdncModifierDetails, String artifactUUID, ComponentTypeEnum componentTypeEnum) throws Exception {
RestResponse restResponse;
if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
- restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(component.getUUID(), component.getComponentInstances().get(0).getNormalizedName(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
} else {
- restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(component.getUUID(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
}
Integer responseCode = restResponse.getErrorCode();
package org.openecomp.sdc.externalApis;
-import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.IOUtils;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Rule;
import org.junit.rules.TestName;
-import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
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.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import static org.testng.AssertJUnit.assertTrue;
-
-import com.google.gson.Gson;
-
-import fj.data.Either;
public class GetCSARofVF extends ComponentBaseTest {
}
-
-
-
-
+ /**
+ * all files in list(expectedDefinitionFolderFileList) must be found in csar file
+ * @param resource
+ * @param toscaModelCsarFile
+ * @throws ZipException
+ * @throws IOException
+ */
public void validateCsarContent(Component resource, File toscaModelCsarFile) throws ZipException, IOException {
ZipFile zipFile = new ZipFile(toscaModelCsarFile);
+ List<String> expectedDefinitionFolderFileList = new ArrayList<String>();
+ expectedDefinitionFolderFileList.add("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template.yml");
+ expectedDefinitionFolderFileList.add("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template-interface.yml");
+ expectedDefinitionFolderFileList.add("Definitions/relationships.yml");
+ expectedDefinitionFolderFileList.add("Definitions/policies.yml");
+ expectedDefinitionFolderFileList.add("Definitions/nodes.yml");
+ expectedDefinitionFolderFileList.add("Definitions/interfaces.yml");
+ expectedDefinitionFolderFileList.add("Definitions/groups.yml");
+ expectedDefinitionFolderFileList.add("Definitions/data.yml");
+ expectedDefinitionFolderFileList.add("Definitions/capabilities.yml");
+ expectedDefinitionFolderFileList.add("Definitions/artifacts.yml");
+
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry nextElement = entries.nextElement();
if (!(nextElement.getName().contains("Artifacts")||nextElement.getName().contains("csar.meta"))){
- assertTrue("missing file in csar template", (nextElement.getName().equals("TOSCA-Metadata/TOSCA.meta") ||
- nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template.yml")) ||
- nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template-interface.yml"));
+// assertTrue("missing file in csar template", (nextElement.getName().equals("TOSCA-Metadata/TOSCA.meta") ||
+// nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template.yml")) ||
+// nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template-interface.yml"));
+ if(expectedDefinitionFolderFileList.contains(nextElement.getName())){
+ expectedDefinitionFolderFileList.remove(nextElement.getName());
}
}
+ }
+ zipFile.close();
+ assertTrue("missing files in csar template definitions folder", expectedDefinitionFolderFileList.size() == 0);
}
public void validateAudit(Component resource) throws Exception {
// Various failure flows
@Test(dataProvider="createVfcmtVariousFailureFlows")
public void createVfcmtVariousFailureFlows(String flow) throws Exception {
-
+ //TODO: check what happens now, test will prbably fail
if(flow.equals("resource_type_missing") || flow.equals("resource_type_invalid")) {
throw new SkipException("TC require repairs");
- }
+ }
User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
case "description_with_invalid_char":
defaultResource.setDescription("\uC2B5");
expectedResourceAuditJavaObject.setDesc("t");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_TYPE.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
// TODO: defect on the flow - need to get error instead create VFC
case "resource_type_missing":
defaultResource.setResourceType("");
expectedResourceAuditJavaObject.setResourceType("");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
// TODO: in audit RESOURCE_NAME is empty
case "resource_type_invalid":
defaultResource.setResourceType("invalid");
expectedResourceAuditJavaObject.setResourceType(ComponentTypeEnum.RESOURCE.getValue());
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_TYPE.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
case "category_type_missing":
// create vfcmt
RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser);
- expectedResourceAuditJavaObject.setStatus("400");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);
outputFolder: target
reportName: index.html
-catalogBeHost: behost
+catalogBeHost: localhost
catalogFeHost: fehost
esHost: eshost
disributionClientHost: disClient
message: "Creation of %1 failed. Generic type %2 was not found",
messageId: "SVC4660"
}
+ #---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ }
\ No newline at end of file
setLog("mibsArtifactCRUDUi");
String filePath = FileHandling.getFilePath(folder);
- if(true){
- throw new SkipException("Open bug 197101");
- }
-
// import Resource
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser());
ResourceUIUtils.importVfc(resourceMetaData, filePath, fileName, getUser());
}
public enum StepsEnum {
- GENERAL("Generalstep"),
+ GENERAL("General"),
ICON("Iconstep"),
- DEPLOYMENT_ARTIFACT("Deployment Artifactstep"),
- INFORMATION_ARTIFACT("Information Artifactstep"),
- PROPERTIES("Propertiesstep"),
- COMPOSITION("Compositionstep"),
- ACTIVITY_LOG("Activity Logstep"),
- DEPLOYMENT_VIEW("Deploymentstep"),
- TOSCA_ARTIFACTS("TOSCA Artifactsstep"),
+ DEPLOYMENT_ARTIFACT("Deployment Artifact"),
+ INFORMATION_ARTIFACT("Information Artifact"),
+ PROPERTIES("Properties"),
+ COMPOSITION("Composition"),
+ ACTIVITY_LOG("Activity Log"),
+ DEPLOYMENT_VIEW("Deployment"),
+ TOSCA_ARTIFACTS("TOSCA Artifacts"),
MONITOR("Monitor step"),
- MANAGEMENT_WORKFLOW("Management Workflowstep"),
- INPUTS("Inputsstep"),
- HIERARCHY("Hierarchystep");
+ MANAGEMENT_WORKFLOW("Management Workflow"),
+ INPUTS("Inputs"),
+ HIERARCHY("Hierarchy");
private String value;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Random;
import java.util.stream.Collectors;
import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
return provideData(fileNamesFromFolder, filepath);
}
+
+ @DataProvider(name = "randomVNF_List", parallel = false)
+ private static final Object[][] randomVnfList() throws Exception {
+ int randomElementNumber = 3; //how many VNFs to onboard randomly
+ String filepath = getFilePath();
+ Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ Object[] newRandomFileNamesFromFolder = getRandomElements(randomElementNumber, fileNamesFromFolder);
+ System.out.println(String.format("There are %s zip file(s) to test", newRandomFileNamesFromFolder.length));
+ return provideData(newRandomFileNamesFromFolder, filepath);
+ }
+
+
+ private static Object[] getRandomElements(int randomElementNumber, Object[] fileNamesFromFolder) {
+ if(fileNamesFromFolder.length == 0 || fileNamesFromFolder.length < randomElementNumber){
+ return null;
+ }else{
+ List<Integer> indexList = new ArrayList<>();
+ Object[] newRandomFileNamesFromFolder = new Object[randomElementNumber];
+ for(int i = 0; i < fileNamesFromFolder.length; i++){
+ indexList.add(i);
+ }
+ Collections.shuffle(indexList);
+ Integer[] randomArray = indexList.subList(0, randomElementNumber).toArray(new Integer[randomElementNumber]);
+ for(int i = 0; i < randomArray.length; i++){
+ newRandomFileNamesFromFolder[i] = fileNamesFromFolder[randomArray[i]];
+ }
+ return newRandomFileNamesFromFolder;
+ }
+ }
+
public static String getFilePath() {
String filepath = System.getProperty("filepath");
if (filepath == null && System.getProperty("os.name").contains("Windows")) {
runOnboardToDistributionFlow(filepath, vnfFile);
}
+
public void runOnboardToDistributionFlow(String filepath, String vnfFile) throws Exception, AWTException {
Pair<String,Map<String,String>> onboardAndValidate = OnboardingUtils.onboardAndValidate(filepath, vnfFile, getUser());
String vspName = onboardAndValidate.left;
runOnboardToDistributionFlow(filepath, vnfFile);
}
+ @Test(dataProvider = "randomVNF_List")
+ public void onboardRandomVNFsTest(String filepath, String vnfFile) throws Exception, Throwable {
+ setLog(vnfFile);
+ System.out.println("printttttttttttttt - >" + makeDistributionValue);
+ System.out.println("vnf File name is: " + vnfFile);
+ runOnboardToDistributionFlow(filepath, vnfFile);
+ }
+
@Test
public void onboardUpdateVNFTest() throws Exception, Throwable {
import java.awt.AWTException;
import java.io.File;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.ArrayList;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.openecomp.sdc.toscaparser.api.common.JToscaException;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
}
+
+ @Test
+ public void onboardingAndParser() throws Exception {
+ Service service = null;
+ String filepath = getFilePath();
+ Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ String vnfFile = fileNamesFromFolder[7].toString();
+ System.err.println(timestamp + " Starting test with VNF: " + vnfFile);
+ service = runOnboardViaApisOnly(filepath, vnfFile);
+
+// AtomicOperationUtils.getServiceObjectByNameAndVersion(sdncModifierDetails, serviceName, serviceVersion);
+// RestResponse distributeService = AtomicOperationUtils.distributeService(service, true);
+// Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject = ResponseParser.convertServiceDistributionStatusToObject(distributeService.getResponse());
+// convertServiceDistributionStatusToObject.
+ }
+
+ public static String getFilePath() {
+ String filepath = System.getProperty("filepath");
+ if (filepath == null && System.getProperty("os.name").contains("Windows")) {
+ filepath = FileHandling.getResourcesFilesPath() +"VNFs";
+ }
+
+ else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
+ filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator +"VNFs";
+ }
+ return filepath;
+ }
+
public static void downloadToscaCsarToDirectory(Service service, File file) {
try {
Either<String,RestResponse> serviceToscaArtifactPayload = AtomicOperationUtils.getServiceToscaArtifactPayload(service, "assettoscacsar");
@Test
public void deleteDeploymentArtifactFromVFInstanceTest() throws Exception{
- if(true){
- throw new SkipException("Open bug 300513");
- }
-
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType());
@Test
public void deleteDeploymentArtifactFromVFInstanceNextVersionTest() throws Exception{
- if(true){
- throw new SkipException("Open bug 300513");
- }
-
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType());
@Test
public void updateDeploymentArtifactOnVFInstanceNextVersionTest() throws Exception{
- if(true){
- throw new SkipException("Open bug 300513");
- }
-
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType());
@Test
public void addPropertiesToVfcInstanceInVfTest() throws Exception {
- if(true){
- throw new SkipException("Open bug 292047");
- }
-
String fileName = "vFW_VFC.yml";
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
jObject.put("description", "new VSP description");
jObject.put("category", "resourceNewCategory.generic");
jObject.put("subCategory", "resourceNewCategory.generic.database");
+ jObject.put("onboardingMethod", "HEAT");
jObject.put("licensingVersion", jlicensingVersionObj);
jObject.put("vendorName", vendorName);
jObject.put("vendorId", vendorId);
boolean vspFound = HomePage.searchForVSP(vspName);
if (vspFound){
-
+
List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable();
// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment"));
ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts);
- validateDeploymentArtifactsVersion(deploymentArtifacts);
+ List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")).
+ map(e -> e.getFileName()).
+ collect(Collectors.toList());
+
+ validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR);
+
DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile);
return createVendorSoftwareProduct;
}
- public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts) {
- String artifactVersion = "1";
+ public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts,
+ List<String> heatEnvFilesFromCSAR) {
+ String artifactVersion;
String artifactName;
-
+
for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) {
+ artifactVersion = "1";
+
if(deploymentArtifact.getType().equals("HEAT_ENV")) {
continue;
} else if(deploymentArtifact.getFileName().contains(".")) {
- artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
+ artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
} else {
- artifactName = deploymentArtifact.getFileName().trim();
+ artifactName = deploymentArtifact.getFileName().trim();
+ }
+
+ if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){
+ artifactVersion = "2";
}
- ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
+ ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
}
}