2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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 * ============LICENSE_END=========================================================
24 package org.onap.appc.util;
26 import java.lang.reflect.Array;
29 public class ObjectMapper {
31 private ObjectMapper() {
34 private static void dispatch(PathContext context, Object obj) {
40 final Class<?> cls = obj.getClass();
43 || String.class.isAssignableFrom(cls)
44 || Number.class.isAssignableFrom(cls)
45 || Boolean.class.isAssignableFrom(cls)) {
46 handlePrimitive(context, obj);
47 } else if (cls.isArray()) {
48 handleArray(context, obj);
49 } else if (Map.class.isAssignableFrom(cls)) {
50 handleMap(context, (Map<?, ?>) obj);
51 } else if (Iterable.class.isAssignableFrom(cls)) {
52 handleCollection(context, Iterable.class.cast(obj));
54 throw new IllegalArgumentException(obj.getClass().getName());
58 public static Map<String, String> map(Object obj) {
59 PathContext context = new PathContext();
60 dispatch(context, obj);
61 return context.entries();
64 private static void handleMap(PathContext context, Map<?, ?> val) {
65 for (Map.Entry<?, ?> entry : val.entrySet()) {
66 context.pushToken(entry.getKey().toString());
67 dispatch(context, entry.getValue());
72 private static void handleCollection(PathContext context, Iterable<?> val) {
74 for (Object elem : val) {
75 handleElement(context, index++, elem);
79 private static void handleArray(PathContext context, Object val) {
80 for (int i = 0, n = Array.getLength(val); i < n; i++) {
81 handleElement(context, i, Array.get(val, i));
85 private static void handleElement(PathContext context, int index, Object val) {
90 String modifier = new StringBuilder().append('[').append(Integer.valueOf(index)).append(']').toString();
92 context.pushModifier(modifier);
93 dispatch(context, val);
94 context.popModifier();
97 private static void handlePrimitive(PathContext context, Object val) {
98 context.entry(context.getPath(), val.toString());