push addional code
[sdc.git] / openecomp-be / lib / openecomp-heat-lib / src / main / java / org / openecomp / sdc / heat / services / HeatStructureUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.heat.services;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.collections4.MapUtils;
25 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
26 import org.openecomp.core.validation.errors.Messages;
27 import org.openecomp.core.validation.types.GlobalValidationContext;
28 import org.openecomp.sdc.datatypes.error.ErrorLevel;
29 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
30 import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
31 import org.openecomp.sdc.heat.datatypes.model.PropertiesMapKeyTypes;
32 import org.openecomp.sdc.heat.datatypes.model.Resource;
33 import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions;
34
35 import java.util.Collection;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Objects;
40 import java.util.Set;
41
42 /**
43  * The type Heat structure util.
44  */
45 public class HeatStructureUtil {
46
47   /**
48    * Gets nested files.
49    *
50    * @param filename      the filename
51    * @param hot           the hot
52    * @param globalContext the global context
53    * @return the nested files
54    */
55   public static Set<String> getNestedFiles(String filename, HeatOrchestrationTemplate hot,
56                                            GlobalValidationContext globalContext) {
57
58     Set<String> nestedFileList = new HashSet<>();
59     Set<String> resourceDefNestedFiles;
60     hot.getResources().values().stream().filter(
61         resource -> (resource.getType().endsWith(".yaml") || resource.getType().endsWith(".yml")))
62         .forEach(resource -> nestedFileList.add(resource.getType()));
63
64     resourceDefNestedFiles = getResourceDefNestedFiles(filename, hot, globalContext);
65     nestedFileList.addAll(resourceDefNestedFiles);
66
67     return nestedFileList;
68   }
69
70
71   private static Set<String> getResourceDefNestedFiles(String filename,
72                                                        HeatOrchestrationTemplate hot,
73                                                        GlobalValidationContext globalContext) {
74     Set<String> resourceDefNestedFiles = new HashSet<>();
75     hot.getResources()
76         .entrySet()
77         .stream()
78         .filter(entry -> entry.getValue().getType()
79             .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()))
80         .filter(entry ->
81             getResourceDef(filename, entry.getKey(), entry.getValue(), globalContext) != null
82                 && isNestedResource(
83                     getResourceDef(filename, entry.getKey(), entry.getValue(), globalContext)
84                         .getType()))
85         .forEach(entry -> resourceDefNestedFiles.add(
86             getResourceDef(filename, entry.getKey(), entry.getValue(), globalContext).getType()));
87
88     return resourceDefNestedFiles;
89   }
90
91
92   /**
93    * Gets resource def.
94    *
95    * @param filename      the filename
96    * @param resourceName  the resource name
97    * @param resource      the resource
98    * @param globalContext the global context
99    * @return the resource def
100    */
101   @SuppressWarnings("unchecked")
102   public static Resource getResourceDef(String filename, String resourceName, Resource resource,
103                                         GlobalValidationContext globalContext) {
104     Resource resourceDef = null;
105     Map<String, Object> resourceDefValueMap = resource.getProperties() == null ? null
106         : (Map<String, Object>) resource.getProperties()
107             .get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
108     if (MapUtils.isNotEmpty(resourceDefValueMap)) {
109       Object resourceDefType = resourceDefValueMap.get("type");
110       if (Objects.nonNull(resourceDefType)) {
111         if (resourceDefType instanceof String) {
112           boolean isNested =
113               checkIfResourceGroupTypeIsNested(filename, resourceName, (String) resourceDefType,
114                   globalContext);
115           if (isNested) {
116             resourceDef = new Resource();
117             resourceDef.setType((String) resourceDefType);
118             //noinspection unchecked
119             resourceDef.setProperties((Map<String, Object>) resourceDefValueMap.get("properties"));
120           }
121         } else {
122           globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
123               .getErrorWithParameters(Messages.INVALID_RESOURCE_GROUP_TYPE.getErrorMessage(),
124                   resourceName, resourceDefType.toString()));
125         }
126       } else {
127         globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
128             .getErrorWithParameters(Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null",
129                 resourceName));
130       }
131
132     }
133     return resourceDef;
134   }
135
136
137   /**
138    * Check if resource group type is nested boolean.
139    *
140    * @param filename        the filename
141    * @param resourceName    the resource name
142    * @param resourceDefType the resource def type
143    * @param globalContext   the global context
144    * @return the boolean
145    */
146   public static boolean checkIfResourceGroupTypeIsNested(String filename, String resourceName,
147                                                          String resourceDefType,
148                                                          GlobalValidationContext globalContext) {
149     if (!HeatStructureUtil.isNestedResource(resourceDefType)) {
150       globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
151           .getErrorWithParameters(Messages.INVALID_RESOURCE_GROUP_TYPE.getErrorMessage(),
152               resourceName, resourceDefType));
153       return false;
154     }
155     return true;
156   }
157
158   /**
159    * Gets artifact files.
160    *
161    * @param filename      the filename
162    * @param hot           the hot
163    * @param globalContext the global context
164    * @return the artifact files
165    */
166   public static Set<String> getArtifactFiles(String filename, HeatOrchestrationTemplate hot,
167                                              GlobalValidationContext globalContext) {
168     Set<String> artifactSet = new HashSet<>();
169     Collection<Resource> resourcesValue =
170         hot.getResources() == null ? null : hot.getResources().values();
171     if (CollectionUtils.isNotEmpty(resourcesValue)) {
172       for (Resource resource : resourcesValue) {
173         Collection<Object> properties =
174             resource.getProperties() == null ? null : resource.getProperties().values();
175         if (CollectionUtils.isNotEmpty(properties)) {
176           for (Object property : properties) {
177             Set<String> artifactNames =
178                 getReferencedValuesByFunctionName(filename, "get_file", property, globalContext);
179             artifactSet.addAll(artifactNames);
180           }
181         }
182       }
183     }
184     return artifactSet;
185   }
186
187   /**
188    * Gets referenced values by function name.
189    *
190    * @param filename      the filename
191    * @param functionName  the function name
192    * @param propertyValue the property value
193    * @param globalContext the global context
194    * @return the referenced values by function name
195    */
196   public static Set<String> getReferencedValuesByFunctionName(String filename, String functionName,
197                                                Object propertyValue,
198                                                GlobalValidationContext globalContext) {
199     Set<String> valuesNames = new HashSet<>();
200     if (propertyValue instanceof Map) {
201       Map<String, Object> currPropertyMap = (Map<String, Object>) propertyValue;
202       if (currPropertyMap.containsKey(functionName)) {
203         Object getFunctionValue = currPropertyMap.get(functionName);
204         if (!(getFunctionValue instanceof String)
205             && functionName.equals(ResourceReferenceFunctions.GET_RESOURCE.getFunction())) {
206           globalContext.addMessage(filename, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
207               .getErrorWithParameters(Messages.INVALID_GET_RESOURCE_SYNTAX.getErrorMessage(),
208                   getFunctionValue == null ? "null" : getFunctionValue.toString()));
209           return valuesNames;
210         }
211         if (getFunctionValue instanceof String) {
212
213           if (functionName.equals(ResourceReferenceFunctions.GET_FILE.getFunction())) {
214             getFunctionValue = ((String) getFunctionValue).replace("file:///", "");
215           }
216
217           valuesNames.add((String) getFunctionValue);
218         } else if (getFunctionValue instanceof List) {
219           if (CollectionUtils.isNotEmpty((List) getFunctionValue)) {
220             if (((List) getFunctionValue).get(0) instanceof String) {
221               valuesNames.add(((String) ((List) getFunctionValue).get(0)).replace("file:///", ""));
222             } else {
223               valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName,
224                   ((List) getFunctionValue).get(0), globalContext));
225             }
226
227           }
228         } else {
229           valuesNames.addAll(
230               getReferencedValuesByFunctionName(filename, functionName, getFunctionValue,
231                   globalContext));
232         }
233       } else {
234         for (Map.Entry<String, Object> nestedPropertyMap : currPropertyMap.entrySet()) {
235           valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName,
236               nestedPropertyMap.getValue(), globalContext));
237         }
238       }
239     } else if (propertyValue instanceof List) {
240       List propertyValueArray = (List) propertyValue;
241       for (Object propertyValueArrayInstance : propertyValueArray) {
242         valuesNames.addAll(
243             getReferencedValuesByFunctionName(filename, functionName, propertyValueArrayInstance,
244                 globalContext));
245       }
246     }
247
248     return valuesNames;
249   }
250
251
252   /**
253    * Is nested resource boolean.
254    *
255    * @param resourceType the resource type
256    * @return the boolean
257    */
258   public static boolean isNestedResource(String resourceType) {
259     return resourceType.endsWith(".yaml") || resourceType.endsWith(".yml");
260   }
261 }