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

org.bdware.doip.cluster.engine.JavaUtil Maven / Gradle / Ivy

The newest version!
package org.bdware.doip.cluster.engine;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.cluster.util.JSONTool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaUtil {

    private JavaUtil(){}

    private static Map classNameMap = new HashMap<>();
    static {
        classNameMap.put("DoipMessage", "org.bdware.doip.codec.doipMessage.DoipMessage");
    }

    static Logger LOGGER = LogManager.getLogger(JavaUtil.class);

    public static Object[] toJavaArray(ScriptObjectMirror som, String elementType) {
        if (som == null) {
            return null;
        }
        try{
            JsonArray jsArray = JSONTool.convertMirrorToJson(som).getAsJsonArray();
            Object[] javaArray = (Object[]) java.lang.reflect.Array.newInstance(getClassName(elementType), jsArray.size());

            for (int i = 0; i < jsArray.size(); i++) {
                JsonObject jo = jsArray.get(i).getAsJsonObject();
                Object convertedObject = convertJsonObjectToType(jo, getClassName(elementType));
                javaArray[i] = convertedObject;
            }
            return javaArray;
        }catch (ClassNotFoundException e){
            return null;
        }
    }

    // Implement this method to get Class from class name string
    private static Class getClassName(String className) throws ClassNotFoundException {
        return Class.forName(classNameMap.get(className));
    }
    private static   T convertJsonObjectToType(JsonObject jsonObject, Class targetType) {
        return new Gson().fromJson(jsonObject,targetType);
    }


    public static List createList(){
        return new ArrayList<>();
    }

}