Policies import when import VSP
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / PolicyExportParserImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.tosca;
22
23
24 import fj.data.Either;
25 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
26 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
27 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
28 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
29 import org.openecomp.sdc.be.model.Component;
30 import org.openecomp.sdc.be.model.ComponentInstance;
31 import org.openecomp.sdc.be.model.DataTypeDefinition;
32 import org.openecomp.sdc.be.model.GroupDefinition;
33 import org.openecomp.sdc.be.model.PolicyDefinition;
34 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
35 import org.openecomp.sdc.be.tosca.model.IToscaMetadata;
36 import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
37 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
38 import org.openecomp.sdc.common.log.wrappers.Logger;
39 import org.springframework.beans.factory.annotation.Autowired;
40
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.function.Supplier;
46 import java.util.stream.Collectors;
47 import org.springframework.context.event.EventListener;
48
49 import static org.apache.commons.collections.CollectionUtils.isEmpty;
50 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
51 import static org.apache.commons.collections.MapUtils.isNotEmpty;
52 import static org.apache.commons.lang.StringUtils.isNotEmpty;
53
54 @org.springframework.stereotype.Component
55 public class PolicyExportParserImpl implements PolicyExportParser {
56
57         private static final Logger log = Logger.getLogger(PolicyExportParserImpl.class);
58    
59         private ApplicationDataTypeCache dataTypeCache;
60         private Map<String, DataTypeDefinition> dataTypes;
61         private PropertyConvertor propertyConvertor;
62         
63         @Autowired
64         public PolicyExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) {
65                 this.dataTypeCache = dataTypeCache;
66                 this.propertyConvertor = propertyConvertor;
67                 this.dataTypes = getDataTypes();
68         }
69         
70         private Map<String, DataTypeDefinition> getDataTypes()  {
71                 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
72                 if (dataTypesEither.isRight()) {
73                         log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); 
74                         throw new SdcResourceNotFoundException(); 
75                 }
76                 
77                 return dataTypesEither.left().value();
78         }
79
80         @EventListener
81         public void onDataTypesCacheChangedEvent(
82                         ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
83                 dataTypes = dataTypesCacheChangedEvent.getNewData();
84                 log.debug("Data types cache updated.");
85         }
86         
87         @Override
88         public Map<String, ToscaPolicyTemplate> getPolicies(Component component) {
89                 Map<String, ToscaPolicyTemplate> toscaPolicies = null;
90                 Map<String, PolicyDefinition> policies = component.getPolicies();               
91                 if (isNotEmpty(policies)) {
92
93                          toscaPolicies = policies.values().stream().collect(
94                                          Collectors.toMap(
95                                                          PolicyDefinition::getName,
96                                                          policy->getToscaPolicyTemplate(policy,component)));
97                         log.debug("policies converted");
98                 }       
99                 return toscaPolicies;   
100         }
101         
102         private ToscaPolicyTemplate getToscaPolicyTemplate(PolicyDefinition policyDefinition,Component component) {
103                 
104                  String type = policyDefinition.getPolicyTypeName();
105              IToscaMetadata metadata = getToscaPolicyTemplateMetadata(policyDefinition);
106              Map<String, Object> properties = getToscaPolicyTemplateProperties(policyDefinition);
107              List<String> targets = getToscaPolicyTemplateTargets(
108                          policyDefinition,component.getComponentInstances(),component.getGroups());
109                                 
110                 return new ToscaPolicyTemplate(type, metadata, properties, targets);
111         }
112         
113         private List<String> getToscaPolicyTemplateTargets(PolicyDefinition policyDefinition,
114                         List<ComponentInstance> componentInstances, List<GroupDefinition> groups) {
115
116                 Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
117                 List<String> targetNames = null;
118
119                 if (targets == null || targets.isEmpty()) {
120                         return null;
121                 }
122
123                 List<String> componentInstancesTargets = targets.get(PolicyTargetType.COMPONENT_INSTANCES);
124                 List<String> groupTargets = targets.get(PolicyTargetType.GROUPS);
125                 
126                 if (isNotEmpty(componentInstancesTargets) && isNotEmpty(componentInstances)) {  
127                         // get target names by Id from component instances
128                         Map<String, String> targetNamesByIdFromComponentInstances = 
129                                         getTargetNamesByIdFromComponentInstances(componentInstances);
130                         targetNames = targetNamesLazyInstantiation(targetNames);
131                         addTargetNames(componentInstancesTargets, targetNames, targetNamesByIdFromComponentInstances);
132                         
133                 }
134                 
135                 if (isNotEmpty(groupTargets) && isNotEmpty(groups)) {
136                         // get target names by id from group definitions
137                         Map<String, String> targetNamesByIdFromGroupDefinitions = getTargetNamesByIdFromGroupDefinitions(groups);
138                         targetNames = targetNamesLazyInstantiation(targetNames);
139                         addTargetNames(groupTargets, targetNames, targetNamesByIdFromGroupDefinitions);
140                         
141                 }
142
143                 return targetNames;
144         }
145
146         private List<String> targetNamesLazyInstantiation(List<String> targetNames) {
147                 if (targetNames == null) {
148                         targetNames = new ArrayList<>();
149                 }
150                 return targetNames;
151         }
152
153         private void addTargetNames(List<String> targets, List<String> targetNames,
154                         Map<String, String> targetNamesById) {
155                 
156                 if (!targetNamesById.isEmpty()) {
157                         
158                         for (String id : targets) {
159                                 String name = targetNamesById.get(id);
160                                 if (name != null) {
161                                         targetNames.add(name);
162                                 }
163                         }
164                 }
165         }
166
167         private Map<String, String> getTargetNamesByIdFromGroupDefinitions(List<GroupDefinition> groups) {      
168                 return groups.stream().collect(
169                                 Collectors.toMap(GroupDefinition::getUniqueId, GroupDefinition::getName));              
170         }
171
172         private Map<String, String> getTargetNamesByIdFromComponentInstances(List<ComponentInstance> componentInstances) {
173                 return componentInstances.stream().collect(
174                                 Collectors.toMap(ComponentInstance::getUniqueId,ComponentInstance::getName));
175         }
176
177         private Map<String, Object> getToscaPolicyTemplateProperties(PolicyDefinition policyDefinition) {
178                 
179                 List<PropertyDataDefinition> tempProperties = policyDefinition.getProperties();
180                 
181                 if (isEmpty(tempProperties)) {
182                         return null;
183                 }
184                                 
185                 Map<String, Object> props = new HashMap<>();
186
187                 tempProperties.forEach(input -> 
188                         propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input))
189                 );
190
191                 if (props.isEmpty()) {
192                         return null;
193                 } else {
194                         return props;
195                 }       
196         }
197
198         private Supplier<String> getPropertyValue(PropertyDataDefinition propertyDataDefinition) {
199                 return () -> {
200                         if (isNotEmpty(propertyDataDefinition.getValue())) {
201                                 return propertyDataDefinition.getValue();
202                         } else {
203                                 return propertyDataDefinition.getDefaultValue();
204                         }
205                 };
206         }
207
208         private IToscaMetadata getToscaPolicyTemplateMetadata(PolicyDefinition policyDefinition) {
209                 IToscaMetadata metadata = new ToscaMetadata();
210                 metadata.setInvariantUUID(policyDefinition.getInvariantUUID());
211                 metadata.setUUID(policyDefinition.getPolicyUUID());
212                 metadata.setName(policyDefinition.getName());
213                 metadata.setVersion(policyDefinition.getVersion());
214                 return metadata;
215         }
216
217 }