2 * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openecomp.sdc.be.components.impl;
18 import static java.util.stream.Collectors.joining;
19 import static java.util.stream.Collectors.toList;
20 import static java.util.stream.Collectors.toMap;
21 import static java.util.stream.Collectors.toSet;
22 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
24 import fj.data.Either;
25 import java.util.ArrayList;
26 import java.util.EnumMap;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.ListIterator;
33 import java.util.Optional;
35 import java.util.function.Function;
38 import org.apache.commons.codec.binary.Base64;
39 import org.apache.commons.collections.CollectionUtils;
40 import org.apache.commons.collections.MapUtils;
41 import org.apache.commons.lang3.tuple.ImmutablePair;
42 import org.openecomp.sdc.be.components.csar.CsarInfo;
43 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
44 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
45 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
46 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
47 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager;
49 import org.openecomp.sdc.be.config.ConfigurationManager;
50 import org.openecomp.sdc.be.dao.api.ActionStatus;
51 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
58 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
59 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
60 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
61 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
62 import org.openecomp.sdc.be.impl.ComponentsUtils;
63 import org.openecomp.sdc.be.model.ArtifactDefinition;
64 import org.openecomp.sdc.be.model.AttributeDefinition;
65 import org.openecomp.sdc.be.model.CapabilityDefinition;
66 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
67 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentInstanceInput;
71 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
72 import org.openecomp.sdc.be.model.ComponentParametersView;
73 import org.openecomp.sdc.be.model.GroupDefinition;
74 import org.openecomp.sdc.be.model.InputDefinition;
75 import org.openecomp.sdc.be.model.InterfaceDefinition;
76 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
77 import org.openecomp.sdc.be.model.LifecycleStateEnum;
78 import org.openecomp.sdc.be.model.NodeTypeInfo;
79 import org.openecomp.sdc.be.model.Operation;
80 import org.openecomp.sdc.be.model.PropertyDefinition;
81 import org.openecomp.sdc.be.model.RelationshipImpl;
82 import org.openecomp.sdc.be.model.RelationshipInfo;
83 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
84 import org.openecomp.sdc.be.model.RequirementDefinition;
85 import org.openecomp.sdc.be.model.Resource;
86 import org.openecomp.sdc.be.model.Service;
87 import org.openecomp.sdc.be.model.UploadCapInfo;
88 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
89 import org.openecomp.sdc.be.model.UploadInfo;
90 import org.openecomp.sdc.be.model.UploadPropInfo;
91 import org.openecomp.sdc.be.model.UploadReqInfo;
92 import org.openecomp.sdc.be.model.UploadResourceInfo;
93 import org.openecomp.sdc.be.model.User;
94 import org.openecomp.sdc.be.model.category.CategoryDefinition;
95 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
96 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
97 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
98 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
99 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
100 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
101 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
102 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
103 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
104 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
105 import org.openecomp.sdc.be.tosca.CsarUtils;
106 import org.openecomp.sdc.be.utils.CommonBeUtils;
107 import org.openecomp.sdc.be.utils.TypeUtils;
108 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
109 import org.openecomp.sdc.common.api.Constants;
110 import org.openecomp.sdc.common.log.wrappers.Logger;
111 import org.openecomp.sdc.common.util.GeneralUtility;
112 import org.openecomp.sdc.common.util.ValidationUtils;
113 import org.openecomp.sdc.exception.ResponseFormat;
114 import org.springframework.beans.factory.annotation.Autowired;
115 import org.yaml.snakeyaml.DumperOptions;
116 import org.yaml.snakeyaml.Yaml;
120 @org.springframework.stereotype.Component
121 public class ServiceImportParseLogic {
123 private static final String INITIAL_VERSION = "0.1";
124 private static final String CREATE_RESOURCE = "Create Resource";
125 private static final String IN_RESOURCE = " in resource {} ";
126 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
127 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
128 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
129 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
130 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
131 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
132 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
133 private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class);
135 private ServiceBusinessLogic serviceBusinessLogic;
137 private ComponentsUtils componentsUtils;
139 private ToscaOperationFacade toscaOperationFacade;
141 private LifecycleBusinessLogic lifecycleBusinessLogic;
143 private InputsBusinessLogic inputsBusinessLogic;
145 private ResourceImportManager resourceImportManager;
147 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
149 private ICapabilityTypeOperation capabilityTypeOperation = null;
151 public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
152 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
153 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
154 Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
155 .left(nodeTypesArtifactsToHandle);
157 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
158 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
159 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
160 csarInfo.getCsarUUID());
161 extractedVfcToscaNames.forEach(
162 (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
163 extractedVfcsArtifacts, namespace, vfcToscaNames));
164 } catch (Exception e) {
165 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
166 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
167 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
169 return nodeTypesArtifactsToHandleRes;
172 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
174 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
175 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
176 if (!nodes.isEmpty()) {
177 Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
178 while (nodesNameEntry.hasNext()) {
179 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
180 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
182 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
185 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
186 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
188 return vfcToscaNames;
191 public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
193 // We need to create a Yaml from each node_types in order to create
195 // resource from each node type using import normative flow.
196 DumperOptions options = new DumperOptions();
197 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
198 Yaml yaml = new Yaml(options);
199 Map<String, Object> node = new HashMap<>();
200 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
201 nodeNameValue.getValue());
202 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
203 return yaml.dumpAsMap(mapToConvert);
206 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
209 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
210 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
211 actualType = ResourceTypeEnum.VFC.name();
213 actualVfName = vfResourceName;
214 actualType = nodeResourceType;
216 String nameWithouNamespacePrefix;
218 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
219 if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
220 nameWithouNamespacePrefix = nodeTypeFullName;
222 nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
224 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
225 String resourceType = findTypes[0];
226 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
227 if (actualName.startsWith(Constants.ABSTRACT)) {
228 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
230 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
232 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
233 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
234 previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
235 } catch (Exception e) {
236 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
237 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
238 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
242 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
243 Map<String, Object> nodes = new HashMap<>();
244 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
245 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
247 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
251 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
252 Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
253 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
254 if (eitherNodeTypes.isLeft()) {
255 nodes.putAll(eitherNodeTypes.left().value());
259 protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
260 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
261 Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
262 ImmutablePair<String, String> vfcToscaNames) {
263 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
264 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
265 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
266 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
267 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
268 if (extractedVfcsArtifacts.containsKey(namespace)) {
269 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
271 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
272 } else if (curNodeType != null) {
273 // delete all artifacts if have not received artifacts from
277 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
278 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
279 // delete all informational artifacts
280 artifactsToDelete.addAll(
281 curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
283 // delete all deployment artifacts
284 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
285 if (!artifactsToDelete.isEmpty()) {
286 curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
288 } catch (Exception e) {
289 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
290 log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
291 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft());
294 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
295 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
299 protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
300 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
301 artifactsToAdd.stream().forEach(a -> {
302 if (!vfcArtifactNames.contains(a.getArtifactName())) {
305 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
310 protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName,
311 StorageOperationStatus status) {
312 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
313 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
314 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
315 } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
316 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
317 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
322 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
323 List<ArtifactDefinition> extractedArtifacts) {
324 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
326 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
327 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
328 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
329 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
330 collectExistingArtifacts(curNodeType));
331 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
332 } catch (Exception e) {
333 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
334 throw new ComponentException(ActionStatus.GENERAL_ERROR);
336 return nodeTypeArtifactsToHandle;
339 protected Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
340 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
341 if (curNodeType == null) {
342 return existingArtifacts;
344 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
345 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
347 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
348 existingArtifacts.putAll(
349 curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
350 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
352 return existingArtifacts;
355 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
356 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
357 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
358 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
359 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
360 if (!artifactsToUpload.isEmpty()) {
361 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
363 if (!artifactsToUpdate.isEmpty()) {
364 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
366 if (!artifactsToDelete.isEmpty()) {
367 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
370 return nodeTypeArtifactsToHandle;
373 protected void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
374 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
375 Map<String, ArtifactDefinition> existingArtifacts) {
377 if (!existingArtifacts.isEmpty()) {
378 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
379 artifactsToDelete.addAll(existingArtifacts.values());
381 } catch (Exception e) {
382 log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
383 throw new ComponentException(ActionStatus.GENERAL_ERROR);
387 protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
388 Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
389 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
390 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
391 if (foundArtifact.isPresent()) {
392 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
393 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
394 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
395 artifactsToUpload.remove(currNewArtifact);
397 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
398 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
399 currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
404 protected void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
405 ArtifactDefinition foundArtifact) {
406 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
407 foundArtifact.setPayload(currNewArtifact.getPayloadData());
408 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
409 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
410 artifactsToUpdate.add(foundArtifact);
414 public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
415 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
416 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
417 && eitherNonMetaArtifacts.isLeft()) {
418 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
419 if (eitherResult.isLeft()) {
420 createdArtifacts.add(eitherResult.left().value());
425 public boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
426 return !org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
429 public void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
430 groupsAsList.forEach(groupDefinition -> {
431 groupDefinition.setInvariantName(groupDefinition.getName());
432 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
436 public String getComponentTypeForResponse(Component component) {
437 String componentTypeForResponse = "SERVICE";
438 if (component instanceof Resource) {
439 componentTypeForResponse = ((Resource) component).getResourceType().name();
441 return componentTypeForResponse;
444 protected boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
445 Set<String> allGroupMembers) {
446 boolean stop = false;
447 // In Case Not Group Stop
448 if (!allGroups.containsKey(groupName)) {
451 // In Case Group Has no members stop
453 GroupDefinition groupDefinition = allGroups.get(groupName);
454 stop = MapUtils.isEmpty(groupDefinition.getMembers());
456 // In Case all group members already contained stop
458 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
459 Set<String> membersOfTypeGroup = allMembers.stream().
460 // Filter In Only Group members
461 filter(allGroups::containsKey).
464 stop = allGroupMembers.containsAll(membersOfTypeGroup);
469 public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
470 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
471 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
472 csarInfo.addNodeToQueue(nodeName);
473 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
476 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
478 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
479 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
480 validateLifecycleTypesCreate(user, resource, actionEnum);
481 validateResourceType(user, resource, actionEnum);
482 resource.setCreatorUserId(user.getUserId());
483 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
484 resource.setContactId(resource.getContactId().toLowerCase());
485 if (org.apache.commons.lang.StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
486 String resourceSystemName;
487 if (csarInfo != null && org.apache.commons.lang.StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
488 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
490 resourceSystemName = resource.getSystemName();
493 .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
495 // Generate invariant UUID - must be here and not in operation since it
497 // should stay constant during clone
500 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
501 resource.setInvariantUUID(invariantUUID);
505 protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
506 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
507 if (resource.getResourceType() == null) {
508 log.debug("Invalid resource type for resource");
509 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
510 eitherResult = Either.right(errorResponse);
511 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
516 protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
517 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
518 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
519 log.debug("validate interface lifecycle Types Exist");
520 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
521 while (intItr.hasNext() && eitherResult.isLeft()) {
522 InterfaceDefinition interfaceDefinition = intItr.next();
523 String intType = interfaceDefinition.getUniqueId();
524 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
525 if (eitherCapTypeFound.isRight()) {
526 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
527 BeEcompErrorManager.getInstance()
528 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
529 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
530 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
531 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
533 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
534 eitherResult = Either.right(errorResponse);
535 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
542 public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
543 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
544 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
545 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
546 log.debug("validate capability Types Exist - capabilities section");
547 for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
548 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
550 if (eitherResult.isRight()) {
551 return Either.right(eitherResult.right().value());
555 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
556 log.debug("validate capability Types Exist - requirements section");
557 for (String type : resource.getRequirements().keySet()) {
558 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
559 eitherResult, type, inTransaction);
560 if (eitherResult.isRight()) {
561 return Either.right(eitherResult.right().value());
568 protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
569 Resource resource, AuditingActionEnum actionEnum,
570 Either<Boolean, ResponseFormat> eitherResult,
571 Map.Entry<String, List<CapabilityDefinition>> typeEntry,
572 boolean inTransaction) {
573 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
574 .getCapabilityType(typeEntry.getKey(), inTransaction);
575 if (eitherCapTypeFound.isRight()) {
576 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
577 BeEcompErrorManager.getInstance()
578 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
579 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
580 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
582 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
583 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
584 eitherResult = Either.right(errorResponse);
585 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
586 return Either.right(eitherResult.right().value());
588 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
589 if (capabilityTypeDefinition.getProperties() != null) {
590 for (CapabilityDefinition capDef : typeEntry.getValue()) {
591 List<ComponentInstanceProperty> properties = capDef.getProperties();
592 if (properties == null || properties.isEmpty()) {
593 properties = new ArrayList<>();
594 for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
595 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
596 properties.add(newProp);
599 for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
600 PropertyDefinition porpFromDef = prop.getValue();
601 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
602 for (ComponentInstanceProperty cip : properties) {
603 if (!cip.getName().equals(porpFromDef.getName())) {
604 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
605 propsToAdd.add(newProp);
608 if (!propsToAdd.isEmpty()) {
609 properties.addAll(propsToAdd);
613 capDef.setProperties(properties);
619 protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
620 Resource resource, List<?> validationObjects,
621 AuditingActionEnum actionEnum,
622 Either<Boolean, ResponseFormat> eitherResult, String type,
623 boolean inTransaction) {
625 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
626 .getCapabilityType(type, inTransaction);
627 if (eitherCapTypeFound.isRight()) {
628 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
629 BeEcompErrorManager.getInstance()
630 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
631 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
632 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
634 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
635 ResponseFormat errorResponse = null;
637 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
639 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
641 eitherResult = Either.right(errorResponse);
642 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
644 } catch (Exception e) {
645 log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
646 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
651 protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum,
652 boolean inTransaction) {
653 serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
655 log.debug("validate category");
656 validateCategory(user, resource, actionEnum, inTransaction);
657 // validate vendor name & release & model number
658 log.debug("validate vendor name");
659 validateVendorName(user, resource, actionEnum);
660 log.debug("validate vendor release");
661 validateVendorReleaseName(user, resource, actionEnum);
662 log.debug("validate resource vendor model number");
663 validateResourceVendorModelNumber(user, resource, actionEnum);
665 log.debug("validate cost");
666 validateCost(resource);
667 // validate licenseType
668 log.debug("validate licenseType");
669 validateLicenseType(user, resource, actionEnum);
670 // validate template (derived from)
671 log.debug("validate derived from");
672 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.VF) {
673 resource.setDerivedFrom(null);
675 validateDerivedFromExist(user, resource, actionEnum);
676 serviceBusinessLogic.checkComponentFieldsForOverrideAttempt(resource);
677 String currentCreatorFullName = resource.getCreatorFullName();
678 if (currentCreatorFullName != null) {
679 log.debug("Resource Creator fullname is automatically set and cannot be updated");
681 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
682 if (currentLastUpdaterFullName != null) {
683 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
685 Long currentLastUpdateDate = resource.getLastUpdateDate();
686 if (currentLastUpdateDate != null) {
687 log.debug("Resource last update date is automatically set and cannot be updated");
689 Boolean currentAbstract = resource.isAbstract();
690 if (currentAbstract != null) {
691 log.debug("Resource abstract is automatically set and cannot be updated");
693 return Either.left(true);
696 protected void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
697 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
700 String templateName = resource.getDerivedFrom().get(0);
701 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
702 if (dataModelResponse.isRight()) {
703 StorageOperationStatus storageStatus = dataModelResponse.right().value();
704 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
705 log.debug("request to data model failed with error: {}", storageStatus);
706 ResponseFormat responseFormat = componentsUtils
707 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
708 log.trace("audit before sending response");
709 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
710 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
711 } else if (!dataModelResponse.left().value()) {
712 log.info("resource template with name: {}, does not exists", templateName);
713 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
714 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
715 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
719 protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
720 log.debug("validate licenseType");
721 String licenseType = resource.getLicenseType();
722 if (licenseType != null) {
723 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
724 if (!licenseTypes.contains(licenseType)) {
725 log.debug("License type {} isn't configured", licenseType);
726 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
727 if (actionEnum != null) {
728 // In update case, no audit is required
729 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
731 throw new ComponentException(ActionStatus.INVALID_CONTENT);
736 protected void validateCost(Resource resource) {
737 String cost = resource.getCost();
739 if (!ValidationUtils.validateCost(cost)) {
740 log.debug("resource cost is invalid.");
741 throw new ComponentException(ActionStatus.INVALID_CONTENT);
746 protected void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
747 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
748 if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
749 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
750 log.info("resource vendor model number exceeds limit.");
751 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
752 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
753 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
754 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
755 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
757 // resource vendor model number is currently validated as vendor
760 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
761 log.info("resource vendor model number is not valid.");
762 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
763 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
764 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
769 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
770 String vendorRelease = resource.getVendorRelease();
771 log.debug("validate vendor relese name");
772 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
773 log.info("vendor relese name is missing.");
774 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
775 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
776 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
778 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
781 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
782 if (vendorRelease != null) {
783 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
784 log.info("vendor release exceds limit.");
785 ResponseFormat errorResponse = componentsUtils
786 .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
787 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
788 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
790 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
791 log.info("vendor release is not valid.");
792 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
793 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
794 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
799 protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
800 List<CategoryDefinition> categories = resource.getCategories();
801 if (CollectionUtils.isEmpty(categories)) {
802 log.debug(CATEGORY_IS_EMPTY);
803 ResponseFormat responseFormat = componentsUtils
804 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
805 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
806 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
808 if (categories.size() > 1) {
809 log.debug("Must be only one category for resource");
810 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
812 CategoryDefinition category = categories.get(0);
813 List<SubCategoryDefinition> subcategories = category.getSubcategories();
814 if (CollectionUtils.isEmpty(subcategories)) {
815 log.debug("Missinig subcategory for resource");
816 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
818 if (subcategories.size() > 1) {
819 log.debug("Must be only one sub category for resource");
820 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
822 SubCategoryDefinition subcategory = subcategories.get(0);
823 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
824 log.debug(CATEGORY_IS_EMPTY);
825 ResponseFormat responseFormat = componentsUtils
826 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
827 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
828 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
830 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
831 log.debug(CATEGORY_IS_EMPTY);
832 ResponseFormat responseFormat = componentsUtils
833 .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
834 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
835 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
837 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
840 protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
841 AuditingActionEnum actionEnum, boolean inTransaction) {
842 ResponseFormat responseFormat;
843 if (category != null && subcategory != null) {
845 log.debug("validating resource category {} against valid categories list", category);
846 Either<List<CategoryDefinition>, ActionStatus> categories = serviceBusinessLogic.elementDao
847 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
848 if (categories.isRight()) {
849 log.debug("failed to retrieve resource categories from Titan");
850 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
851 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
852 throw new ComponentException(categories.right().value());
854 List<CategoryDefinition> categoryList = categories.left().value();
855 Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
857 if (!foundCategory.isPresent()) {
858 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
859 failOnInvalidCategory(user, resource, actionEnum);
861 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
862 .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
863 if (!foundSubcategory.isPresent()) {
864 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
865 foundCategory.get().getSubcategories());
866 failOnInvalidCategory(user, resource, actionEnum);
868 } catch (Exception e) {
869 log.debug("Exception occured when validateCategoryListed, error is:{}", e.getMessage(), e);
870 throw new ComponentException(ActionStatus.GENERAL_ERROR);
875 protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
876 ResponseFormat responseFormat;
877 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
878 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
879 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
882 protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
883 String vendorName = resource.getVendorName();
884 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
885 log.info("vendor name is missing.");
886 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
887 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
888 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
890 validateVendorName(vendorName, user, resource, actionEnum);
893 protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
894 if (vendorName != null) {
895 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
896 log.info("vendor name exceds limit.");
897 ResponseFormat errorResponse = componentsUtils
898 .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
899 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
900 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
902 if (!ValidationUtils.validateVendorName(vendorName)) {
903 log.info("vendor name is not valid.");
904 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
905 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
906 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
911 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
912 Resource cvfc = new Resource();
913 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
914 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
915 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
916 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
917 cvfc.setResourceType(ResourceTypeEnum.VF);
918 cvfc.setAbstract(true);
919 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
920 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
921 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
922 cvfc.setContactId(csarInfo.getModifier().getUserId());
923 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
924 cvfc.setVendorName(resourceVf.getVendorName());
925 cvfc.setVendorRelease(resourceVf.getVendorRelease());
926 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
927 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
928 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
929 List<String> tags = new ArrayList<>();
930 tags.add(cvfc.getName());
932 CategoryDefinition category = new CategoryDefinition();
933 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
934 SubCategoryDefinition subCategory = new SubCategoryDefinition();
935 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
936 category.addSubCategory(subCategory);
937 List<CategoryDefinition> categories = new ArrayList<>();
938 categories.add(category);
939 cvfc.setCategories(categories);
940 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
941 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
942 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
946 private String buildCvfcName(String resourceVfName, String nodeName) {
947 String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
948 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
949 String resourceType = findTypes[0];
950 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
951 return addCvfcSuffixToResourceName(resourceName);
954 private String addCvfcSuffixToResourceName(String resourceName) {
955 return resourceName + "VF";
958 public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
959 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
960 // validate nodetype name prefix
961 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
962 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
963 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
965 String actualName = this.getNodeTypeActualName(nodeName);
966 String namePrefix = nodeName.replace(actualName, "");
967 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
968 // if we import from csar, the node_type name can be
970 // org.openecomp.resource.abstract.node_name - in this case we always
973 if (resourceType.equals(Constants.ABSTRACT)) {
974 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
977 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
978 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
979 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
982 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
983 // Setting type from name
984 String type = resourceType.toUpperCase();
985 resourceMetaData.setResourceType(type);
986 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
987 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
988 resourceMetaData.setContactId(user.getUserId());
989 resourceMetaData.setVendorName(resourceVf.getVendorName());
990 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
992 List<String> tags = new ArrayList<>();
993 tags.add(resourceMetaData.getName());
994 resourceMetaData.setTags(tags);
996 CategoryDefinition category = new CategoryDefinition();
997 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
998 SubCategoryDefinition subCategory = new SubCategoryDefinition();
999 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1000 category.addSubCategory(subCategory);
1001 List<CategoryDefinition> categories = new ArrayList<>();
1002 categories.add(category);
1003 resourceMetaData.setCategories(categories);
1004 return resourceMetaData;
1007 protected String getNodeTypeActualName(String fullName) {
1008 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1009 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1010 String resourceType = findTypes[0];
1011 return nameWithouNamespacePrefix.substring(resourceType.length());
1014 public void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
1015 String propName = prop.getName();
1016 if (!currPropertiesMap.containsKey(propName)) {
1017 currPropertiesMap.put(propName, prop);
1021 public Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
1022 UploadComponentInstanceInfo uploadComponentInstanceInfo,
1023 ComponentInstance currentCompInstance, String capName) {
1024 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
1025 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
1026 RequirementDefinition validRegDef = null;
1028 for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
1029 for (RequirementDefinition reqDef : entry.getValue()) {
1030 if (reqDef.getName().equals(regName)) {
1031 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1032 String leftOccurrences = reqDef.getLeftOccurrences();
1033 if (leftOccurrences == null) {
1034 leftOccurrences = reqDef.getMaxOccurrences();
1036 int left = Integer.parseInt(leftOccurrences);
1039 reqDef.setLeftOccurrences(String.valueOf(left));
1040 validRegDef = reqDef;
1046 validRegDef = reqDef;
1051 if (validRegDef != null) {
1056 for (RequirementDefinition reqDef : list) {
1057 if (reqDef.getName().equals(regName)) {
1058 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1059 String leftOccurrences = reqDef.getLeftOccurrences();
1060 if (leftOccurrences == null) {
1061 leftOccurrences = reqDef.getMaxOccurrences();
1063 int left = Integer.parseInt(leftOccurrences);
1066 reqDef.setLeftOccurrences(String.valueOf(left));
1067 validRegDef = reqDef;
1073 validRegDef = reqDef;
1079 if (validRegDef == null) {
1080 ResponseFormat responseFormat = componentsUtils
1081 .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
1082 uploadComponentInstanceInfo.getType());
1083 return Either.right(responseFormat);
1085 return Either.left(validRegDef);
1088 public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1089 UploadReqInfo uploadReqInfo) {
1091 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
1092 // get by capability type
1093 return findAvailableCapability(validReq, currentCapCompInstance);
1095 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
1096 } catch (Exception e) {
1097 log.debug("Exception occured when findAvailableCapabilityByTypeOrName, error is:{}", e.getMessage(), e);
1098 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1102 protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
1103 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
1104 if (capMap.containsKey(validReq.getCapability())) {
1105 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
1106 for (CapabilityDefinition cap : capList) {
1107 if (isBoundedByOccurrences(cap)) {
1108 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
1109 int left = Integer.parseInt(leftOccurrences);
1112 cap.setLeftOccurrences(String.valueOf(left));
1123 protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1124 UploadReqInfo uploadReqInfo) {
1125 CapabilityDefinition cap = null;
1126 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
1127 if (!capMap.containsKey(validReq.getCapability())) {
1130 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
1131 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
1132 if (!capByName.isPresent()) {
1135 cap = capByName.get();
1136 if (isBoundedByOccurrences(cap)) {
1137 String leftOccurrences = cap.getLeftOccurrences();
1138 int left = Integer.parseInt(leftOccurrences);
1141 cap.setLeftOccurrences(String.valueOf(left));
1147 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
1148 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
1151 public ComponentParametersView getComponentFilterAfterCreateRelations() {
1152 ComponentParametersView parametersView = new ComponentParametersView();
1153 parametersView.disableAll();
1154 parametersView.setIgnoreComponentInstances(false);
1155 parametersView.setIgnoreComponentInstancesProperties(false);
1156 parametersView.setIgnoreCapabilities(false);
1157 parametersView.setIgnoreRequirements(false);
1158 parametersView.setIgnoreGroups(false);
1159 return parametersView;
1162 public ComponentParametersView getComponentWithInstancesFilter() {
1163 ComponentParametersView parametersView = new ComponentParametersView();
1164 parametersView.disableAll();
1165 parametersView.setIgnoreComponentInstances(false);
1166 parametersView.setIgnoreInputs(false);
1167 // inputs are read when creating
1169 // property values on instances
1170 parametersView.setIgnoreUsers(false);
1171 return parametersView;
1174 protected void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
1175 Map<String, List<CapabilityDefinition>> defaultCapabilities,
1176 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
1177 String capabilityType = capabilities.get(0).getType();
1178 if (defaultCapabilities.containsKey(capabilityType)) {
1179 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
1180 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
1181 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
1182 validCapabilityList.add(defaultCapability);
1183 validCapabilitiesMap.put(key, validCapabilityList);
1185 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
1189 protected CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
1190 String capabilityType) {
1191 CapabilityDefinition defaultCapability;
1192 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
1193 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
1195 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
1196 if (getFullComponentRes.isRight()) {
1197 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
1198 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId));
1200 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
1202 return defaultCapability;
1205 protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
1206 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
1207 log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
1208 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
1209 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
1210 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
1211 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
1215 protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
1216 UploadCapInfo uploadedCapability) {
1217 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
1218 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
1219 .collect(toMap(PropertyDefinition::getName, Function.identity()));
1220 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
1221 for (UploadPropInfo property : uploadedProperties) {
1222 String propertyName = property.getName().toLowerCase();
1223 String propertyType = property.getType();
1224 ComponentInstanceProperty validProperty;
1225 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
1226 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName));
1228 validProperty = new ComponentInstanceProperty();
1229 validProperty.setName(propertyName);
1230 if (property.getValue() != null) {
1231 validProperty.setValue(property.getValue().toString());
1233 validProperty.setDescription(property.getDescription());
1234 validProperty.setPassword(property.isPassword());
1235 validProperties.add(validProperty);
1237 defaultCapability.setProperties(validProperties);
1240 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
1241 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
1244 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1245 if (component instanceof Service) {
1246 Service service = (Service) component;
1247 Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
1248 if (artifactMap == null) {
1249 artifactMap = new HashMap<>();
1251 service.setDeploymentArtifacts(artifactMap);
1252 } else if (component instanceof Resource) {
1253 Resource resource = (Resource) component;
1254 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
1255 if (artifactMap == null) {
1256 artifactMap = new HashMap<>();
1258 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1259 .getDeploymentResourceArtifacts();
1260 if (deploymentResourceArtifacts != null) {
1261 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
1262 deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
1264 resource.setDeploymentArtifacts(artifactMap);
1268 protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
1269 boolean shouldCreateArtifact = true;
1270 Map<String, Object> artifactDetails = (Map<String, Object>) v;
1271 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
1272 if (object != null) {
1273 List<String> artifactTypes = (List<String>) object;
1274 if (!artifactTypes.contains(resource.getResourceType().name())) {
1278 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
1280 if (shouldCreateArtifact) {
1281 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1282 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1283 .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
1284 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
1285 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1291 public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
1292 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
1293 newResource.setTags(oldResource.getTags());
1295 if (newResource.getDescription() == null) {
1296 newResource.setDescription(oldResource.getDescription());
1298 if (newResource.getContactId() == null) {
1299 newResource.setContactId(oldResource.getContactId());
1301 newResource.setCategories(oldResource.getCategories());
1304 protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1305 Resource cvfc = new Resource();
1306 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1307 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1308 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1309 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1310 cvfc.setResourceType(ResourceTypeEnum.VF);
1311 cvfc.setAbstract(true);
1312 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1313 cvfc.setDescription(ImportUtils.Constants.VF_DESCRIPTION);
1314 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1315 cvfc.setContactId(csarInfo.getModifier().getUserId());
1316 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1317 cvfc.setVendorName("cmri");
1318 cvfc.setVendorRelease("1.0");
1319 cvfc.setResourceVendorModelNumber("");
1320 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1321 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1322 List<String> tags = new ArrayList<>();
1323 tags.add(cvfc.getName());
1325 CategoryDefinition category = new CategoryDefinition();
1326 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1327 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1328 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1329 category.addSubCategory(subCategory);
1330 List<CategoryDefinition> categories = new ArrayList<>();
1331 categories.add(category);
1332 cvfc.setCategories(categories);
1333 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1334 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1335 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1339 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1340 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1344 private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
1345 log.debug("validate resource derivedFrom field");
1346 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
1347 .getDerivedFrom().get(0).trim().isEmpty())) {
1348 log.info("derived from (template) field is missing for the resource");
1349 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1350 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
1351 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1355 public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
1356 List<InputDefinition> resourceProperties = service.getInputs();
1357 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1358 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service);
1359 if (createInputs.isRight()) {
1360 throw new ComponentException(createInputs.right().value());
1365 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1366 if (updatedResource.isRight()) {
1367 throw new ComponentException(componentsUtils
1368 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1369 ComponentTypeEnum.SERVICE));
1371 return updatedResource.left().value();
1374 public Service createServiceTransaction(Service service, User user, boolean isNormative) {
1375 // validate resource name uniqueness
1376 log.debug("validate resource name");
1377 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
1378 .validateComponentNameExists(service.getName(), null, service.getComponentType());
1379 if (eitherValidation.isRight()) {
1380 log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
1381 ResponseFormat errorResponse = componentsUtils
1382 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1383 throw new ComponentException(errorResponse);
1385 if (eitherValidation.left().value()) {
1386 log.debug("resource with name: {}, already exists", service.getName());
1387 ResponseFormat errorResponse = componentsUtils
1388 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1389 throw new ComponentException(errorResponse);
1391 log.debug("send resource {} to dao for create", service.getName());
1392 createArtifactsPlaceHolderData(service, user);
1395 log.debug("enrich resource with creator, version and state");
1396 service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1397 service.setVersion(INITIAL_VERSION);
1398 service.setHighestVersion(true);
1400 return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
1403 public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1404 ResponseFormat responseFormat = componentsUtils
1405 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1406 throw new ComponentException(responseFormat);
1409 protected void createArtifactsPlaceHolderData(Service service, User user) {
1410 setInformationalArtifactsPlaceHolder(service, user);
1411 serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1412 serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1415 @SuppressWarnings("unchecked")
1416 protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1417 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1418 if (artifactMap == null) {
1419 artifactMap = new HashMap<>();
1421 String resourceUniqueId = service.getUniqueId();
1422 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1423 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1424 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1425 .getInformationalResourceArtifacts();
1426 List<CategoryDefinition> categories = service.getCategories();
1427 boolean isCreateArtifact = true;
1428 if (exludeResourceCategory != null) {
1429 String category = categories.get(0).getName();
1430 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1432 if (informationalResourceArtifacts != null && isCreateArtifact) {
1433 Set<String> keys = informationalResourceArtifacts.keySet();
1434 for (String informationalResourceArtifactName : keys) {
1435 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1436 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1437 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1438 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1439 ArtifactGroupTypeEnum.INFORMATIONAL);
1440 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1444 service.setArtifacts(artifactMap);
1447 public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
1448 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1449 if (!inTransaction) {
1450 serviceBusinessLogic.janusGraphDao.rollback();
1452 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1453 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1454 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), service.getName());
1458 public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1459 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
1462 private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1464 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1467 private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1469 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
1470 .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
1471 if (resourceResponse.isRight()) {
1472 throw new ByResponseFormatComponentException(resourceResponse.right().value());
1474 return resourceResponse.left().value();
1477 public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
1478 boolean hasBeenCertified) {
1479 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1480 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1481 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
1482 log.trace("Update normative types");
1483 return Either.left(true);
1485 String derivedFromCurrent = currentDerivedFrom.get(0);
1486 String derivedFromUpdated = updatedDerivedFrom.get(0);
1487 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1488 if (!hasBeenCertified) {
1489 validateDerivedFromExist(null, updateInfoResource, null);
1491 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
1493 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1494 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1495 return validateDerivedFromExtending;
1499 return Either.left(true);
1502 protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
1503 AuditingActionEnum actionEnum) {
1504 String currentTemplateName = currentResource.getDerivedFrom().get(0);
1505 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1506 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1507 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
1508 if (dataModelResponse.isRight()) {
1509 StorageOperationStatus storageStatus = dataModelResponse.right().value();
1510 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1511 ResponseFormat responseFormat = componentsUtils
1512 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1513 log.trace("audit before sending response");
1514 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1515 return Either.right(responseFormat);
1517 if (!dataModelResponse.left().value()) {
1518 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
1519 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1520 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1521 return Either.right(responseFormat);
1523 return Either.left(true);
1526 public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1527 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1530 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1531 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1532 log.debug("validate resource name before update");
1533 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1534 log.debug("validate description before update");
1535 if (serviceBusinessLogic.componentDescriptionValidator != null) {
1536 serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1538 log.debug("validate icon before update");
1539 log.debug("validate tags before update");
1540 if (serviceBusinessLogic.componentTagsValidator != null) {
1541 serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1543 log.debug("validate vendor name before update");
1544 log.debug("validate resource vendor model number before update");
1545 log.debug("validate vendor release before update");
1546 log.debug("validate contact info before update");
1547 if (serviceBusinessLogic.componentContactIdValidator != null) {
1548 serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1550 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1551 log.debug("validate category before update");
1554 protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
1555 String resourceNameUpdated = updateInfoResource.getName();
1556 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1557 if (isNested || !hasBeenCertified) {
1558 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1559 currentResource.setName(resourceNameUpdated);
1560 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1561 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1563 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
1564 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1569 protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1570 String resourceNameUpdated = updateInfoResource.getName();
1571 String resourceNameCurrent = currentResource.getName();
1572 if (resourceNameCurrent.equals(resourceNameUpdated)) {
1575 return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
1576 .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1579 public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
1580 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1582 return lifecycleBusinessLogic
1583 .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
1584 inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
1589 protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1590 if (response.getRequestError() != null) {
1591 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
1592 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1593 ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
1595 throw new ComponentException(response);
1598 public Resource handleResourceGenericType(Resource resource) {
1599 Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1600 if (resource.shouldGenerateInputs()) {
1601 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1603 return genericResource;
1606 public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1607 List<InputDefinition> resourceProperties = resource.getInputs();
1608 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1609 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
1610 if (createInputs.isRight()) {
1611 throw new ComponentException(createInputs.right().value());
1616 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1617 if (updatedResource.isRight()) {
1618 throw new ComponentException(
1619 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1621 return updatedResource.left().value();
1624 protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1625 List<GroupDefinition> groupsFromResource = resource.getGroups();
1626 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1627 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1628 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1629 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1630 if (isNotEmpty(groupsFromResource)) {
1631 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1632 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1634 groupsToCreate.addAll(groupsAsList);
1636 if (isNotEmpty(groupsToCreate)) {
1637 fillGroupsFinalFields(groupsToCreate);
1638 if (isNotEmpty(groupsFromResource)) {
1639 serviceBusinessLogic.groupBusinessLogic.addGroups(resource, groupsToCreate, true).left()
1640 .on(serviceBusinessLogic::throwComponentException);
1642 serviceBusinessLogic.groupBusinessLogic.createGroups(resource, groupsToCreate, true).left()
1643 .on(serviceBusinessLogic::throwComponentException);
1646 if (isNotEmpty(groupsToDelete)) {
1647 serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
1649 if (isNotEmpty(groupsToUpdate)) {
1650 serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
1651 .on(serviceBusinessLogic::throwComponentException);
1655 protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1656 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1657 for (GroupDefinition group : groupsAsList) {
1658 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
1660 if (op.isPresent()) {
1661 GroupDefinition groupToUpdate = op.get();
1662 groupToUpdate.setMembers(group.getMembers());
1663 groupToUpdate.setCapabilities(group.getCapabilities());
1664 groupToUpdate.setProperties(group.getProperties());
1665 groupsToUpdate.add(groupToUpdate);
1667 groupsToCreate.add(group);
1672 protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1673 List<GroupDefinition> groupsToDelete) {
1674 for (GroupDefinition group : groupsFromResource) {
1675 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1676 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1677 groupsToDelete.add(group);
1682 protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1683 List<GroupDefinition> result = new ArrayList<>();
1684 List<ComponentInstance> componentInstances = component.getComponentInstances();
1685 if (groups != null) {
1686 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1687 if (validateCyclicGroupsDependencies.isRight()) {
1688 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1690 for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1691 String groupName = entry.getKey();
1692 GroupDefinition groupDefinition = entry.getValue();
1693 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1694 updatedGroupDefinition.setMembers(null);
1695 Map<String, String> members = groupDefinition.getMembers();
1696 if (members != null) {
1697 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1699 result.add(updatedGroupDefinition);
1705 public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
1706 List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1707 Set<String> compInstancesNames = members.keySet();
1708 if (CollectionUtils.isEmpty(componentInstances)) {
1709 String membersAstString = compInstancesNames.stream().collect(joining(","));
1710 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
1711 groupName, component.getNormalizedName());
1712 throw new ComponentException(componentsUtils
1713 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1714 getComponentTypeForResponse(component)));
1716 // Find all component instances with the member names
1717 Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1718 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1719 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
1720 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1721 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1722 List<String> foundMembers = new ArrayList<>();
1723 if (relevantInstances != null) {
1724 foundMembers = relevantInstances.keySet().stream().collect(toList());
1726 compInstancesNames.removeAll(foundMembers);
1727 String membersAstString = compInstancesNames.stream().collect(joining(","));
1728 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1729 throw new ComponentException(componentsUtils
1730 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1731 getComponentTypeForResponse(component)));
1733 updatedGroupDefinition.setMembers(relevantInstances);
1736 public Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1737 Either<Boolean, ResponseFormat> result = Either.left(true);
1739 Iterator<Map.Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1740 while (allGroupsItr.hasNext() && result.isLeft()) {
1741 Map.Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1742 // Fetches a group member A
1743 String groupAName = groupAEntry.getKey();
1744 // Finds all group members in group A
1745 Set<String> allGroupAMembersNames = new HashSet<>();
1746 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1747 // If A is a group member of itself found cyclic dependency
1748 if (allGroupAMembersNames.contains(groupAName)) {
1749 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1750 result = Either.right(responseFormat);
1753 } catch (Exception e) {
1754 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1755 result = Either.right(responseFormat);
1756 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1761 protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1762 // Found Cyclic dependency
1763 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1766 GroupDefinition groupDefinition = allGroups.get(groupName);
1767 // All Members Of Current Group Resource Instances & Other Groups
1768 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1769 // Filtered Members Of Current Group containing only members which
1772 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1773 // Keep Only Elements of type group and not Resource Instances
1774 filter(allGroups::containsKey).
1775 // Add Filtered Elements to main Set
1776 peek(allGroupMembers::add).
1779 // Recursively call the method for all the filtered group members
1780 for (String innerGroupName : currGroupFilteredMembers) {
1781 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1785 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
1786 boolean isInTransaction, boolean needLock,
1787 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1788 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1789 boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
1791 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1792 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1793 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1794 return resourceImportManager
1795 .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
1796 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1799 public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
1800 Map<String, Object> mapToConvert, Service resourceVf,
1802 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1803 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1804 boolean forceCertificationAllowed, CsarInfo csarInfo,
1806 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1807 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1808 user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1809 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1810 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1813 protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
1814 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1815 // validate nodetype name prefix
1816 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1817 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1818 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1820 String actualName = this.getNodeTypeActualName(nodeName);
1821 String namePrefix = nodeName.replace(actualName, "");
1822 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1823 // if we import from csar, the node_type name can be
1825 // org.openecomp.resource.abstract.node_name - in this case we always
1828 if (resourceType.equals(Constants.ABSTRACT)) {
1829 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1832 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1833 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1834 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1837 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1838 // Setting type from name
1839 String type = resourceType.toUpperCase();
1840 resourceMetaData.setResourceType(type);
1841 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1842 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1843 resourceMetaData.setContactId(user.getUserId());
1845 List<String> tags = new ArrayList<>();
1846 tags.add(resourceMetaData.getName());
1847 resourceMetaData.setTags(tags);
1849 CategoryDefinition category = new CategoryDefinition();
1850 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1851 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1852 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1853 category.addSubCategory(subCategory);
1854 List<CategoryDefinition> categories = new ArrayList<>();
1855 categories.add(category);
1856 resourceMetaData.setCategories(categories);
1857 return resourceMetaData;
1860 public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1861 boolean needLock, boolean forceCertificationAllowed) {
1862 Either<Resource, ResponseFormat> result = null;
1864 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
1865 .isFirstCertification(resource.getVersion())) {
1866 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1868 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
1869 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
1870 .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
1873 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
1874 } catch (Exception e) {
1875 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
1878 if (result == null || result.isRight()) {
1879 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
1880 if (!inTransaction) {
1881 serviceBusinessLogic.janusGraphDao.rollback();
1883 } else if (!inTransaction) {
1884 serviceBusinessLogic.janusGraphDao.commit();
1889 public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1890 Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
1891 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1892 csarInfo.addNodeToQueue(nodeName);
1893 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1896 public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1897 if (MapUtils.isEmpty(groups)) {
1900 updateOrCreateGroups(resource, groups);
1902 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1903 if (updatedResource.isRight()) {
1904 throw new ComponentException(
1905 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1907 return updatedResource.left().value();
1910 protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
1911 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
1912 if (artifactMap == null) {
1913 artifactMap = new HashMap<>();
1915 String resourceUniqueId = resource.getUniqueId();
1916 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1917 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1918 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1919 .getInformationalResourceArtifacts();
1920 List<CategoryDefinition> categories = resource.getCategories();
1921 boolean isCreateArtifact = true;
1922 if (exludeResourceCategory != null) {
1923 String category = categories.get(0).getName();
1924 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1926 if (isCreateArtifact && exludeResourceType != null) {
1927 String resourceType = resource.getResourceType().name();
1928 isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
1930 if (informationalResourceArtifacts != null && isCreateArtifact) {
1931 Set<String> keys = informationalResourceArtifacts.keySet();
1932 for (String informationalResourceArtifactName : keys) {
1933 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1934 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1935 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1936 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1937 ArtifactGroupTypeEnum.INFORMATIONAL);
1938 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1942 resource.setArtifacts(artifactMap);
1945 public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1946 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1947 if (!inTransaction) {
1948 serviceBusinessLogic.janusGraphDao.rollback();
1950 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1951 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1952 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
1956 public void createArtifactsPlaceHolderData(Resource resource, User user) {
1957 setInformationalArtifactsPlaceHolder(resource, user);
1958 setDeploymentArtifactsPlaceHolder(resource, user);
1959 serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
1962 public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
1963 List<InputDefinition> inputs = service.getInputs();
1964 if (MapUtils.isNotEmpty(groups)) {
1965 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1966 .forEach(p -> handleGetInputs(p, inputs));
1970 public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1971 List<InputDefinition> inputs = resource.getInputs();
1972 if (MapUtils.isNotEmpty(groups)) {
1973 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1974 .forEach(p -> handleGetInputs(p, inputs));
1978 protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1979 if (isNotEmpty(property.getGetInputValues())) {
1980 if (inputs == null || inputs.isEmpty()) {
1981 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1982 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1983 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1985 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1986 while (getInputValuesIter.hasNext()) {
1987 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1988 InputDefinition input = findInputByName(inputs, getInput);
1989 getInput.setInputId(input.getUniqueId());
1990 if (getInput.getGetInputIndex() != null) {
1991 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1992 input = findInputByName(inputs, getInputIndex);
1993 getInputIndex.setInputId(input.getUniqueId());
1994 getInputValuesIter.add(getInputIndex);
2000 public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
2001 Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
2002 if (!inputOpt.isPresent()) {
2003 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
2004 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
2006 return inputOpt.get();
2009 public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2010 Map<String, List<ComponentInstanceProperty>> instProperties) {
2012 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2013 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2014 if (addPropToInst.isRight()) {
2015 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
2016 throw new ComponentException(
2017 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2019 } catch (Exception e) {
2020 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
2021 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2025 public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2026 Map<String, List<ComponentInstanceInput>> instInputs) {
2027 if (MapUtils.isNotEmpty(instInputs)) {
2028 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2029 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2030 if (addInputToInst.isRight()) {
2031 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
2032 throw new ComponentException(
2033 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2038 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2039 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2040 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2041 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2042 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2043 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2047 public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2048 StorageOperationStatus addArtToInst;
2049 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2050 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2051 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2052 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2056 public void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2057 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2058 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2059 StorageOperationStatus addArtToInst;
2060 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2061 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2062 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2063 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2067 public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2068 Map<String, List<AttributeDefinition>> instAttributes) {
2069 StorageOperationStatus addArtToInst;
2070 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2071 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2072 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2073 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2077 public Resource getResourceAfterCreateRelations(Resource resource) {
2078 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2079 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2080 if (eitherGetResource.isRight()) {
2081 throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
2083 return eitherGetResource.left().value();
2086 public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2087 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
2088 throw new ComponentException(responseFormat);
2091 public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2092 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2093 for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2094 if (originCapabilities.containsKey(currEntry.getKey())) {
2095 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2098 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2099 capabilities.getValue().stream().forEach(cap -> {
2100 if (uploadedCapabilities.containsKey(cap.getName())) {
2101 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2102 c.setName(cap.getName());
2103 c.setType(cap.getType());
2110 public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
2111 Map<String, List<CapabilityDefinition>> defaultCapabilities,
2112 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2113 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2114 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
2115 return validCapabilitiesMap;
2118 public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2119 if (MapUtils.isNotEmpty(instInputs)) {
2120 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2121 .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2122 if (addInputToInst.isRight()) {
2123 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
2124 throw new ComponentException(
2125 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2130 public void associateComponentInstancePropertiesToComponent(String yamlName, Service service,
2131 Map<String, List<ComponentInstanceProperty>> instProperties) {
2132 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2133 .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2134 if (addPropToInst.isRight()) {
2135 throw new ComponentException(
2136 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2140 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
2141 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2142 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2143 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2144 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2145 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2149 public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2150 StorageOperationStatus addArtToInst;
2151 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2152 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2153 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2154 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2158 public void associateOrAddCalculatedCapReq(String yamlName, Service resource,
2159 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2160 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2161 StorageOperationStatus addArtToInst;
2162 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2163 log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
2164 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2165 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2166 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2170 public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
2171 Map<String, List<AttributeDefinition>> instAttributes) {
2172 StorageOperationStatus addArtToInst;
2173 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2174 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2175 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2176 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2180 public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2181 StorageOperationStatus addReqToService;
2182 addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
2183 if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2184 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
2185 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2189 public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
2190 StorageOperationStatus addCapToService;
2191 addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
2192 if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2193 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
2194 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2198 public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2199 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2200 .associateResourceInstances(service, service.getUniqueId(), relations);
2201 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2202 StorageOperationStatus status = relationsEither.right().value();
2203 log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
2204 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2208 public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2209 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
2210 originCapabilities.put(type, list);
2213 public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2214 for (UploadCapInfo capability : capabilities) {
2215 if (isNotEmpty(capability.getProperties())) {
2216 newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
2221 public Service getServiceWithGroups(String resourceId) {
2222 ComponentParametersView filter = new ComponentParametersView();
2223 filter.setIgnoreGroups(false);
2224 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2225 if (updatedResource.isRight()) {
2226 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2228 return updatedResource.left().value();
2231 public Resource getResourceWithGroups(String resourceId) {
2232 ComponentParametersView filter = new ComponentParametersView();
2233 filter.setIgnoreGroups(false);
2234 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2235 if (updatedResource.isRight()) {
2236 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2238 return updatedResource.left().value();
2241 public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2242 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2243 .associateResourceInstances(resource, resource.getUniqueId(), relations);
2244 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2245 StorageOperationStatus status = relationsEither.right().value();
2246 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
2247 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2251 public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2252 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2253 for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2254 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2255 ComponentInstance currentCompInstance = null;
2256 for (ComponentInstance compInstance : componentInstancesList) {
2257 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2258 currentCompInstance = compInstance;
2262 if (currentCompInstance == null) {
2263 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
2264 BeEcompErrorManager.getInstance()
2265 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
2266 BeEcompErrorManager.ErrorSeverity.ERROR);
2267 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2268 throw new ComponentException(responseFormat);
2270 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2271 if (addRelationToRiRes.getStatus() != 200) {
2272 throw new ComponentException(addRelationToRiRes);
2277 protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
2278 List<RequirementCapabilityRelDef> relations) {
2279 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2280 ComponentInstance currentCompInstance = null;
2281 for (ComponentInstance compInstance : componentInstancesList) {
2282 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2283 currentCompInstance = compInstance;
2287 if (currentCompInstance == null) {
2288 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
2289 BeEcompErrorManager.getInstance()
2290 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
2291 BeEcompErrorManager.ErrorSeverity.ERROR);
2292 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2294 String resourceInstanceId = currentCompInstance.getUniqueId();
2295 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2296 if (regMap != null) {
2297 Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2298 while (nodesRegValue.hasNext()) {
2299 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2300 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2301 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2302 log.debug("Going to create relation {}", uploadRegInfo.getName());
2303 String regName = uploadRegInfo.getName();
2304 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2305 regCapRelDef.setFromNode(resourceInstanceId);
2306 log.debug("try to find available requirement {} ", regName);
2307 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue,
2308 currentCompInstance, uploadRegInfo.getCapabilityName());
2309 if (eitherReqStatus.isRight()) {
2310 return eitherReqStatus.right().value();
2312 RequirementDefinition validReq = eitherReqStatus.left().value();
2313 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2314 if (reqAndRelationshipPairList == null) {
2315 reqAndRelationshipPairList = new ArrayList<>();
2317 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2318 reqAndRelationshipPair.setRequirement(regName);
2319 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2320 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2321 RelationshipImpl relationship = new RelationshipImpl();
2322 relationship.setType(validReq.getCapability());
2323 reqAndRelationshipPair.setRelationships(relationship);
2324 ComponentInstance currentCapCompInstance = null;
2325 for (ComponentInstance compInstance : componentInstancesList) {
2326 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2327 currentCapCompInstance = compInstance;
2331 if (currentCapCompInstance == null) {
2332 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
2333 BeEcompErrorManager.getInstance()
2334 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
2335 BeEcompErrorManager.ErrorSeverity.ERROR);
2336 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2338 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2339 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2340 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2341 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2342 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2343 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2344 if (aviableCapForRel == null) {
2345 BeEcompErrorManager.getInstance().logInternalDataError(
2346 "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2347 .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2348 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2350 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2351 capReqRel.setRelation(reqAndRelationshipPair);
2352 reqAndRelationshipPairList.add(capReqRel);
2353 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2354 relations.add(regCapRelDef);
2357 } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2358 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2360 return componentsUtils.getResponseFormat(ActionStatus.OK);