2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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 * ============LICENSE_END=========================================================
16 * Modifications copyright (c) 2019 Nokia
17 * ================================================================================
20 package org.openecomp.sdc.externalupload.utils;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.google.common.collect.ImmutableSet;
25 import java.lang.reflect.Field;
27 import org.onap.sdc.tosca.services.CommonUtil;
29 public class ServiceUtils {
31 private static ImmutableSet<Class> collectionClasses = ImmutableSet.of(Map.class, List.class, Set.class);
32 private static ImmutableSet<Class> primitiveTypesClasses = ImmutableSet.of(String.class, Integer.class, Double.class, Float.class);
34 private ServiceUtils() {}
36 public static <T> Optional<T> createObjectUsingSetters(Object objectCandidate,
37 Class<T> classToCreate)
39 if (Objects.isNull(objectCandidate)) {
40 return Optional.empty();
43 Map<String, Object> objectAsMap = getObjectAsMap(objectCandidate);
45 List<Field> declaredFields = getAllFields(classToCreate);
47 CommonUtil.createSubObjectsUsingSetters(objectAsMap, declaredFields.toArray(new Field[0]));
48 T result = CommonUtil.populateBean(objectAsMap, classToCreate);
50 return Optional.of(result);
53 private static <T> List<Field> getAllFields(Class<T> clazz) {
54 List<Field> fields = new ArrayList<>();
55 for(Class<?> c = clazz; c != null; c = c.getSuperclass()) {
56 fields.addAll(Arrays.asList(c.getDeclaredFields()));
62 private static boolean isComplexClass(Field field) {
63 return !isCollectionClass(field)
64 && !isPrimitiveClass(field)
65 && !field.getType().equals(Object.class);
68 private static boolean isCollectionClass(Field field) {
69 return collectionClasses.contains(field.getType());
72 private static boolean isPrimitiveClass(Field field) {
73 return primitiveTypesClasses.contains(field.getType());
76 public static Map<String, Object> getObjectAsMap(Object obj) {
77 return new ObjectMapper().convertValue(obj, Map.class);
80 public static Set<String> getClassFieldNames(Class<? extends Object> classType) {
81 Set<String> fieldNames = new HashSet<>();
82 List<Field> allFields = getAllFields(classType);
83 allFields.forEach(field -> fieldNames.add(field.getName()));