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 fj.data.Either;
20 import org.apache.commons.codec.binary.Base64;
21 import org.apache.commons.collections.CollectionUtils;
22 import org.apache.commons.collections.MapUtils;
23 import org.apache.commons.lang3.tuple.ImmutablePair;
24 import org.openecomp.sdc.be.components.csar.CsarInfo;
25 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
26 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
27 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
28 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
29 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
30 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.dao.api.ActionStatus;
34 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
35 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
36 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
37 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
38 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
39 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterPropertyDataDefinition;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
46 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
48 import org.openecomp.sdc.be.impl.ComponentsUtils;
49 import org.openecomp.sdc.be.model.ArtifactDefinition;
50 import org.openecomp.sdc.be.model.AttributeDefinition;
51 import org.openecomp.sdc.be.model.CapabilityDefinition;
52 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
53 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
54 import org.openecomp.sdc.be.model.Component;
55 import org.openecomp.sdc.be.model.ComponentInstance;
56 import org.openecomp.sdc.be.model.ComponentInstanceInput;
57 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
58 import org.openecomp.sdc.be.model.ComponentParametersView;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.InputDefinition;
61 import org.openecomp.sdc.be.model.InterfaceDefinition;
62 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
63 import org.openecomp.sdc.be.model.LifecycleStateEnum;
64 import org.openecomp.sdc.be.model.NodeTypeInfo;
65 import org.openecomp.sdc.be.model.Operation;
66 import org.openecomp.sdc.be.model.OutputDefinition;
67 import org.openecomp.sdc.be.model.PropertyDefinition;
68 import org.openecomp.sdc.be.model.RelationshipImpl;
69 import org.openecomp.sdc.be.model.RelationshipInfo;
70 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
71 import org.openecomp.sdc.be.model.RequirementDefinition;
72 import org.openecomp.sdc.be.model.Resource;
73 import org.openecomp.sdc.be.model.Service;
74 import org.openecomp.sdc.be.model.UploadCapInfo;
75 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
76 import org.openecomp.sdc.be.model.UploadInfo;
77 import org.openecomp.sdc.be.model.UploadInterfaceInfo;
78 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
79 import org.openecomp.sdc.be.model.UploadPropInfo;
80 import org.openecomp.sdc.be.model.UploadReqInfo;
81 import org.openecomp.sdc.be.model.UploadResourceInfo;
82 import org.openecomp.sdc.be.model.User;
83 import org.openecomp.sdc.be.model.category.CategoryDefinition;
84 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
85 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
86 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
87 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
88 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
89 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
90 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
91 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
94 import org.openecomp.sdc.be.tosca.CsarUtils;
95 import org.openecomp.sdc.be.utils.CommonBeUtils;
96 import org.openecomp.sdc.be.utils.TypeUtils;
97 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
98 import org.openecomp.sdc.common.api.Constants;
99 import org.openecomp.sdc.common.log.wrappers.Logger;
100 import org.openecomp.sdc.common.util.GeneralUtility;
101 import org.openecomp.sdc.common.util.ValidationUtils;
102 import org.openecomp.sdc.exception.ResponseFormat;
103 import org.yaml.snakeyaml.DumperOptions;
104 import org.yaml.snakeyaml.Yaml;
106 import java.util.ArrayList;
107 import java.util.EnumMap;
108 import java.util.HashMap;
109 import java.util.Iterator;
110 import java.util.List;
111 import java.util.ListIterator;
112 import java.util.Map;
113 import java.util.Optional;
114 import java.util.Set;
115 import java.util.function.Function;
117 import static java.util.stream.Collectors.joining;
118 import static java.util.stream.Collectors.toList;
119 import static java.util.stream.Collectors.toMap;
120 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
123 @org.springframework.stereotype.Component
124 public class ServiceImportParseLogic {
126 private static final String INITIAL_VERSION = "0.1";
127 private static final String CREATE_RESOURCE = "Create Resource";
128 private static final String IN_RESOURCE = " in resource {} ";
129 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
130 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
131 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
132 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
133 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
134 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
135 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
136 private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class);
137 private final ServiceBusinessLogic serviceBusinessLogic;
138 private final ComponentsUtils componentsUtils;
139 private final ToscaOperationFacade toscaOperationFacade;
140 private final LifecycleBusinessLogic lifecycleBusinessLogic;
141 private final InputsBusinessLogic inputsBusinessLogic;
142 private final ResourceImportManager resourceImportManager;
143 private final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic;
144 private final IInterfaceLifecycleOperation interfaceTypeOperation;
145 private final ICapabilityTypeOperation capabilityTypeOperation;
146 private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
147 private final GroupBusinessLogic groupBusinessLogic;
148 private final OutputsBusinessLogic outputsBusinessLogic;
150 public ServiceImportParseLogic(final ServiceBusinessLogic serviceBusinessLogic, final ComponentsUtils componentsUtils,
151 final ToscaOperationFacade toscaOperationFacade, final LifecycleBusinessLogic lifecycleBusinessLogic,
152 final InputsBusinessLogic inputsBusinessLogic, final ResourceImportManager resourceImportManager,
153 final ComponentSubstitutionFilterBusinessLogic substitutionFilterBusinessLogic,
154 final IInterfaceLifecycleOperation interfaceTypeOperation, final ICapabilityTypeOperation capabilityTypeOperation,
155 final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic,
156 final GroupBusinessLogic groupBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic) {
157 this.serviceBusinessLogic = serviceBusinessLogic;
158 this.componentsUtils = componentsUtils;
159 this.toscaOperationFacade = toscaOperationFacade;
160 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
161 this.inputsBusinessLogic = inputsBusinessLogic;
162 this.resourceImportManager = resourceImportManager;
163 this.substitutionFilterBusinessLogic = substitutionFilterBusinessLogic;
164 this.interfaceTypeOperation = interfaceTypeOperation;
165 this.capabilityTypeOperation = capabilityTypeOperation;
166 this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
167 this.groupBusinessLogic = groupBusinessLogic;
168 this.outputsBusinessLogic = outputsBusinessLogic;
171 public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
172 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
173 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
174 Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
175 .left(nodeTypesArtifactsToHandle);
177 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
178 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
179 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
180 csarInfo.getCsarUUID());
181 extractedVfcToscaNames.forEach(
182 (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
183 extractedVfcsArtifacts, namespace, vfcToscaNames));
184 } catch (Exception e) {
185 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
186 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
187 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
189 return nodeTypesArtifactsToHandleRes;
192 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
194 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
195 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
196 if (!nodes.isEmpty()) {
197 Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
198 while (nodesNameEntry.hasNext()) {
199 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
200 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
202 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
205 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
206 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
208 return vfcToscaNames;
211 public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
213 // We need to create a Yaml from each node_types in order to create
215 // resource from each node type using import normative flow.
216 DumperOptions options = new DumperOptions();
217 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
218 Yaml yaml = new Yaml(options);
219 Map<String, Object> node = new HashMap<>();
220 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
221 nodeNameValue.getValue());
222 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
223 return yaml.dumpAsMap(mapToConvert);
226 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
229 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
230 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
231 actualType = ResourceTypeEnum.VFC.name();
233 actualVfName = vfResourceName;
234 actualType = nodeResourceType;
236 String nameWithouNamespacePrefix;
238 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
239 if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
240 nameWithouNamespacePrefix = nodeTypeFullName;
242 nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
244 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
245 String resourceType = findTypes[0];
246 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
247 if (actualName.startsWith(Constants.ABSTRACT)) {
248 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
250 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
252 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
253 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
254 previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
255 } catch (Exception e) {
256 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
257 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
258 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
262 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
263 Map<String, Object> nodes = new HashMap<>();
264 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
265 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
267 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
271 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
272 Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
273 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
274 if (eitherNodeTypes.isLeft()) {
275 nodes.putAll(eitherNodeTypes.left().value());
279 protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
280 Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
281 Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
282 ImmutablePair<String, String> vfcToscaNames) {
283 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
284 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
285 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
286 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
287 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
288 if (extractedVfcsArtifacts.containsKey(namespace)) {
289 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
291 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
292 } else if (curNodeType != null) {
293 // delete all artifacts if have not received artifacts from
297 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
298 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
299 // delete all informational artifacts
300 artifactsToDelete.addAll(
301 curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
303 // delete all deployment artifacts
304 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
305 if (!artifactsToDelete.isEmpty()) {
306 curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
308 } catch (Exception e) {
309 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
310 log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
311 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft());
314 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
315 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
319 protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
320 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
321 artifactsToAdd.stream().forEach(a -> {
322 if (!vfcArtifactNames.contains(a.getArtifactName())) {
325 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
330 protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName,
331 StorageOperationStatus status) {
332 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
333 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
334 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
335 } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
336 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
337 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
342 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
343 List<ArtifactDefinition> extractedArtifacts) {
344 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
346 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
347 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
348 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
349 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
350 collectExistingArtifacts(curNodeType));
351 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
352 } catch (Exception e) {
353 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
354 throw new ComponentException(ActionStatus.GENERAL_ERROR);
356 return nodeTypeArtifactsToHandle;
359 protected Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
360 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
361 if (curNodeType == null) {
362 return existingArtifacts;
364 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
365 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
367 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
368 existingArtifacts.putAll(
369 curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
370 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
372 return existingArtifacts;
375 protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
376 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
377 EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
378 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
379 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
380 if (!artifactsToUpload.isEmpty()) {
381 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
383 if (!artifactsToUpdate.isEmpty()) {
384 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
386 if (!artifactsToDelete.isEmpty()) {
387 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
390 return nodeTypeArtifactsToHandle;
393 protected void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
394 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
395 Map<String, ArtifactDefinition> existingArtifacts) {
397 if (!existingArtifacts.isEmpty()) {
398 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
399 artifactsToDelete.addAll(existingArtifacts.values());
401 } catch (Exception e) {
402 log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
403 throw new ComponentException(ActionStatus.GENERAL_ERROR);
407 protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
408 Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
409 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
410 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
411 if (foundArtifact.isPresent()) {
412 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
413 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
414 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
415 artifactsToUpload.remove(currNewArtifact);
417 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
418 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
419 currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
424 protected void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
425 ArtifactDefinition foundArtifact) {
426 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
427 foundArtifact.setPayload(currNewArtifact.getPayloadData());
428 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
429 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
430 artifactsToUpdate.add(foundArtifact);
434 public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
435 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
436 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
437 && eitherNonMetaArtifacts.isLeft()) {
438 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
439 if (eitherResult.isLeft()) {
440 createdArtifacts.add(eitherResult.left().value());
445 public boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
446 return !org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
449 public void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
450 groupsAsList.forEach(groupDefinition -> {
451 groupDefinition.setInvariantName(groupDefinition.getName());
452 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
456 public String getComponentTypeForResponse(Component component) {
457 String componentTypeForResponse = "SERVICE";
458 if (component instanceof Resource) {
459 componentTypeForResponse = ((Resource) component).getResourceType().name();
461 return componentTypeForResponse;
464 public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
465 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
466 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
467 csarInfo.addNodeToQueue(nodeName);
468 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
471 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
473 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
474 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
475 validateLifecycleTypesCreate(user, resource, actionEnum);
476 validateResourceType(user, resource, actionEnum);
477 resource.setCreatorUserId(user.getUserId());
478 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
479 resource.setContactId(resource.getContactId().toLowerCase());
480 if (org.apache.commons.lang.StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
481 String resourceSystemName;
482 if (csarInfo != null && org.apache.commons.lang.StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
483 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
485 resourceSystemName = resource.getSystemName();
488 .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
490 // Generate invariant UUID - must be here and not in operation since it
492 // should stay constant during clone
495 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
496 resource.setInvariantUUID(invariantUUID);
500 protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
501 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
502 if (resource.getResourceType() == null) {
503 log.debug("Invalid resource type for resource");
504 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
505 eitherResult = Either.right(errorResponse);
506 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
511 protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
512 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
513 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
514 log.debug("validate interface lifecycle Types Exist");
515 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
516 while (intItr.hasNext() && eitherResult.isLeft()) {
517 InterfaceDefinition interfaceDefinition = intItr.next();
518 String intType = interfaceDefinition.getUniqueId();
519 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
520 if (eitherCapTypeFound.isRight()) {
521 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
522 BeEcompErrorManager.getInstance()
523 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
524 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
525 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
526 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
528 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
529 eitherResult = Either.right(errorResponse);
530 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
537 public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
538 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
539 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
540 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
541 log.debug("validate capability Types Exist - capabilities section");
542 for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
543 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
545 if (eitherResult.isRight()) {
546 return Either.right(eitherResult.right().value());
550 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
551 log.debug("validate capability Types Exist - requirements section");
552 for (String type : resource.getRequirements().keySet()) {
553 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
554 eitherResult, type, inTransaction);
555 if (eitherResult.isRight()) {
556 return Either.right(eitherResult.right().value());
563 protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
564 Resource resource, AuditingActionEnum actionEnum,
565 Either<Boolean, ResponseFormat> eitherResult,
566 Map.Entry<String, List<CapabilityDefinition>> typeEntry,
567 boolean inTransaction) {
568 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
569 .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
570 if (eitherCapTypeFound.isRight()) {
571 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
572 BeEcompErrorManager.getInstance()
573 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
574 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
575 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
577 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
578 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
579 eitherResult = Either.right(errorResponse);
580 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
581 return Either.right(eitherResult.right().value());
583 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
584 if (capabilityTypeDefinition.getProperties() != null) {
585 for (CapabilityDefinition capDef : typeEntry.getValue()) {
586 List<ComponentInstanceProperty> properties = capDef.getProperties();
587 if (properties == null || properties.isEmpty()) {
588 properties = new ArrayList<>();
589 for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
590 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
591 properties.add(newProp);
594 for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
595 PropertyDefinition porpFromDef = prop.getValue();
596 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
597 for (ComponentInstanceProperty cip : properties) {
598 if (!cip.getName().equals(porpFromDef.getName())) {
599 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
600 propsToAdd.add(newProp);
603 if (!propsToAdd.isEmpty()) {
604 properties.addAll(propsToAdd);
608 capDef.setProperties(properties);
614 protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
615 Resource resource, List<?> validationObjects,
616 AuditingActionEnum actionEnum,
617 Either<Boolean, ResponseFormat> eitherResult, String type,
618 boolean inTransaction) {
620 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
621 .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
622 if (eitherCapTypeFound.isRight()) {
623 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
624 BeEcompErrorManager.getInstance()
625 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
626 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
627 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
629 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
630 ResponseFormat errorResponse = null;
632 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
634 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
636 eitherResult = Either.right(errorResponse);
637 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
639 } catch (Exception e) {
640 log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
641 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
646 protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum,
647 boolean inTransaction) {
648 serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
650 log.debug("validate category");
651 validateCategory(user, resource, actionEnum, inTransaction);
652 // validate vendor name & release & model number
653 log.debug("validate vendor name");
654 validateVendorName(user, resource, actionEnum);
655 log.debug("validate vendor release");
656 validateVendorReleaseName(user, resource, actionEnum);
657 log.debug("validate resource vendor model number");
658 validateResourceVendorModelNumber(user, resource, actionEnum);
660 log.debug("validate cost");
661 validateCost(resource);
662 // validate licenseType
663 log.debug("validate licenseType");
664 validateLicenseType(user, resource, actionEnum);
665 // validate template (derived from)
666 log.debug("validate derived from");
667 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.VF) {
668 resource.setDerivedFrom(null);
670 validateDerivedFromExist(user, resource, actionEnum);
671 serviceBusinessLogic.checkComponentFieldsForOverrideAttempt(resource);
672 String currentCreatorFullName = resource.getCreatorFullName();
673 if (currentCreatorFullName != null) {
674 log.debug("Resource Creator fullname is automatically set and cannot be updated");
676 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
677 if (currentLastUpdaterFullName != null) {
678 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
680 Long currentLastUpdateDate = resource.getLastUpdateDate();
681 if (currentLastUpdateDate != null) {
682 log.debug("Resource last update date is automatically set and cannot be updated");
684 Boolean currentAbstract = resource.isAbstract();
685 if (currentAbstract != null) {
686 log.debug("Resource abstract is automatically set and cannot be updated");
688 return Either.left(true);
691 protected void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
692 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
695 String templateName = resource.getDerivedFrom().get(0);
696 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
697 if (dataModelResponse.isRight()) {
698 StorageOperationStatus storageStatus = dataModelResponse.right().value();
699 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
700 log.debug("request to data model failed with error: {}", storageStatus);
701 ResponseFormat responseFormat = componentsUtils
702 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
703 log.trace("audit before sending response");
704 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
705 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
706 } else if (!dataModelResponse.left().value()) {
707 log.info("resource template with name: {}, does not exists", templateName);
708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
709 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
710 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
714 protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
715 log.debug("validate licenseType");
716 String licenseType = resource.getLicenseType();
717 if (licenseType != null) {
718 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
719 if (!licenseTypes.contains(licenseType)) {
720 log.debug("License type {} isn't configured", licenseType);
721 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
722 if (actionEnum != null) {
723 // In update case, no audit is required
724 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
726 throw new ComponentException(ActionStatus.INVALID_CONTENT);
731 protected void validateCost(Resource resource) {
732 String cost = resource.getCost();
734 if (!ValidationUtils.validateCost(cost)) {
735 log.debug("resource cost is invalid.");
736 throw new ComponentException(ActionStatus.INVALID_CONTENT);
741 protected void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
742 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
743 if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
744 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
745 log.info("resource vendor model number exceeds limit.");
746 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
747 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
748 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
749 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
750 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
752 // resource vendor model number is currently validated as vendor
755 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
756 log.info("resource vendor model number is not valid.");
757 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
758 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
759 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
764 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
765 String vendorRelease = resource.getVendorRelease();
766 log.debug("validate vendor relese name");
767 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
768 log.info("vendor relese name is missing.");
769 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
770 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
771 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
773 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
776 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
777 if (vendorRelease != null) {
778 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
779 log.info("vendor release exceds limit.");
780 ResponseFormat errorResponse = componentsUtils
781 .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
782 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
783 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
785 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
786 log.info("vendor release is not valid.");
787 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
788 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
789 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
794 protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
795 List<CategoryDefinition> categories = resource.getCategories();
796 if (CollectionUtils.isEmpty(categories)) {
797 log.debug(CATEGORY_IS_EMPTY);
798 ResponseFormat responseFormat = componentsUtils
799 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
800 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
801 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
803 if (categories.size() > 1) {
804 log.debug("Must be only one category for resource");
805 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
807 CategoryDefinition category = categories.get(0);
808 List<SubCategoryDefinition> subcategories = category.getSubcategories();
809 if (CollectionUtils.isEmpty(subcategories)) {
810 log.debug("Missinig subcategory for resource");
811 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
813 if (subcategories.size() > 1) {
814 log.debug("Must be only one sub category for resource");
815 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
817 SubCategoryDefinition subcategory = subcategories.get(0);
818 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
819 log.debug(CATEGORY_IS_EMPTY);
820 ResponseFormat responseFormat = componentsUtils
821 .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
822 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
823 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
825 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
826 log.debug(CATEGORY_IS_EMPTY);
827 ResponseFormat responseFormat = componentsUtils
828 .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
829 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
830 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
832 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
835 protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
836 AuditingActionEnum actionEnum, boolean inTransaction) {
837 ResponseFormat responseFormat;
838 if (category != null && subcategory != null) {
840 log.debug("validating resource category {} against valid categories list", category);
841 Either<List<CategoryDefinition>, ActionStatus> categories = serviceBusinessLogic.elementDao
842 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
843 if (categories.isRight()) {
844 log.debug("failed to retrieve resource categories from Titan");
845 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
846 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
847 throw new ComponentException(categories.right().value());
849 List<CategoryDefinition> categoryList = categories.left().value();
850 Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
852 if (!foundCategory.isPresent()) {
853 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
854 failOnInvalidCategory(user, resource, actionEnum);
856 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
857 .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
858 if (!foundSubcategory.isPresent()) {
859 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
860 foundCategory.get().getSubcategories());
861 failOnInvalidCategory(user, resource, actionEnum);
863 } catch (Exception e) {
864 log.debug("Exception occured when validateCategoryListed, error is:{}", e.getMessage(), e);
865 throw new ComponentException(ActionStatus.GENERAL_ERROR);
870 protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
871 ResponseFormat responseFormat;
872 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
873 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
874 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
877 protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
878 String vendorName = resource.getVendorName();
879 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
880 log.info("vendor name is missing.");
881 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
882 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
883 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
885 validateVendorName(vendorName, user, resource, actionEnum);
888 protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
889 if (vendorName != null) {
890 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
891 log.info("vendor name exceds limit.");
892 ResponseFormat errorResponse = componentsUtils
893 .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
894 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
895 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
897 if (!ValidationUtils.validateVendorName(vendorName)) {
898 log.info("vendor name is not valid.");
899 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
900 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
901 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
906 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
907 Resource cvfc = new Resource();
908 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
909 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
910 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
911 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
912 cvfc.setResourceType(ResourceTypeEnum.VF);
913 cvfc.setAbstract(true);
914 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
915 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
916 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
917 cvfc.setContactId(csarInfo.getModifier().getUserId());
918 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
919 cvfc.setVendorName(resourceVf.getVendorName());
920 cvfc.setVendorRelease(resourceVf.getVendorRelease());
921 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
922 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
923 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
924 List<String> tags = new ArrayList<>();
925 tags.add(cvfc.getName());
927 CategoryDefinition category = new CategoryDefinition();
928 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
929 SubCategoryDefinition subCategory = new SubCategoryDefinition();
930 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
931 category.addSubCategory(subCategory);
932 List<CategoryDefinition> categories = new ArrayList<>();
933 categories.add(category);
934 cvfc.setCategories(categories);
935 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
936 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
937 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
941 private String buildCvfcName(String resourceVfName, String nodeName) {
942 String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
943 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
944 String resourceType = findTypes[0];
945 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
946 return addCvfcSuffixToResourceName(resourceName);
949 private String addCvfcSuffixToResourceName(String resourceName) {
950 return resourceName + "VF";
953 public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
954 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
955 // validate nodetype name prefix
956 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
957 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
958 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
960 String actualName = this.getNodeTypeActualName(nodeName);
961 String namePrefix = nodeName.replace(actualName, "");
962 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
963 // if we import from csar, the node_type name can be
965 // org.openecomp.resource.abstract.node_name - in this case we always
968 if (resourceType.equals(Constants.ABSTRACT)) {
969 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
972 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
973 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
974 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
977 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
978 // Setting type from name
979 String type = resourceType.toUpperCase();
980 resourceMetaData.setResourceType(type);
981 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
982 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
983 resourceMetaData.setContactId(user.getUserId());
984 resourceMetaData.setVendorName(resourceVf.getVendorName());
985 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
987 List<String> tags = new ArrayList<>();
988 tags.add(resourceMetaData.getName());
989 resourceMetaData.setTags(tags);
991 CategoryDefinition category = new CategoryDefinition();
992 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
993 SubCategoryDefinition subCategory = new SubCategoryDefinition();
994 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
995 category.addSubCategory(subCategory);
996 List<CategoryDefinition> categories = new ArrayList<>();
997 categories.add(category);
998 resourceMetaData.setCategories(categories);
999 return resourceMetaData;
1002 protected String getNodeTypeActualName(String fullName) {
1003 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1004 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1005 String resourceType = findTypes[0];
1006 return nameWithouNamespacePrefix.substring(resourceType.length());
1009 public void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
1010 String propName = prop.getName();
1011 if (!currPropertiesMap.containsKey(propName)) {
1012 currPropertiesMap.put(propName, prop);
1016 public Either<RequirementDefinition, ResponseFormat> findAvailableRequirement(String regName, String yamlName,
1017 UploadComponentInstanceInfo uploadComponentInstanceInfo,
1018 ComponentInstance currentCompInstance, String capName) {
1019 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
1020 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
1021 RequirementDefinition validRegDef = null;
1023 for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
1024 for (RequirementDefinition reqDef : entry.getValue()) {
1025 if (reqDef.getName().equals(regName)) {
1026 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1027 String leftOccurrences = reqDef.getLeftOccurrences();
1028 if (leftOccurrences == null) {
1029 leftOccurrences = reqDef.getMaxOccurrences();
1031 int left = Integer.parseInt(leftOccurrences);
1034 reqDef.setLeftOccurrences(String.valueOf(left));
1035 validRegDef = reqDef;
1039 validRegDef = reqDef;
1044 if (validRegDef != null) {
1049 for (RequirementDefinition reqDef : list) {
1050 if (reqDef.getName().equals(regName)) {
1051 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1052 String leftOccurrences = reqDef.getLeftOccurrences();
1053 if (leftOccurrences == null) {
1054 leftOccurrences = reqDef.getMaxOccurrences();
1056 int left = Integer.parseInt(leftOccurrences);
1059 reqDef.setLeftOccurrences(String.valueOf(left));
1060 validRegDef = reqDef;
1064 validRegDef = reqDef;
1070 if (validRegDef == null) {
1071 ResponseFormat responseFormat = componentsUtils
1072 .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
1073 uploadComponentInstanceInfo.getType());
1074 return Either.right(responseFormat);
1076 return Either.left(validRegDef);
1079 public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1080 UploadReqInfo uploadReqInfo) {
1082 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
1083 // get by capability type
1084 return findAvailableCapability(validReq, currentCapCompInstance);
1086 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
1087 } catch (Exception e) {
1088 log.debug("Exception occured when findAvailableCapabilityByTypeOrName, error is:{}", e.getMessage(), e);
1089 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1093 protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
1094 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
1095 if (capMap.containsKey(validReq.getCapability())) {
1096 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
1097 for (CapabilityDefinition cap : capList) {
1098 if (isBoundedByOccurrences(cap)) {
1099 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
1100 int left = Integer.parseInt(leftOccurrences);
1103 cap.setLeftOccurrences(String.valueOf(left));
1114 protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
1115 UploadReqInfo uploadReqInfo) {
1116 CapabilityDefinition cap = null;
1117 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
1118 if (!capMap.containsKey(validReq.getCapability())) {
1121 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
1122 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
1123 if (!capByName.isPresent()) {
1126 cap = capByName.get();
1127 if (isBoundedByOccurrences(cap)) {
1128 String leftOccurrences = cap.getLeftOccurrences();
1129 int left = Integer.parseInt(leftOccurrences);
1132 cap.setLeftOccurrences(String.valueOf(left));
1138 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
1139 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
1142 public ComponentParametersView getComponentFilterAfterCreateRelations() {
1143 ComponentParametersView parametersView = new ComponentParametersView();
1144 parametersView.disableAll();
1145 parametersView.setIgnoreComponentInstances(false);
1146 parametersView.setIgnoreComponentInstancesProperties(false);
1147 parametersView.setIgnoreCapabilities(false);
1148 parametersView.setIgnoreRequirements(false);
1149 parametersView.setIgnoreGroups(false);
1150 return parametersView;
1153 public ComponentParametersView getComponentWithInstancesFilter() {
1154 ComponentParametersView parametersView = new ComponentParametersView();
1155 parametersView.disableAll();
1156 parametersView.setIgnoreComponentInstances(false);
1157 parametersView.setIgnoreInputs(false);
1158 // inputs are read when creating
1160 // property values on instances
1161 parametersView.setIgnoreUsers(false);
1162 return parametersView;
1165 protected void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
1166 Map<String, List<CapabilityDefinition>> defaultCapabilities,
1167 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
1168 String capabilityType = capabilities.get(0).getType();
1169 if (defaultCapabilities.containsKey(capabilityType)) {
1170 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
1171 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
1172 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
1173 validCapabilityList.add(defaultCapability);
1174 validCapabilitiesMap.put(key, validCapabilityList);
1176 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
1180 protected CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
1181 String capabilityType) {
1182 CapabilityDefinition defaultCapability;
1183 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
1184 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
1186 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
1187 if (getFullComponentRes.isRight()) {
1188 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
1189 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId));
1191 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
1193 return defaultCapability;
1196 protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
1197 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
1198 log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
1199 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
1200 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
1201 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
1202 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
1206 protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
1207 UploadCapInfo uploadedCapability) {
1208 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
1209 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
1210 .collect(toMap(PropertyDefinition::getName, Function.identity()));
1211 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
1212 for (UploadPropInfo property : uploadedProperties) {
1213 String propertyName = property.getName().toLowerCase();
1214 String propertyType = property.getType();
1215 ComponentInstanceProperty validProperty;
1216 if (defaultProperties.containsKey(propertyName) && propertyTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
1217 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName));
1219 validProperty = new ComponentInstanceProperty();
1220 validProperty.setName(propertyName);
1221 if (property.getValue() != null) {
1222 validProperty.setValue(property.getValue().toString());
1224 validProperty.setDescription(property.getDescription());
1225 validProperty.setPassword(property.isPassword());
1226 validProperties.add(validProperty);
1228 defaultCapability.setProperties(validProperties);
1231 private boolean propertyTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
1232 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
1235 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1236 if (component instanceof Service) {
1237 Service service = (Service) component;
1238 Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
1239 if (artifactMap == null) {
1240 artifactMap = new HashMap<>();
1242 service.setDeploymentArtifacts(artifactMap);
1243 } else if (component instanceof Resource) {
1244 Resource resource = (Resource) component;
1245 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
1246 if (artifactMap == null) {
1247 artifactMap = new HashMap<>();
1249 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1250 .getDeploymentResourceArtifacts();
1251 if (deploymentResourceArtifacts != null) {
1252 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
1253 deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
1255 resource.setDeploymentArtifacts(artifactMap);
1259 protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
1260 boolean shouldCreateArtifact = true;
1261 Map<String, Object> artifactDetails = (Map<String, Object>) v;
1262 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
1263 if (object != null) {
1264 List<String> artifactTypes = (List<String>) object;
1265 if (!artifactTypes.contains(resource.getResourceType().name())) {
1269 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
1271 if (shouldCreateArtifact) {
1272 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1273 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1274 .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
1275 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
1276 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1282 public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
1283 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
1284 newResource.setTags(oldResource.getTags());
1286 if (newResource.getDescription() == null) {
1287 newResource.setDescription(oldResource.getDescription());
1289 if (newResource.getContactId() == null) {
1290 newResource.setContactId(oldResource.getContactId());
1292 newResource.setCategories(oldResource.getCategories());
1295 protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1296 Resource cvfc = new Resource();
1297 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1298 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1299 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1300 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1301 cvfc.setResourceType(ResourceTypeEnum.VF);
1302 cvfc.setAbstract(true);
1303 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1304 cvfc.setDescription(ImportUtils.Constants.VF_DESCRIPTION);
1305 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1306 cvfc.setContactId(csarInfo.getModifier().getUserId());
1307 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1308 cvfc.setVendorName("cmri");
1309 cvfc.setVendorRelease("1.0");
1310 cvfc.setResourceVendorModelNumber("");
1311 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1312 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1313 List<String> tags = new ArrayList<>();
1314 tags.add(cvfc.getName());
1316 CategoryDefinition category = new CategoryDefinition();
1317 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1318 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1319 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1320 category.addSubCategory(subCategory);
1321 List<CategoryDefinition> categories = new ArrayList<>();
1322 categories.add(category);
1323 cvfc.setCategories(categories);
1324 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1325 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1326 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1330 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1331 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1335 private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
1336 log.debug("validate resource derivedFrom field");
1337 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
1338 .getDerivedFrom().get(0).trim().isEmpty())) {
1339 log.info("derived from (template) field is missing for the resource");
1340 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1341 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
1342 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1346 public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
1347 List<InputDefinition> resourceProperties = service.getInputs();
1348 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1349 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service);
1350 if (createInputs.isRight()) {
1351 throw new ComponentException(createInputs.right().value());
1356 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1357 if (updatedResource.isRight()) {
1358 throw new ComponentException(componentsUtils
1359 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1360 ComponentTypeEnum.SERVICE));
1362 return updatedResource.left().value();
1365 public Service createOutputsOnService(final Service service, final Map<String, OutputDefinition> outputs, final String userId) {
1366 if (MapUtils.isNotEmpty(outputs) || isNotEmpty(service.getOutputs())) {
1367 final Either<List<OutputDefinition>, ResponseFormat> createOutputs = outputsBusinessLogic.createOutputsInGraph(outputs, service, userId);
1368 if (createOutputs.isRight()) {
1369 throw new ComponentException(createOutputs.right().value());
1374 final Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1375 if (updatedResource.isRight()) {
1376 throw new ComponentException(
1377 componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1378 ComponentTypeEnum.SERVICE));
1380 return updatedResource.left().value();
1383 public Service createSubstitutionFilterOnService(Service service,
1384 ListDataDefinition<SubstitutionFilterPropertyDataDefinition> substitutionFilterProperties)
1385 throws BusinessLogicException {
1386 if (substitutionFilterProperties == null || substitutionFilterProperties.isEmpty()) {
1389 substitutionFilterBusinessLogic.addSubstitutionFilterInGraph(service.getUniqueId(), substitutionFilterProperties);
1390 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1391 if (updatedResource.isRight()) {
1392 throw new ComponentException(componentsUtils
1393 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1394 ComponentTypeEnum.SERVICE));
1396 return updatedResource.left().value();
1400 public Service createServiceTransaction(Service service, User user, boolean isNormative) {
1401 // validate resource name uniqueness
1402 log.debug("validate resource name");
1403 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
1404 .validateComponentNameExists(service.getName(), null, service.getComponentType());
1405 if (eitherValidation.isRight()) {
1406 log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
1407 ResponseFormat errorResponse = componentsUtils
1408 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1409 throw new ComponentException(errorResponse);
1411 if (eitherValidation.left().value()) {
1412 log.debug("resource with name: {}, already exists", service.getName());
1413 ResponseFormat errorResponse = componentsUtils
1414 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1415 throw new ComponentException(errorResponse);
1417 log.debug("send resource {} to dao for create", service.getName());
1418 createArtifactsPlaceHolderData(service, user);
1421 log.debug("enrich resource with creator, version and state");
1422 service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1423 service.setVersion(INITIAL_VERSION);
1424 service.setHighestVersion(true);
1426 return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
1429 public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1430 ResponseFormat responseFormat = componentsUtils
1431 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1432 throw new ComponentException(responseFormat);
1435 protected void createArtifactsPlaceHolderData(Service service, User user) {
1436 setInformationalArtifactsPlaceHolder(service, user);
1437 serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1438 serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1441 @SuppressWarnings("unchecked")
1442 protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1443 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1444 if (artifactMap == null) {
1445 artifactMap = new HashMap<>();
1447 String resourceUniqueId = service.getUniqueId();
1448 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1449 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1450 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1451 .getInformationalResourceArtifacts();
1452 List<CategoryDefinition> categories = service.getCategories();
1453 boolean isCreateArtifact = true;
1454 if (exludeResourceCategory != null) {
1455 String category = categories.get(0).getName();
1456 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1458 if (informationalResourceArtifacts != null && isCreateArtifact) {
1459 Set<String> keys = informationalResourceArtifacts.keySet();
1460 for (String informationalResourceArtifactName : keys) {
1461 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1462 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1463 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1464 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1465 ArtifactGroupTypeEnum.INFORMATIONAL);
1466 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1470 service.setArtifacts(artifactMap);
1473 public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
1474 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1475 if (!inTransaction) {
1476 serviceBusinessLogic.janusGraphDao.rollback();
1478 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1479 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1480 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), service.getName());
1484 public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1485 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
1488 private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1490 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1493 private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1495 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
1496 .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
1497 if (resourceResponse.isRight()) {
1498 throw new ByResponseFormatComponentException(resourceResponse.right().value());
1500 return resourceResponse.left().value();
1503 public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
1504 boolean hasBeenCertified) {
1505 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1506 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1507 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
1508 log.trace("Update normative types");
1509 return Either.left(true);
1511 String derivedFromCurrent = currentDerivedFrom.get(0);
1512 String derivedFromUpdated = updatedDerivedFrom.get(0);
1513 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1514 if (!hasBeenCertified) {
1515 validateDerivedFromExist(null, updateInfoResource, null);
1517 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
1519 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1520 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1521 return validateDerivedFromExtending;
1525 return Either.left(true);
1528 protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
1529 AuditingActionEnum actionEnum) {
1530 String currentTemplateName = currentResource.getDerivedFrom().get(0);
1531 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1532 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1533 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
1534 if (dataModelResponse.isRight()) {
1535 StorageOperationStatus storageStatus = dataModelResponse.right().value();
1536 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1537 ResponseFormat responseFormat = componentsUtils
1538 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1539 log.trace("audit before sending response");
1540 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1541 return Either.right(responseFormat);
1543 if (!dataModelResponse.left().value()) {
1544 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
1545 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1546 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1547 return Either.right(responseFormat);
1549 return Either.left(true);
1552 public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1553 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1556 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1557 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1558 log.debug("validate resource name before update");
1559 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1560 log.debug("validate description before update");
1561 if (serviceBusinessLogic.componentDescriptionValidator != null) {
1562 serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1564 log.debug("validate icon before update");
1565 log.debug("validate tags before update");
1566 if (serviceBusinessLogic.componentTagsValidator != null) {
1567 serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1569 log.debug("validate vendor name before update");
1570 log.debug("validate resource vendor model number before update");
1571 log.debug("validate vendor release before update");
1572 log.debug("validate contact info before update");
1573 if (serviceBusinessLogic.componentContactIdValidator != null) {
1574 serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1576 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1577 log.debug("validate category before update");
1580 protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
1581 String resourceNameUpdated = updateInfoResource.getName();
1582 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1583 if (isNested || !hasBeenCertified) {
1584 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1585 currentResource.setName(resourceNameUpdated);
1586 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1587 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1589 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
1590 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1595 protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1596 String resourceNameUpdated = updateInfoResource.getName();
1597 String resourceNameCurrent = currentResource.getName();
1598 if (resourceNameCurrent.equals(resourceNameUpdated)) {
1601 return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
1602 .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1605 public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
1606 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1608 return lifecycleBusinessLogic
1609 .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
1610 inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
1615 protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1616 if (response.getRequestError() != null) {
1617 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
1618 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1619 ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
1621 throw new ComponentException(response);
1624 public Resource handleResourceGenericType(Resource resource) {
1625 Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1626 if (resource.shouldGenerateInputs()) {
1627 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1629 return genericResource;
1632 public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1633 List<InputDefinition> resourceProperties = resource.getInputs();
1634 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1635 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
1636 if (createInputs.isRight()) {
1637 throw new ComponentException(createInputs.right().value());
1642 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1643 if (updatedResource.isRight()) {
1644 throw new ComponentException(
1645 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1647 return updatedResource.left().value();
1650 protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1651 List<GroupDefinition> groupsFromResource = resource.getGroups();
1652 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1653 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1654 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1655 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1656 if (isNotEmpty(groupsFromResource)) {
1657 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1658 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1660 groupsToCreate.addAll(groupsAsList);
1662 if (isNotEmpty(groupsToCreate)) {
1663 fillGroupsFinalFields(groupsToCreate);
1664 if (isNotEmpty(groupsFromResource)) {
1665 groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1667 groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(serviceBusinessLogic::throwComponentException);
1670 if (isNotEmpty(groupsToDelete)) {
1671 groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
1673 if (isNotEmpty(groupsToUpdate)) {
1674 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
1675 .on(serviceBusinessLogic::throwComponentException);
1679 protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1680 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1681 for (GroupDefinition group : groupsAsList) {
1682 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
1684 if (op.isPresent()) {
1685 GroupDefinition groupToUpdate = op.get();
1686 groupToUpdate.setMembers(group.getMembers());
1687 groupToUpdate.setCapabilities(group.getCapabilities());
1688 groupToUpdate.setProperties(group.getProperties());
1689 groupsToUpdate.add(groupToUpdate);
1691 groupsToCreate.add(group);
1696 protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1697 List<GroupDefinition> groupsToDelete) {
1698 for (GroupDefinition group : groupsFromResource) {
1699 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1700 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1701 groupsToDelete.add(group);
1706 protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1707 List<GroupDefinition> result = new ArrayList<>();
1708 List<ComponentInstance> componentInstances = component.getComponentInstances();
1709 if (groups != null) {
1710 for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1711 String groupName = entry.getKey();
1712 GroupDefinition groupDefinition = entry.getValue();
1713 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1714 updatedGroupDefinition.setMembers(null);
1715 Map<String, String> members = groupDefinition.getMembers();
1716 if (members != null) {
1717 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1719 result.add(updatedGroupDefinition);
1725 public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
1726 List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1727 Set<String> compInstancesNames = members.keySet();
1728 if (CollectionUtils.isEmpty(componentInstances)) {
1729 String membersAstString = compInstancesNames.stream().collect(joining(","));
1730 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
1731 groupName, component.getNormalizedName());
1732 throw new ComponentException(componentsUtils
1733 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1734 getComponentTypeForResponse(component)));
1736 // Find all component instances with the member names
1737 Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1738 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1739 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
1740 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1741 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1742 List<String> foundMembers = new ArrayList<>();
1743 if (relevantInstances != null) {
1744 foundMembers = relevantInstances.keySet().stream().collect(toList());
1746 compInstancesNames.removeAll(foundMembers);
1747 String membersAstString = compInstancesNames.stream().collect(joining(","));
1748 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1749 throw new ComponentException(componentsUtils
1750 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
1751 getComponentTypeForResponse(component)));
1753 updatedGroupDefinition.setMembers(relevantInstances);
1756 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
1757 boolean isInTransaction, boolean needLock,
1758 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1759 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1760 boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
1762 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1763 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1764 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1765 return resourceImportManager
1766 .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
1767 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1770 public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
1771 Map<String, Object> mapToConvert, Service resourceVf,
1773 Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1774 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1775 boolean forceCertificationAllowed, CsarInfo csarInfo,
1777 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1778 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1779 user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1780 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1781 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1784 protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
1785 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1786 // validate nodetype name prefix
1787 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1788 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1789 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1791 String actualName = this.getNodeTypeActualName(nodeName);
1792 String namePrefix = nodeName.replace(actualName, "");
1793 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1794 // if we import from csar, the node_type name can be
1796 // org.openecomp.resource.abstract.node_name - in this case we always
1799 if (resourceType.equals(Constants.ABSTRACT)) {
1800 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1803 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1804 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1805 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1808 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1809 // Setting type from name
1810 String type = resourceType.toUpperCase();
1811 resourceMetaData.setResourceType(type);
1812 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1813 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1814 resourceMetaData.setContactId(user.getUserId());
1816 List<String> tags = new ArrayList<>();
1817 tags.add(resourceMetaData.getName());
1818 resourceMetaData.setTags(tags);
1820 CategoryDefinition category = new CategoryDefinition();
1821 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1822 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1823 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1824 category.addSubCategory(subCategory);
1825 List<CategoryDefinition> categories = new ArrayList<>();
1826 categories.add(category);
1827 resourceMetaData.setCategories(categories);
1828 return resourceMetaData;
1831 public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
1832 boolean needLock, boolean forceCertificationAllowed) {
1833 Either<Resource, ResponseFormat> result = null;
1835 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
1836 .isFirstCertification(resource.getVersion())) {
1837 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
1839 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
1840 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
1841 .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
1844 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
1845 } catch (Exception e) {
1846 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
1849 if (result == null || result.isRight()) {
1850 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
1851 if (!inTransaction) {
1852 serviceBusinessLogic.janusGraphDao.rollback();
1854 } else if (!inTransaction) {
1855 serviceBusinessLogic.janusGraphDao.commit();
1860 public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1861 Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
1862 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1863 csarInfo.addNodeToQueue(nodeName);
1864 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1867 public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1868 if (MapUtils.isEmpty(groups)) {
1871 updateOrCreateGroups(resource, groups);
1873 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1874 if (updatedResource.isRight()) {
1875 throw new ComponentException(
1876 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1878 return updatedResource.left().value();
1881 protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
1882 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
1883 if (artifactMap == null) {
1884 artifactMap = new HashMap<>();
1886 String resourceUniqueId = resource.getUniqueId();
1887 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
1888 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
1889 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1890 .getInformationalResourceArtifacts();
1891 List<CategoryDefinition> categories = resource.getCategories();
1892 boolean isCreateArtifact = true;
1893 if (exludeResourceCategory != null) {
1894 String category = categories.get(0).getName();
1895 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
1897 if (isCreateArtifact && exludeResourceType != null) {
1898 String resourceType = resource.getResourceType().name();
1899 isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
1901 if (informationalResourceArtifacts != null && isCreateArtifact) {
1902 Set<String> keys = informationalResourceArtifacts.keySet();
1903 for (String informationalResourceArtifactName : keys) {
1904 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
1905 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1906 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
1907 .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1908 ArtifactGroupTypeEnum.INFORMATIONAL);
1909 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1913 resource.setArtifacts(artifactMap);
1916 public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1917 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1918 if (!inTransaction) {
1919 serviceBusinessLogic.janusGraphDao.rollback();
1921 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1922 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1923 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
1927 public void createArtifactsPlaceHolderData(Resource resource, User user) {
1928 setInformationalArtifactsPlaceHolder(resource, user);
1929 setDeploymentArtifactsPlaceHolder(resource, user);
1930 serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
1933 public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
1934 List<InputDefinition> inputs = service.getInputs();
1935 if (MapUtils.isNotEmpty(groups)) {
1936 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1937 .forEach(p -> handleGetInputs(p, inputs));
1941 public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1942 List<InputDefinition> inputs = resource.getInputs();
1943 if (MapUtils.isNotEmpty(groups)) {
1944 groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
1945 .forEach(p -> handleGetInputs(p, inputs));
1949 protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1950 if (isNotEmpty(property.getGetInputValues())) {
1951 if (inputs == null || inputs.isEmpty()) {
1952 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1953 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1954 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1956 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1957 while (getInputValuesIter.hasNext()) {
1958 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1959 InputDefinition input = findInputByName(inputs, getInput);
1960 getInput.setInputId(input.getUniqueId());
1961 if (getInput.getGetInputIndex() != null) {
1962 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1963 input = findInputByName(inputs, getInputIndex);
1964 getInputIndex.setInputId(input.getUniqueId());
1965 getInputValuesIter.add(getInputIndex);
1971 public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1972 Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
1973 if (!inputOpt.isPresent()) {
1974 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1975 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1977 return inputOpt.get();
1980 public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
1981 Map<String, List<ComponentInstanceProperty>> instProperties) {
1983 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
1984 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
1985 if (addPropToInst.isRight()) {
1986 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
1987 throw new ComponentException(
1988 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
1990 } catch (Exception e) {
1991 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
1992 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1996 public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
1997 Map<String, List<ComponentInstanceInput>> instInputs) {
1998 if (MapUtils.isNotEmpty(instInputs)) {
1999 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2000 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2001 if (addInputToInst.isRight()) {
2002 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
2003 throw new ComponentException(
2004 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2009 public void associateComponentInstanceInterfacesToComponent(
2012 Map<String, Map<String, InterfaceDefinition>> instInterfaces
2014 if (MapUtils.isNotEmpty(instInterfaces)) {
2015 Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> addInterfaceToInst =
2016 toscaOperationFacade
2017 .associateComponentInstanceInterfacesToComponent(
2019 service.getUniqueId()
2021 if (addInterfaceToInst.isRight()) {
2022 log.error("failed to associate interfaces value of service {}, status is {}", service.getUniqueId(), addInterfaceToInst.right().value());
2023 throw new ComponentException(
2024 componentsUtils.getResponseFormat(
2025 componentsUtils.convertFromStorageResponse(
2026 addInterfaceToInst.right().value()
2035 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2036 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2037 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2038 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2039 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2040 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2044 public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2045 StorageOperationStatus addArtToInst;
2046 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2047 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2048 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2049 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2053 public void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2054 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2055 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2056 StorageOperationStatus addArtToInst;
2057 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2058 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2059 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2060 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2064 public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2065 Map<String, List<AttributeDefinition>> instAttributes) {
2066 StorageOperationStatus addArtToInst;
2067 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2068 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2069 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2070 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2074 public Resource getResourceAfterCreateRelations(Resource resource) {
2075 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2076 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2077 if (eitherGetResource.isRight()) {
2078 throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
2080 return eitherGetResource.left().value();
2083 public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2084 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
2085 throw new ComponentException(responseFormat);
2088 public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2089 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2090 for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2091 if (originCapabilities.containsKey(currEntry.getKey())) {
2092 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2095 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2096 capabilities.getValue().stream().forEach(cap -> {
2097 if (uploadedCapabilities.containsKey(cap.getName())) {
2098 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2099 c.setName(cap.getName());
2100 c.setType(cap.getType());
2107 public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
2108 Map<String, List<CapabilityDefinition>> defaultCapabilities,
2109 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2110 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2111 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
2112 return validCapabilitiesMap;
2115 public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2116 if (MapUtils.isNotEmpty(instInputs)) {
2117 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2118 .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2119 if (addInputToInst.isRight()) {
2120 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
2121 throw new ComponentException(
2122 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2127 public void associateCINodeFilterToComponent(String yamlName, Service service, Map<String, UploadNodeFilterInfo> nodeFilter) {
2128 log.trace("************* Going to associate all resource node filters {}", yamlName);
2129 if (MapUtils.isNotEmpty(nodeFilter)) {
2130 StorageOperationStatus status = componentNodeFilterBusinessLogic.associateNodeFilterToComponentInstance(service.getUniqueId(),
2132 if (status != StorageOperationStatus.OK) {
2133 throw new ComponentException(
2134 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2139 public void associateComponentInstancePropertiesToComponent(String yamlName, Service service,
2140 Map<String, List<ComponentInstanceProperty>> instProperties) {
2141 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2142 .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2143 if (addPropToInst.isRight()) {
2144 throw new ComponentException(
2145 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2149 public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
2150 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2151 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
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 associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2159 StorageOperationStatus addArtToInst;
2160 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2161 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2162 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2163 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2167 public void associateOrAddCalculatedCapReq(String yamlName, Service resource,
2168 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2169 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2170 StorageOperationStatus addArtToInst;
2171 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
2172 log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
2173 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2174 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2175 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2179 public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
2180 Map<String, List<AttributeDefinition>> instAttributes) {
2181 StorageOperationStatus addArtToInst;
2182 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
2183 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2184 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2185 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2189 public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2190 StorageOperationStatus addReqToService;
2191 addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
2192 if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2193 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
2194 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2198 public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
2199 StorageOperationStatus addCapToService;
2200 addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
2201 if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2202 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
2203 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2207 public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2208 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2209 .associateResourceInstances(service, service.getUniqueId(), relations);
2210 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2211 StorageOperationStatus status = relationsEither.right().value();
2212 log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
2213 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2217 public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2218 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
2219 originCapabilities.put(type, list);
2222 public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2223 for (UploadCapInfo capability : capabilities) {
2224 if (isNotEmpty(capability.getProperties())) {
2225 newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
2230 public Service getServiceWithGroups(String resourceId) {
2231 ComponentParametersView filter = new ComponentParametersView();
2232 filter.setIgnoreGroups(false);
2233 Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2234 if (updatedResource.isRight()) {
2235 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2237 return updatedResource.left().value();
2240 public Resource getResourceWithGroups(String resourceId) {
2241 ComponentParametersView filter = new ComponentParametersView();
2242 filter.setIgnoreGroups(false);
2243 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2244 if (updatedResource.isRight()) {
2245 serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2247 return updatedResource.left().value();
2250 public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2251 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
2252 .associateResourceInstances(resource, resource.getUniqueId(), relations);
2253 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2254 StorageOperationStatus status = relationsEither.right().value();
2255 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
2256 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2260 public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2261 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2262 for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2263 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2264 ComponentInstance currentCompInstance = null;
2265 for (ComponentInstance compInstance : componentInstancesList) {
2266 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2267 currentCompInstance = compInstance;
2271 if (currentCompInstance == null) {
2272 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
2273 BeEcompErrorManager.getInstance()
2274 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
2275 BeEcompErrorManager.ErrorSeverity.ERROR);
2276 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2277 throw new ComponentException(responseFormat);
2279 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2280 if (addRelationToRiRes.getStatus() != 200) {
2281 throw new ComponentException(addRelationToRiRes);
2286 protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
2287 List<RequirementCapabilityRelDef> relations) {
2288 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2289 ComponentInstance currentCompInstance = null;
2290 for (ComponentInstance compInstance : componentInstancesList) {
2291 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2292 currentCompInstance = compInstance;
2296 if (currentCompInstance == null) {
2297 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
2298 BeEcompErrorManager.getInstance()
2299 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
2300 BeEcompErrorManager.ErrorSeverity.ERROR);
2301 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2303 String resourceInstanceId = currentCompInstance.getUniqueId();
2304 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2305 if (regMap != null) {
2306 Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2307 while (nodesRegValue.hasNext()) {
2308 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2309 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2310 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2311 log.debug("Going to create relation {}", uploadRegInfo.getName());
2312 String regName = uploadRegInfo.getName();
2313 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2314 regCapRelDef.setFromNode(resourceInstanceId);
2315 log.debug("try to find available requirement {} ", regName);
2316 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAvailableRequirement(regName, yamlName, nodesInfoValue,
2317 currentCompInstance, uploadRegInfo.getCapabilityName());
2318 if (eitherReqStatus.isRight()) {
2319 return eitherReqStatus.right().value();
2321 RequirementDefinition validReq = eitherReqStatus.left().value();
2322 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2323 if (reqAndRelationshipPairList == null) {
2324 reqAndRelationshipPairList = new ArrayList<>();
2326 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2327 reqAndRelationshipPair.setRequirement(regName);
2328 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2329 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2330 RelationshipImpl relationship = new RelationshipImpl();
2331 relationship.setType(validReq.getCapability());
2332 reqAndRelationshipPair.setRelationships(relationship);
2333 ComponentInstance currentCapCompInstance = null;
2334 for (ComponentInstance compInstance : componentInstancesList) {
2335 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2336 currentCapCompInstance = compInstance;
2340 if (currentCapCompInstance == null) {
2341 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
2342 BeEcompErrorManager.getInstance()
2343 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
2344 BeEcompErrorManager.ErrorSeverity.ERROR);
2345 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2347 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2348 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2349 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2350 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2351 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2352 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2353 if (aviableCapForRel == null) {
2354 BeEcompErrorManager.getInstance().logInternalDataError(
2355 "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2356 .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2357 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2359 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2360 capReqRel.setRelation(reqAndRelationshipPair);
2361 reqAndRelationshipPairList.add(capReqRel);
2362 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2363 relations.add(regCapRelDef);
2366 } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2367 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2369 return componentsUtils.getResponseFormat(ActionStatus.OK);