802827e34351aa81e63e0505217fa7971f6a3113
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.openecomp.core.impl;
18
19 import org.apache.commons.collections4.CollectionUtils;
20 import org.apache.commons.lang.StringUtils;
21 import org.openecomp.core.converter.errors.CreateToscaObjectErrorBuilder;
22 import org.openecomp.sdc.common.errors.CoreException;
23 import org.openecomp.sdc.logging.api.Logger;
24 import org.openecomp.sdc.logging.api.LoggerFactory;
25
26 import java.lang.reflect.Field;
27 import java.util.HashSet;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.stream.Collectors;
33 import java.util.stream.Stream;
34
35 public class ToscaConverterUtil {
36
37   private static final String SET = "set";
38   private static final String DEFAULT = "default";
39   private static final String DEFAULT_CAPITAL = "Default";
40   private static final Set<String> DEFAULT_VALUE_KEYS;
41
42   private static final Logger LOGGER = LoggerFactory.getLogger(ToscaConverterUtil.class);
43
44   static {
45     DEFAULT_VALUE_KEYS =
46         Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet());
47   }
48
49   private ToscaConverterUtil() {
50     // static utility methods only, prevent instantiation
51   }
52
53   public static <T> Optional<T> createObjectFromClass(String objectId,
54                                                       Object objectCandidate,
55                                                       Class<T> classToCreate) {
56     try {
57       return createObjectUsingSetters(objectCandidate, classToCreate);
58     } catch (Exception ex) {
59       throw new CoreException(
60           new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId)
61               .build(), ex);
62     }
63   }
64
65   private static <T> Optional<T> createObjectUsingSetters(Object objectCandidate,
66                                                           Class<T> classToCreate)
67           throws ReflectiveOperationException {
68     if (Objects.isNull(objectCandidate)
69         || !(objectCandidate instanceof Map)) {
70       return Optional.empty();
71     }
72
73     Map<String, Object> objectAsMap = (Map<String, Object>) objectCandidate;
74     Field[] classFields = classToCreate.getDeclaredFields();
75     T result = classToCreate.newInstance();
76
77     for (Field field : classFields) {
78       Object fieldValueToAssign = objectAsMap.get(field.getName());
79       String methodName = SET + StringUtils.capitalize(field.getName());
80
81       if(shouldSetterMethodNeedsToGetInvoked(classToCreate, field, fieldValueToAssign, methodName)) {
82         classToCreate.getMethod(methodName, field.getType()).invoke(result, fieldValueToAssign);
83       }
84     }
85
86     return Optional.of(result);
87   }
88   private static <T> boolean shouldSetterMethodNeedsToGetInvoked(Class<T> classToCreate,
89                                                                  Field field,
90                                                                  Object fieldValueToAssign,
91                                                                  String methodName) {
92
93     try {
94       return Objects.nonNull(fieldValueToAssign)
95           && Objects.nonNull(classToCreate.getMethod(methodName, field.getType()));
96     } catch (NoSuchMethodException e) {
97       LOGGER.debug(String.format("Could not extract method '%s' from class '%s'. returning false " +
98               "with filedType '%s'.", methodName, classToCreate, field.getType()), e);
99       return false;
100     }
101   }
102
103   public static Optional<Object> getDefaultValue(Object entryValue,
104                                        Object objectToAssignDefaultValue) {
105     if (!(entryValue instanceof Map)
106         || Objects.isNull(objectToAssignDefaultValue)) {
107       return Optional.empty();
108     }
109
110     return Optional.ofNullable(getDefaultParameterValue((Map<String, Object>) entryValue));
111   }
112
113   private static Object getDefaultParameterValue(Map<String, Object> entryValue) {
114     Object defaultValue = null;
115     Set<String> keys = new HashSet<>(entryValue.keySet());
116     keys.retainAll(DEFAULT_VALUE_KEYS);
117
118     if (CollectionUtils.isNotEmpty(keys)) {
119       defaultValue = entryValue.get(keys.iterator().next());
120     }
121
122     return defaultValue;
123   }
124 }