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