All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.predic8.membrane.core.kubernetes.GenericJsonParser Maven / Gradle / Ivy

There is a newer version: 5.7.3
Show newest version
/* Copyright 2009, 2021 predic8 GmbH, www.predic8.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */
package com.predic8.membrane.core.kubernetes;

import com.predic8.membrane.annot.MCAttribute;
import com.predic8.membrane.annot.MCChildElement;
import com.predic8.membrane.core.config.spring.K8sHelperGeneratorAutoGenerated;
import org.jose4j.json.internal.json_simple.JSONArray;
import org.jose4j.json.internal.json_simple.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Creates and configures a router rule with json as described in {@link K8sHelperGeneratorAutoGenerated}
 */
public class GenericJsonParser {

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static  T parse(Class clazz, JSONObject json) {
        T obj = null;
        try {
            obj = clazz.newInstance();
            for (Object property : json.entrySet()) {
                Map.Entry entry = (Map.Entry) property;
                Method setter = getSetter(clazz, entry.getKey());

                Object toSetValue = entry.getValue();
                if (isStructured(setter)) {
                    if (isCollection(setter)) {
                        JSONArray collection = new JSONArray((Collection) toSetValue);
                        List coll = new ArrayList<>();
                        for (Object o : collection) {
                            JSONObject jo = new JSONObject((Map) o);
                            String key = (String) jo.keySet().stream()
                                    .findFirst()
                                    .orElseThrow(() -> new RuntimeException("Can't get key from " + jo));
                            JSONObject unwrapped = new JSONObject((Map) jo.get(key));
                            Class child = K8sHelperGeneratorAutoGenerated.elementMapping.get(key);
                            coll.add(parse(child, unwrapped));
                        }
                        toSetValue = coll;
                    } else {
                        Class childClass = K8sHelperGeneratorAutoGenerated.elementMapping.get(entry.getKey());
                        toSetValue = parse(childClass, new JSONObject((Map) json.get(entry.getKey())));
                    }
                }

                setSetter(obj, setter, toSetValue);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return obj;
    }

    private static  Method getSetter(Class clazz, String key) {
        return Arrays.stream(clazz.getMethods())
                .filter(GenericJsonParser::isSetter)
                .filter(method -> matchesJsonKey(method, key))
                .findFirst()
                .orElseThrow(() ->
                        new RuntimeException("Can't find method for key: " + key + " in " + clazz.getName()));
    }

    private static  void setSetter(T instance, Method method, Object value) throws InvocationTargetException, IllegalAccessException {
        method.invoke(instance, value);
    }

    private static boolean matchesJsonKey(Method method, String key) {
        return method.getName().substring(3).equalsIgnoreCase(key) || equalsAttributeName(method, key);
    }

    private static boolean isCollection(Method method) {
        return Arrays.asList(method.getParameterTypes()).contains(List.class);
    }

    private static boolean equalsAttributeName(Method method, String key) {
        if (!method.isAnnotationPresent(MCAttribute.class))
            return false;
        return method.getAnnotation(MCAttribute.class).attributeName().equals(key);
    }

    private static boolean isStructured(Method method) {
        return method.isAnnotationPresent(MCChildElement.class);
    }

    private static boolean isSetter(Method method) {
        return method.getName().startsWith("set");
    }
}