package com.sebastian_daschner.jaxrs_analyzer.utils; import java.util.Map; import java.util.TreeMap; import java.util.stream.IntStream; /** * @author Sebastian Daschner */ public final class DebugUtils { private static final char INDENTATION_CHARACTER = ' '; private static final int INDENTATION_SIZE = 2; private DebugUtils() { throw new UnsupportedOperationException(); } /** * Prettifies the {@link Object#toString()} output generated by IntelliJ. * * @param object The object to print * @return The toString representation with line breaks and indentations */ public static String prettyToString(final Object object) { return prettyToString(object, INDENTATION_SIZE); } /** * Prettifies the {@link Object#toString()} output generated by IntelliJ. * * @param object The object to print * @param indentation The number of blanks on a new line * @return The toString representation with line breaks and indentations */ public static String prettyToString(final Object object, final int indentation) { final String string = object.toString(); // position of new lines and number of intending spaces final Map<Integer, Integer> newLines = new TreeMap<>(); int currentLevel = 0; boolean inStringLiteral = false; for (int i = 0; i < string.length(); i++) { final char currentChar = string.charAt(i); if (currentChar == ',' && !inStringLiteral) newLines.put(i, currentLevel); if (currentChar == '{' && !inStringLiteral) currentLevel++; if (currentChar == '}' && !inStringLiteral) currentLevel--; // known flaw -> will fail for string containing a ' character if (currentChar == '\'') inStringLiteral = !inStringLiteral; } final StringBuilder builder = new StringBuilder(string); int modifiedLength = 0; for (final Map.Entry<Integer, Integer> entry : newLines.entrySet()) { final String intend = IntStream.range(0, entry.getValue() * indentation).mapToObj(c -> INDENTATION_CHARACTER) .collect(() -> new StringBuilder("\n"), StringBuilder::append, StringBuilder::append).toString(); builder.insert(modifiedLength + entry.getKey() + 1, intend); modifiedLength += intend.length(); } return builder.toString(); } }