Catalog alignment
[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 import org.springframework.stereotype.Service;
41
42 import java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.function.Supplier;
47 import java.util.stream.Collectors;
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 @Service
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 = PropertyConvertor.getInstance();
62         
63         @Autowired
64         public PolicyExportParserImpl(ApplicationDataTypeCache dataTypeCache) {
65                 this.dataTypeCache = dataTypeCache;
66                 this.dataTypes = getDataTypes();
67         }
68         
69         private Map<String, DataTypeDefinition> getDataTypes()  {
70                 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
71                 if (dataTypesEither.isRight()) {
72                         log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); 
73                         throw new SdcResourceNotFoundException(); 
74                 }
75                 
76                 return dataTypesEither.left().value();
77         }
78         
79         @Override
80         public Map<String, ToscaPolicyTemplate> getPolicies(Component component) {
81                 Map<String, ToscaPolicyTemplate> toscaPolicies = null;
82                 Map<String, PolicyDefinition> policies = component.getPolicies();               
83                 if (isNotEmpty(policies)) {
84
85                          toscaPolicies = policies.values().stream().collect(
86                                          Collectors.toMap(
87                                                          PolicyDefinition::getName,
88                                                          policy->getToscaPolicyTemplate(policy,component)));
89                         log.debug("policies converted");
90                 }       
91                 return toscaPolicies;   
92         }
93         
94         private ToscaPolicyTemplate getToscaPolicyTemplate(PolicyDefinition policyDefinition,Component component) {
95                 
96                  String type = policyDefinition.getPolicyTypeName();
97              IToscaMetadata metadata = getToscaPolicyTemplateMetadata(policyDefinition);
98              Map<String, Object> properties = getToscaPolicyTemplateProperties(policyDefinition);
99              List<String> targets = getToscaPolicyTemplateTargets(
100                          policyDefinition,component.getComponentInstances(),component.getGroups());
101                                 
102                 return new ToscaPolicyTemplate(type, metadata, properties, targets);
103         }
104         
105         private List<String> getToscaPolicyTemplateTargets(PolicyDefinition policyDefinition,
106                         List<ComponentInstance> componentInstances, List<GroupDefinition> groups) {
107
108                 Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
109                 List<String> targetNames = null;
110
111                 if (targets == null || targets.isEmpty()) {
112                         return null;
113                 }
114
115                 List<String> componentInstancesTargets = targets.get(PolicyTargetType.COMPONENT_INSTANCES);
116                 List<String> groupTargets = targets.get(PolicyTargetType.GROUPS);
117                 
118                 if (isNotEmpty(componentInstancesTargets) && isNotEmpty(componentInstances)) {  
119                         // get target names by Id from component instances
120                         Map<String, String> targetNamesByIdFromComponentInstances = 
121                                         getTargetNamesByIdFromComponentInstances(componentInstances);
122                         targetNames = targetNamesLazyInstantiation(targetNames);
123                         addTargetNames(componentInstancesTargets, targetNames, targetNamesByIdFromComponentInstances);
124                         
125                 }
126                 
127                 if (isNotEmpty(groupTargets) && isNotEmpty(groups)) {
128                         // get target names by id from group definitions
129                         Map<String, String> targetNamesByIdFromGroupDefinitions = getTargetNamesByIdFromGroupDefinitions(groups);
130                         targetNames = targetNamesLazyInstantiation(targetNames);
131                         addTargetNames(groupTargets, targetNames, targetNamesByIdFromGroupDefinitions);
132                         
133                 }
134
135                 return targetNames;
136         }
137
138         private List<String> targetNamesLazyInstantiation(List<String> targetNames) {
139                 if (targetNames == null) {
140                         targetNames = new ArrayList<>();
141                 }
142                 return targetNames;
143         }
144
145         private void addTargetNames(List<String> targets, List<String> targetNames,
146                         Map<String, String> targetNamesById) {
147                 
148                 if (!targetNamesById.isEmpty()) {
149                         
150                         for (String id : targets) {
151                                 String name = targetNamesById.get(id);
152                                 if (name != null) {
153                                         targetNames.add(name);
154                                 }
155                         }
156                 }
157         }
158
159         private Map<String, String> getTargetNamesByIdFromGroupDefinitions(List<GroupDefinition> groups) {      
160                 return groups.stream().collect(
161                                 Collectors.toMap(GroupDefinition::getUniqueId, GroupDefinition::getName));              
162         }
163
164         private Map<String, String> getTargetNamesByIdFromComponentInstances(List<ComponentInstance> componentInstances) {
165                 return componentInstances.stream().collect(
166                                 Collectors.toMap(ComponentInstance::getUniqueId,ComponentInstance::getName));
167         }
168
169         private Map<String, Object> getToscaPolicyTemplateProperties(PolicyDefinition policyDefinition) {
170                 
171                 List<PropertyDataDefinition> tempProperties = policyDefinition.getProperties();
172                 
173                 if (isEmpty(tempProperties)) {
174                         return null;
175                 }
176                                 
177                 Map<String, Object> props = new HashMap<>();
178
179                 tempProperties.forEach(input -> 
180                         propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input))
181                 );
182
183                 if (props.isEmpty()) {
184                         return null;
185                 } else {
186                         return props;
187                 }       
188         }
189
190         private Supplier<String> getPropertyValue(PropertyDataDefinition propertyDataDefinition) {
191                 return () -> {
192                         if (isNotEmpty(propertyDataDefinition.getValue())) {
193                                 return propertyDataDefinition.getValue();
194                         } else {
195                                 return propertyDataDefinition.getDefaultValue();
196                         }
197                 };
198         }
199
200         private IToscaMetadata getToscaPolicyTemplateMetadata(PolicyDefinition policyDefinition) {
201                 IToscaMetadata metadata = new ToscaMetadata();
202                 metadata.setInvariantUUID(policyDefinition.getInvariantUUID());
203                 metadata.setUUID(policyDefinition.getPolicyUUID());
204                 metadata.setName(policyDefinition.getName());
205                 metadata.setVersion(policyDefinition.getVersion());
206                 return metadata;
207         }
208
209 }