2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
20 package org.onap.so.aaisimulator.utils;
22 import java.lang.reflect.Method;
23 import java.util.HashMap;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * @author Waqas Ikram (waqas.ikram@est.tech)
34 public class ShallowBeanCopy {
35 private static final Logger LOGGER = LoggerFactory.getLogger(ShallowBeanCopy.class);
37 private ShallowBeanCopy() {}
39 public static void copy(final Object from, final Object to) throws Exception {
40 final Map<String, Method> fromMethods = getMethods(from);
41 final Map<String, Method> toMethods = getMethods(to);
43 for (final Entry<String, Method> entry : fromMethods.entrySet()) {
44 final String methodName = entry.getKey();
45 final Method fromMethod = entry.getValue();
47 final Optional<Method> optional = getSetMethod(to, fromMethod);
48 if (optional.isPresent()) {
49 final Method toGetMethod = toMethods.get(methodName);
50 final Method toMethod = optional.get();
51 final Object toValue = fromMethod.invoke(from);
53 final Object fromValue = toGetMethod.invoke(to);
54 if (toValue != null && !toValue.equals(fromValue)) {
55 LOGGER.info("Changing {} value from: {} to: {}", methodName, fromValue, toValue);
56 toMethod.invoke(to, toValue);
63 private static Optional<Method> getSetMethod(final Object to, final Method fromMethod) {
64 final String name = fromMethod.getName().replaceFirst("get|is", "set");
65 final Class<?> returnType = fromMethod.getReturnType();
67 return Optional.of(to.getClass().getMethod(name, returnType));
68 } catch (final NoSuchMethodException noSuchMethodException) {
70 return Optional.empty();
73 private static Map<String, Method> getMethods(final Object object) {
74 final Map<String, Method> methodsFound = new HashMap<>();
75 final Method[] methods = object.getClass().getMethods();
77 for (final Method method : methods) {
78 if (method.getName().startsWith("get") || method.getName().startsWith("is")) {
79 final String name = method.getName().replaceFirst("get|is", "");
81 methodsFound.put(name, method);