datatypes.Constants:
[sdc.git] / openecomp-be / lib / openecomp-tosca-converter-lib / openecomp-tosca-converter-core / src / main / java / org / openecomp / core / impl / ToscaConverterUtil.java
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.openecomp.core.converter.errors.CreateToscaObjectErrorBuilder;
21 import org.openecomp.sdc.common.errors.CoreException;
22 import org.openecomp.sdc.common.utils.CommonUtil;
23
24 import java.util.*;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27
28 public class ToscaConverterUtil {
29
30   private static final String DEFAULT = "default";
31   private static final String DEFAULT_CAPITAL = "Default";
32   private static final Set<String> DEFAULT_VALUE_KEYS;
33
34   static {
35     DEFAULT_VALUE_KEYS =
36         Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet());
37   }
38
39   private ToscaConverterUtil() {
40     // static utility methods only, prevent instantiation
41   }
42
43   static <T> Optional<T> createObjectFromClass(String objectId,
44                                                Object objectCandidate,
45                                                Class<T> classToCreate) {
46     try {
47       return CommonUtil.createObjectUsingSetters(objectCandidate, classToCreate);
48     } catch (Exception ex) {
49       throw new CoreException(
50           new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId)
51               .build(), ex);
52     }
53   }
54
55
56   static Optional<Object> getDefaultValue(Object entryValue,
57                                        Object objectToAssignDefaultValue) {
58     if (!(entryValue instanceof Map)
59         || Objects.isNull(objectToAssignDefaultValue)) {
60       return Optional.empty();
61     }
62
63     return Optional.ofNullable(getDefaultParameterValue((Map<String, Object>) entryValue));
64   }
65
66   private static Object getDefaultParameterValue(Map<String, Object> entryValue) {
67     Object defaultValue = null;
68     Set<String> keys = new HashSet<>(entryValue.keySet());
69     keys.retainAll(DEFAULT_VALUE_KEYS);
70
71     if (CollectionUtils.isNotEmpty(keys)) {
72       defaultValue = entryValue.get(keys.iterator().next());
73     }
74
75     return defaultValue;
76   }
77 }