2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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=========================================================
22 package org.openecomp.appc.util;
24 import java.lang.reflect.Array;
27 public class ObjectMapper {
29 private ObjectMapper() {
32 private static void dispatch(PathContext context, Object obj) {
38 final Class<?> cls = obj.getClass();
41 || String.class.isAssignableFrom(cls)
42 || Number.class.isAssignableFrom(cls)
43 || Boolean.class.isAssignableFrom(cls)) {
44 handlePrimitive(context, obj);
45 } else if (cls.isArray()) {
46 handleArray(context, obj);
47 } else if (Map.class.isAssignableFrom(cls)) {
48 handleMap(context, (Map<?, ?>) obj);
49 } else if (Iterable.class.isAssignableFrom(cls)) {
50 handleCollection(context, Iterable.class.cast(obj));
52 throw new IllegalArgumentException(obj.getClass().getName());
56 public static Map<String, String> map(Object obj) {
57 PathContext context = new PathContext();
58 dispatch(context, obj);
59 return context.entries();
62 private static void handleMap(PathContext context, Map<?, ?> val) {
63 for (Map.Entry<?, ?> entry : val.entrySet()) {
64 context.pushToken(entry.getKey().toString());
65 dispatch(context, entry.getValue());
70 private static void handleCollection(PathContext context, Iterable<?> val) {
72 for (Object elem : val) {
73 handleElement(context, index++, elem);
77 private static void handleArray(PathContext context, Object val) {
78 for (int i = 0, n = Array.getLength(val); i < n; i++) {
79 handleElement(context, i, Array.get(val, i));
83 private static void handleElement(PathContext context, int index, Object val) {
88 String modifier = new StringBuilder().append('[').append(Integer.valueOf(index)).append(']').toString();
90 context.pushModifier(modifier);
91 dispatch(context, val);
92 context.popModifier();
95 private static void handlePrimitive(PathContext context, Object val) {
96 context.entry(context.getPath(), val.toString());