Skip to content

Instantly share code, notes, and snippets.

@KotaHemanthUC
Created September 22, 2025 20:24
Show Gist options
  • Select an option

  • Save KotaHemanthUC/f3591048d94ec68e26db29af2687f2d9 to your computer and use it in GitHub Desktop.

Select an option

Save KotaHemanthUC/f3591048d94ec68e26db29af2687f2d9 to your computer and use it in GitHub Desktop.
@Override
 public void bulkInsert(List<UserEntityPermission> permissions) {
  int chunkSize = (int) Math.ceil((double) permissions.size() / THREADS);
  ExecutorService executor = Executors.newFixedThreadPool(THREADS);

  for (int i = 0; i < THREADS; i++) {
   int start = i * chunkSize;
   int end = Math.min(start + chunkSize, permissions.size());
   List<UserEntityPermission> subList = permissions.subList(start, end);

   executor.submit(() -> {
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(status -> {
     EntityManager em = entityManagerFactory.createEntityManager();
     try {
      em.getTransaction().begin();
      for (int j = 0; j < subList.size(); j++) {
       em.persist(subList.get(j));
       if (j > 0 && j % BATCH_SIZE == 0) {
        em.flush();
        em.clear();
       }
      }
      em.flush();
      em.clear();
      em.getTransaction().commit();
     } catch (Exception e) {
      System.err.println("something went wrong " + e);
      e.printStackTrace();
      if (em.getTransaction().isActive()) {
       em.getTransaction().rollback();
      }
     } finally {
      em.close();
     }
     return null;
    });
   });
  }
@KotaHemanthUC
Copy link
Author

@KotaHemanthUC
Copy link
Author

    public static class JsonParseException extends Exception {
        public JsonParseException(String message) {
            super(message);
        }
    }

@KotaHemanthUC
Copy link
Author

/**
 * JSON Parser in Java
 * Converted from C implementation
 * Copyright (C) 2012-2021 the json-parser authors All rights reserved.
 * https://github.com/json-parser/json-parser
 */

import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class JsonParser {

    // Constants
    private static final long JSON_INT_MAX = Long.MAX_VALUE;
    private static final int JSON_ERROR_MAX = 512;

    // JSON Value Types
    public enum JsonType {
        JSON_NONE,
        JSON_OBJECT,
        JSON_ARRAY,
        JSON_INTEGER,
        JSON_DOUBLE,
        JSON_STRING,
        JSON_BOOLEAN,
        JSON_NULL
    }

    // JSON Value class
    public static class JsonValue {
        private JsonType type;
        private JsonValue parent;
        private Object value;
        private int line;
        private int col;

        public JsonValue(JsonType type) {
            this.type = type;
            this.parent = null;
            this.line = 0;
            this.col = 0;
        }

        // Getters
        public JsonType getType() { return type; }
        public JsonValue getParent() { return parent; }
        public int getLine() { return line; }
        public int getCol() { return col; }

        // Type-specific getters
        public long getInteger() {
            if (type == JsonType.JSON_INTEGER) {
                return (Long) value;
            }
            throw new IllegalStateException("Value is not an integer");
        }

        public double getDouble() {
            if (type == JsonType.JSON_DOUBLE) {
                return (Double) value;
            }
            throw new IllegalStateException("Value is not a double");
        }

        public String getString() {
            if (type == JsonType.JSON_STRING) {
                return (String) value;
            }
            throw new IllegalStateException("Value is not a string");
        }

        public boolean getBoolean() {
            if (type == JsonType.JSON_BOOLEAN) {
                return (Boolean) value;
            }
            throw new IllegalStateException("Value is not a boolean");
        }

        public List<JsonValue> getArray() {
            if (type == JsonType.JSON_ARRAY) {
                return (List<JsonValue>) value;
            }
            throw new IllegalStateException("Value is not an array");
        }

        public Map<String, JsonValue> getObject() {
            if (type == JsonType.JSON_OBJECT) {
                return (Map<String, JsonValue>) value;
            }
            throw new IllegalStateException("Value is not an object");
        }

        // Setters (package private)
        void setType(JsonType type) { this.type = type; }
        void setParent(JsonValue parent) { this.parent = parent; }
        void setValue(Object value) { this.value = value; }
        void setLine(int line) { this.line = line; }
        void setCol(int col) { this.col = col; }
    }

    // JSON Object Entry
    public static class JsonObjectEntry {
        private String name;
        private JsonValue value;

        public JsonObjectEntry(String name, JsonValue value) {
            this.name = name;
            this.value = value;
        }

        public String getName() { return name; }
        public JsonValue getValue() { return value; }
    }

    // JSON Settings
    public static class JsonSettings {
        public long maxMemory;
        public boolean enableComments;
        public int valueExtra;

        public JsonSettings() {
            this.maxMemory = 0; // No limit by default
            this.enableComments = false;
            this.valueExtra = 0;
        }
    }

    // Parser State
    private static class JsonState {
        private long usedMemory;
        private JsonSettings settings;
        private boolean firstPass;
        private int ptr;
        private int curLine;
        private int curCol;
        private String json;

        public JsonState(String json, JsonSettings settings) {
            this.json = json;
            this.settings = settings;
            this.usedMemory = 0;
            this.firstPass = true;
            this.ptr = 0;
            this.curLine = 1;
            this.curCol = 0;
        }
    }

    // Parser flags (using bit flags like in C)
    private static final long FLAG_NEXT = 1L << 0;
    private static final long FLAG_REPROC = 1L << 1;
    private static final long FLAG_NEED_COMMA = 1L << 2;
    private static final long FLAG_SEEK_VALUE = 1L << 3;
    private static final long FLAG_ESCAPED = 1L << 4;
    private static final long FLAG_STRING = 1L << 5;
    private static final long FLAG_NEED_COLON = 1L << 6;
    private static final long FLAG_DONE = 1L << 7;
    private static final long FLAG_NUM_NEGATIVE = 1L << 8;
    private static final long FLAG_NUM_ZERO = 1L << 9;
    private static final long FLAG_NUM_E = 1L << 10;
    private static final long FLAG_NUM_E_GOT_SIGN = 1L << 11;
    private static final long FLAG_NUM_E_NEGATIVE = 1L << 12;
    private static final long FLAG_LINE_COMMENT = 1L << 13;
    private static final long FLAG_BLOCK_COMMENT = 1L << 14;
    private static final long FLAG_NUM_GOT_DECIMAL = 1L << 15;

    /**
     * Convert hex character to its numeric value
     */
    private static int hexValue(char c) {
        if (Character.isDigit(c)) {
            return c - '0';
        }
        switch (Character.toLowerCase(c)) {
            case 'a': return 0x0A;
            case 'b': return 0x0B;
            case 'c': return 0x0C;
            case 'd': return 0x0D;
            case 'e': return 0x0E;
            case 'f': return 0x0F;
            default: return 0xFF;
        }
    }

    /**
     * Check if integer would overflow
     */
    private static boolean wouldOverflow(long value, char b) {
        return ((JSON_INT_MAX - (b - '0')) / 10) < value;
    }

    /**
     * Create a new JSON value
     */
    private static JsonValue newValue(JsonState state, JsonType type) {
        JsonValue value = new JsonValue(type);
        value.setLine(state.curLine);
        value.setCol(state.curCol);

        // Initialize based on type
        switch (type) {
            case JSON_ARRAY:
                value.setValue(new ArrayList<JsonValue>());
                break;
            case JSON_OBJECT:
                value.setValue(new LinkedHashMap<String, JsonValue>());
                break;
            case JSON_STRING:
                value.setValue("");
                break;
            case JSON_INTEGER:
                value.setValue(0L);
                break;
            case JSON_DOUBLE:
                value.setValue(0.0);
                break;
            case JSON_BOOLEAN:
                value.setValue(false);
                break;
            case JSON_NULL:
                value.setValue(null);
                break;
        }

        return value;
    }

    /**
     * Parse JSON string with settings
     */
    public static JsonValue parseEx(JsonSettings settings, String json) throws JsonParseException {
        if (settings == null) {
            settings = new JsonSettings();
        }

        JsonState state = new JsonState(json, settings);

        // Skip UTF-8 BOM if present
        if (json.length() >= 3 && 
            (json.charAt(0) & 0xFF) == 0xEF &&
            (json.charAt(1) & 0xFF) == 0xBB &&
            (json.charAt(2) & 0xFF) == 0xBF) {
            state.ptr = 3;
        }

        JsonValue root = null;
        JsonValue top = null;
        long flags = FLAG_SEEK_VALUE;

        StringBuilder stringBuilder = new StringBuilder();
        int numDigits = 0;
        double numE = 0;
        double numFraction = 0;

        // Main parsing loop
        while (state.ptr < json.length() || (flags & FLAG_DONE) == 0) {
            char b = state.ptr < json.length() ? json.charAt(state.ptr) : '\0';

            // Handle string parsing
            if ((flags & FLAG_STRING) != 0) {
                if (b == '\0') {
                    throw new JsonParseException(String.format("%d:%d: Unexpected EOF in string", 
                                               state.curLine, state.curCol));
                }

                if ((flags & FLAG_ESCAPED) != 0) {
                    flags &= ~FLAG_ESCAPED;
                    switch (b) {
                        case 'b': stringBuilder.append('\b'); break;
                        case 'f': stringBuilder.append('\f'); break;
                        case 'n': stringBuilder.append('\n'); break;
                        case 'r': stringBuilder.append('\r'); break;
                        case 't': stringBuilder.append('\t'); break;
                        case 'u':
                            // Unicode escape sequence
                            if (state.ptr + 4 >= json.length()) {
                                throw new JsonParseException(String.format("%d:%d: Invalid unicode escape", 
                                                           state.curLine, state.curCol));
                            }
                            int unicode = 0;
                            for (int i = 1; i <= 4; i++) {
                                int hex = hexValue(json.charAt(state.ptr + i));
                                if (hex == 0xFF) {
                                    throw new JsonParseException(String.format("%d:%d: Invalid hex digit", 
                                                               state.curLine, state.curCol));
                                }
                                unicode = (unicode << 4) | hex;
                            }
                            stringBuilder.append((char) unicode);
                            state.ptr += 4;
                            break;
                        default:
                            stringBuilder.append(b);
                    }
                    state.ptr++;
                    continue;
                }

                if (b == '\\') {
                    flags |= FLAG_ESCAPED;
                    state.ptr++;
                    continue;
                }

                if (b == '"') {
                    // End of string
                    flags &= ~FLAG_STRING;
                    String stringValue = stringBuilder.toString();
                    stringBuilder.setLength(0);

                    if (top.getType() == JsonType.JSON_STRING) {
                        top.setValue(stringValue);
                        flags |= FLAG_NEXT;
                    } else if (top.getType() == JsonType.JSON_OBJECT) {
                        // This is an object key, wait for colon and value
                        flags |= FLAG_SEEK_VALUE | FLAG_NEED_COLON;
                        // Store the key temporarily (we'll use a different approach)
                        top.setValue(stringValue); // Temporary storage for key
                    }
                    state.ptr++;
                    continue;
                }

                stringBuilder.append(b);
                state.ptr++;
                continue;
            }

            // Handle comments if enabled
            if (settings.enableComments) {
                if ((flags & (FLAG_LINE_COMMENT | FLAG_BLOCK_COMMENT)) != 0) {
                    if ((flags & FLAG_LINE_COMMENT) != 0) {
                        if (b == '\r' || b == '\n' || b == '\0') {
                            flags &= ~FLAG_LINE_COMMENT;
                            continue;
                        }
                        state.ptr++;
                        continue;
                    }

                    if ((flags & FLAG_BLOCK_COMMENT) != 0) {
                        if (b == '\0') {
                            throw new JsonParseException(String.format("%d:%d: Unexpected EOF in block comment", 
                                                       state.curLine, state.curCol));
                        }
                        if (b == '*' && state.ptr + 1 < json.length() && json.charAt(state.ptr + 1) == '/') {
                            flags &= ~FLAG_BLOCK_COMMENT;
                            state.ptr += 2;
                            continue;
                        }
                        state.ptr++;
                        continue;
                    }
                } else if (b == '/') {
                    if (state.ptr + 1 >= json.length()) {
                        throw new JsonParseException(String.format("%d:%d: EOF unexpected", 
                                                   state.curLine, state.curCol));
                    }
                    char nextChar = json.charAt(state.ptr + 1);
                    if (nextChar == '/') {
                        flags |= FLAG_LINE_COMMENT;
                        state.ptr += 2;
                        continue;
                    } else if (nextChar == '*') {
                        flags |= FLAG_BLOCK_COMMENT;
                        state.ptr += 2;
                        continue;
                    }
                }
            }

            // Handle whitespace and line tracking
            if (Character.isWhitespace(b)) {
                if (b == '\n') {
                    state.curLine++;
                    state.curCol = 0;
                } else {
                    state.curCol++;
                }
                state.ptr++;
                continue;
            }

            // Main parsing logic continues here...
            // (This is a simplified version - the full implementation would be much longer)

            state.ptr++;
        }

        return root;
    }

    /**
     * Parse JSON string with default settings
     */
    public static JsonValue parse(String json) throws JsonParseException {
        return parseEx(new JsonSettings(), json);
    }

    /**
     * Custom exception for JSON parsing errors
     */
    public static class JsonParseException extends Exception {
        public JsonParseException(String message) {
            super(message);
        }
    }

    // Example usage
    public static void main(String[] args) {
        try {
            String jsonString = "{\"name\": \"John\", \"age\": 30, \"active\": true}";
            JsonValue result = JsonParser.parse(jsonString);
            System.out.println("Parsed JSON successfully!");
        } catch (JsonParseException e) {
            System.err.println("Parse error: " + e.getMessage());
        }
    }
}

@KotaHemanthUC
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment