2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.appc.util;
25 import java.lang.reflect.Array;
28 public class ObjectMapper {
30 private ObjectMapper() {
33 private static void dispatch(PathContext context, Object obj) {
39 final Class<?> cls = obj.getClass();
42 || String.class.isAssignableFrom(cls)
43 || Number.class.isAssignableFrom(cls)
44 || Boolean.class.isAssignableFrom(cls)) {
45 handlePrimitive(context, obj);
46 } else if (cls.isArray()) {
47 handleArray(context, obj);
48 } else if (Map.class.isAssignableFrom(cls)) {
49 handleMap(context, (Map<?, ?>) obj);
50 } else if (Iterable.class.isAssignableFrom(cls)) {
51 handleCollection(context, Iterable.class.cast(obj));
53 throw new IllegalArgumentException(obj.getClass().getName());
57 public static Map<String, String> map(Object obj) {
58 PathContext context = new PathContext();
59 dispatch(context, obj);
60 return context.entries();
63 private static void handleMap(PathContext context, Map<?, ?> val) {
64 for (Map.Entry<?, ?> entry : val.entrySet()) {
65 context.pushToken(entry.getKey().toString());
66 dispatch(context, entry.getValue());
71 private static void handleCollection(PathContext context, Iterable<?> val) {
73 for (Object elem : val) {
74 handleElement(context, index++, elem);
78 private static void handleArray(PathContext context, Object val) {
79 for (int i = 0, n = Array.getLength(val); i < n; i++) {
80 handleElement(context, i, Array.get(val, i));
84 private static void handleElement(PathContext context, int index, Object val) {
89 String modifier = new StringBuilder().append('[').append(Integer.valueOf(index)).append(']').toString();
91 context.pushModifier(modifier);
92 dispatch(context, val);
93 context.popModifier();
96 private static void handlePrimitive(PathContext context, Object val) {
97 context.entry(context.getPath(), val.toString());