1 package org.openecomp.core.impl;
3 import org.apache.commons.collections4.CollectionUtils;
4 import org.apache.commons.lang.StringUtils;
5 import org.openecomp.core.converter.errors.CreateToscaObjectErrorBuilder;
6 import org.openecomp.sdc.common.errors.CoreException;
8 import java.lang.reflect.Field;
9 import java.util.HashSet;
11 import java.util.Objects;
12 import java.util.Optional;
14 import java.util.stream.Collectors;
15 import java.util.stream.Stream;
17 public class ToscaConverterUtil {
18 private static final String SET = "set";
19 private static final String DEFAULT = "default";
20 private static final String DEFAULT_CAPITAL = "Default";
21 private static Set<String> defaultValueKeys;
25 Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet());
28 public static <T> Optional<T> createObjectFromClass(String objectId,
29 Object objectCandidate,
30 Class<T> classToCreate) {
32 return createObjectUsingSetters(objectCandidate, classToCreate);
33 } catch (Exception e) {
34 throw new CoreException(
35 new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId, e.getMessage())
40 private static <T> Optional<T> createObjectUsingSetters(Object objectCandidate,
41 Class<T> classToCreate) throws Exception {
42 if (Objects.isNull(objectCandidate)
43 || !(objectCandidate instanceof Map)) {
44 return Optional.empty();
47 Map<String, Object> objectAsMap = (Map<String, Object>) objectCandidate;
48 Field[] classFields = classToCreate.getDeclaredFields();
49 T result = classToCreate.newInstance();
51 for (Field field : classFields) {
52 Object fieldValueToAssign = objectAsMap.get(field.getName());
53 String methodName = SET + StringUtils.capitalize(field.getName());
55 if(shouldSetterMethodNeedsToGetInvoked(classToCreate, field, fieldValueToAssign, methodName)) {
56 classToCreate.getMethod(methodName, field.getType()).invoke(result, fieldValueToAssign);
60 return Optional.of(result);
62 private static <T> boolean shouldSetterMethodNeedsToGetInvoked(Class<T> classToCreate,
64 Object fieldValueToAssign,
68 return Objects.nonNull(fieldValueToAssign)
69 && Objects.nonNull(classToCreate.getMethod(methodName, field.getType()));
70 } catch (NoSuchMethodException e) {
75 public static Optional<Object> getDefaultValue(Object entryValue,
76 Object objectToAssignDefaultValue) {
77 if (!(entryValue instanceof Map)
78 || Objects.isNull(objectToAssignDefaultValue)) {
79 return Optional.empty();
82 return Optional.ofNullable(getDefaultParameterValue((Map<String, Object>) entryValue));
85 private static Object getDefaultParameterValue(Map<String, Object> entryValue) {
86 Object defaultValue = null;
87 Set<String> keys = new HashSet<>(entryValue.keySet());
88 keys.retainAll(defaultValueKeys);
90 if (CollectionUtils.isNotEmpty(keys)) {
91 defaultValue = entryValue.get(keys.iterator().next());