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

com.aeontronix.enhancedmule.tools.util.JsonHelper Maven / Gradle / Ivy

There is a newer version: 2.0.0-alpha4
Show newest version
/*
 * Copyright (c) Aeontronix 2023
 */

package com.aeontronix.enhancedmule.tools.util;

import com.aeontronix.commons.StringUtils;
import com.aeontronix.enhancedmule.tools.anypoint.AnypointObject;
import com.aeontronix.enhancedmule.tools.anypoint.InvalidJsonException;
import com.aeontronix.enhancedmule.tools.anypoint.LegacyAnypointClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;

public class JsonHelper implements Serializable {
    private LegacyAnypointClient client;
    private ObjectMapper jsonMapper;

    public JsonHelper(LegacyAnypointClient client) {
        this.client = client;
    }

    public void init(HttpHelper httpHelper) {
        jsonMapper = createMapper();
        jsonMapper.setInjectableValues(new InjectableValues.Std()
                .addValue(JsonHelper.class, this)
                .addValue(HttpHelper.class, httpHelper)
                .addValue(LegacyAnypointClient.class, client));
    }

    public static void processVariables(ObjectNode json, HashMap vars) {
        LinkedList nodes = new LinkedList<>();
        nodes.add(json);
        while (!nodes.isEmpty()) {
            final JsonNode node = nodes.removeFirst();
            if (node != null && !node.isNull()) {
                if (node instanceof ObjectNode) {
                    final Iterator> fields = node.fields();
                    while (fields.hasNext()) {
                        Map.Entry field = fields.next();
                        final JsonNode n = field.getValue();
                        if (n instanceof TextNode) {
                            ((ObjectNode) node).replace(field.getKey(), new TextNode(StringUtils.substituteVariables(n.textValue(), vars)));
                        } else if (n instanceof ArrayNode) {
                            for (JsonNode children : node) {
                                nodes.addLast(children);
                            }
                        } else if (n instanceof ObjectNode) {
                            nodes.addLast(n);
                        }
                    }
                } else if (node instanceof ArrayNode) {
                    final int size = node.size();
                    for (int i = 0; i < size; i++) {
                        JsonNode child = node.get(i);
                        if (child instanceof TextNode) {
                            final TextNode replacement = new TextNode(StringUtils.substituteVariables(child.textValue(), vars));
                            ((ArrayNode) node).remove(i);
                            ((ArrayNode) node).insert(i, replacement);
                        } else {
                            nodes.addLast(child);
                        }
                    }
                    for (JsonNode children : node) {
                        nodes.addLast(children);
                    }
                }
            }
        }
    }

    public static Object getCaseInsensitive(ObjectNode node, String name) {
        final Iterator names = node.fieldNames();
        while (names.hasNext()) {
            String n = names.next();
            if(n.equalsIgnoreCase(name)) {
                return node.get(n);
            }
        }
        return null;
    }

    public LegacyAnypointClient getClient() {
        return client;
    }

    public void setClient(LegacyAnypointClient client) {
        this.client = client;
    }

    public ObjectMapper getJsonMapper() {
        return jsonMapper;
    }

    public byte[] toJson(Object obj) {
        try (ByteArrayOutputStream tmp = new ByteArrayOutputStream()) {
            jsonMapper.writeValue(tmp, obj);
            return tmp.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Map toJsonMap(String json) {
        try {
            return jsonMapper.readValue(json, new TypeReference>() {
            });
        } catch (IOException e) {
            throw new InvalidJsonException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public Map toJsonMap(JsonNode node) {
        try {
            return jsonMapper.treeToValue(node, Map.class);
        } catch (JsonProcessingException e) {
            throw new InvalidJsonException(e);
        }
    }

    public MapBuilder buildJsonMap() {
        return new MapBuilder();
    }

    public MapBuilder buildJsonMap(Map data) {
        return new MapBuilder(null, data);
    }

    public JsonNode readJsonTree(String json) {
        try {
            return jsonMapper.readTree(json);
        } catch (IOException e) {
            throw new InvalidJsonException(e);
        }
    }

    public  X readJson(X obj, String json, String jsonPath) {
        try {
            return readJson(obj, jsonMapper.readerForUpdating(obj).readTree(json).at(jsonPath));
        } catch (IOException e) {
            throw new InvalidJsonException(e);
        }
    }

    public  X readJson(X obj, String json) {
        return readJson(obj, json, (AnypointObject) null);
    }

    @SuppressWarnings("unchecked")
    public  X readJson(X obj, String json, AnypointObject parent) {
        try {
            jsonMapper.readerForUpdating(obj).readValue(json);
            if (obj instanceof AnypointObject) {
                ((AnypointObject) obj).setJson(json);
                if (parent != null) {
                    ((AnypointObject) obj).setParent(parent);
                }
            }
            return obj;
        } catch (IOException e) {
            throw new InvalidJsonException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public  X readJson(Class objClass, JsonNode node, AnypointObject parent) {
        try {
            Object obj = jsonMapper.treeToValue(node, objClass);
            if (obj instanceof AnypointObject) {
                ((AnypointObject) obj).setJson(node.toString());
                ((AnypointObject) obj).setParent(parent);
            }
            return (X) obj;
        } catch (JsonProcessingException e) {
            throw new InvalidJsonException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public  X readJson(Class objClass, JsonNode node, LegacyAnypointClient client) {
        try {
            Object obj = jsonMapper.treeToValue(node, objClass);
            return (X) obj;
        } catch (JsonProcessingException e) {
            throw new InvalidJsonException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public  List readJsonList(Class objClass, String json, AnypointObject parent) {
        return readJsonList(objClass, json, parent, null);
    }

    @SuppressWarnings("unchecked")
    public  List readJsonList(Class objClass, String json, AnypointObject parent, String path) {
        try {
            ArrayList list = new ArrayList<>();
            JsonNode node = jsonMapper.readTree(json);
            if (path != null) {
                node = node.at(path);
            }
            for (JsonNode n : node) {
                list.add(readJson(objClass, n, parent));
            }
            return list;
        } catch (IOException e) {
            throw new InvalidJsonException(e);
        }
    }

    public  X readJson(X obj, JsonNode node) {
        try {
            jsonMapper.readerForUpdating(obj).readValue(node);
            if (obj instanceof AnypointObject) {
                ((AnypointObject) obj).setJson(node.toString());
            }
            return obj;
        } catch (IOException e) {
            throw new InvalidJsonException(e);
        }
    }

    public class MapBuilder {
        private MapBuilder parent;
        private Map request;

        public MapBuilder() {
            request = new HashMap<>();
        }

        public MapBuilder(MapBuilder parent, Map request) {
            this.parent = parent;
            this.request = request;
        }

        public MapBuilder set(String key, Object value) {
            request.put(key, value);
            return this;
        }

        public MapBuilder setNested(String nestKey, String key, Object value) {
            HashMap nestedMap = new HashMap<>();
            nestedMap.put(key, value);
            request.put(nestKey, nestedMap);
            return this;
        }

        public Map toMap() {
            if (parent != null) {
                return parent.toMap();
            } else {
                return request;
            }
        }

        public MapBuilder addMap(String name) {
            HashMap subMap = new HashMap<>();
            request.put(name, subMap);
            return new MapBuilder(this, subMap);
        }
    }

    public static ObjectMapper createMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

    public static boolean isNull(JsonNode node) {
        return node == null || node.isNull();
    }

    public static boolean isNotNull(JsonNode node) {
        return !isNull(node);
    }

    public static String getText(JsonNode node, String name) {
        if (isNotNull(node)) {
            final JsonNode val = node.get(name);
            if (isNotNull(val)) {
                return val.textValue();
            }
        }
        return null;
    }

    public static ObjectNode toObjectNode(JsonNode node) {
        if (node == null || node.isNull()) {
            return null;
        } else {
            return (ObjectNode) node;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy