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