DEV Community

Query Filter
Query Filter

Posted on

bridge101

package com.yourpackage;

import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.SmartLifecycle;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class SpringVisualizer implements ApplicationContextAware, SmartLifecycle {

    private ConfigurableApplicationContext startContext;
    private boolean isRunning = false;
    private final Set<String> currentBeanManualDeps = new HashSet<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.startContext = (ConfigurableApplicationContext) applicationContext;
    }

    @Override
    public void start() {
        StringBuilder dot = new StringBuilder("digraph G {\n");
        dot.append("  rankdir=LR; node [shape=plain, fontname=\"Arial\", fontsize=10];\n");
        dot.append("  edge [fontname=\"Arial\", fontsize=8];\n\n");

        Set<String> processed = new HashSet<>();
        ApplicationContext current = this.startContext;

        while (current != null) {
            ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) current).getBeanFactory();
            for (String name : factory.getBeanDefinitionNames()) {
                if (processed.add(name)) {
                    BeanDefinition def = factory.getBeanDefinition(name);
                    currentBeanManualDeps.clear(); 

                    String color = name.toLowerCase().contains("comet") ? "#FFF9C4" : 
                                   (name.toLowerCase().contains("cpls") ? "#C8E6C9" : "#E1F5FE");

                    dot.append(String.format("  \"%s\" [label=<", name));
                    dot.append("<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" BGCOLOR=\"").append(color).append("\">");
                    dot.append("<TR><TD COLSPAN=\"2\"><B>").append(xmlEscape(name.trim())).append("</B></TD></TR>");

                    // 1. Process Properties
                    for (PropertyValue pv : def.getPropertyValues().getPropertyValues()) {
                        dot.append("<TR><TD ALIGN=\"LEFT\">").append(xmlEscape(pv.getName().trim())).append("</TD>");
                        dot.append("<TD ALIGN=\"LEFT\">").append(extractValue(pv.getValue())).append("</TD></TR>");
                    }

                    // 2. Process Constructor Args
                    ConstructorArgumentValues cav = def.getConstructorArgumentValues();
                    for (Map.Entry<Integer, ConstructorArgumentValues.ValueHolder> entry : cav.getIndexedArgumentValues().entrySet()) {
                        dot.append("<TR><TD ALIGN=\"LEFT\"><I>arg[").append(entry.getKey()).append("]</I></TD>");
                        dot.append("<TD ALIGN=\"LEFT\">").append(extractValue(entry.getValue().getValue())).append("</TD></TR>");
                    }
                    for (ConstructorArgumentValues.ValueHolder vh : cav.getGenericArgumentValues()) {
                        String type = vh.getType() != null ? vh.getType().substring(vh.getType().lastIndexOf('.') + 1) : "gen";
                        dot.append("<TR><TD ALIGN=\"LEFT\"><I>arg:").append(type.trim()).append("</I></TD>");
                        dot.append("<TD ALIGN=\"LEFT\">").append(extractValue(vh.getValue())).append("</TD></TR>");
                    }
                    dot.append("</TABLE>>];\n");

                    // 3. Connections
                    Set<String> allDeps = new HashSet<>(Arrays.asList(factory.getDependenciesForBean(name)));
                    allDeps.addAll(currentBeanManualDeps);
                    for (String dep : allDeps) {
                        dot.append(String.format("  \"%s\" -> \"%s\";\n", name, dep));
                    }
                }
            }
            current = current.getParent();
        }
        dot.append("}\n");
        writeToFile(dot.toString());
        this.isRunning = true;
    }

    private String extractValue(Object value) {
        if (value == null) return "null";

        // 1. Bean References (Manual Dependency Tracker)
        if (value instanceof BeanReference) {
            String beanName = ((BeanReference) value).getBeanName().trim();
            currentBeanManualDeps.add(beanName); 
            return "@" + xmlEscape(beanName);
        }

        // 2. TypedStringValue (The wrapper we need to peel)
        if (value instanceof TypedStringValue) {
            String raw = ((TypedStringValue) value).getValue();
            return xmlEscape(raw != null ? raw.trim() : "null");
        }

        // 3. Inner Bean Definitions
        if (value instanceof BeanDefinition) {
            String className = ((BeanDefinition) value).getBeanClassName();
            if (className != null) {
                String shortName = className.substring(className.lastIndexOf('.') + 1);
                return "<i>" + xmlEscape(shortName.trim()) + "</i>";
            }
            return "<i>InnerBean</i>";
        }

        // 4. Collections (Iterable for Sets/Lists)
        if (value instanceof Iterable) {
            List<String> cleaned = new ArrayList<>();
            int count = 0;
            for (Object item : (Iterable<?>) value) {
                if (count++ >= 15) { cleaned.add("..."); break; }
                cleaned.add(extractValue(item)); // Recursively trims items
            }
            return String.join("<BR ALIGN=\"LEFT\"/>", cleaned);
        }

        // 5. Maps
        if (value instanceof Map) {
            StringBuilder mapStr = new StringBuilder();
            for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                // Key and Value both passed through extractValue (which trims)
                mapStr.append(extractValue(entry.getKey()))
                      .append("=")
                      .append(extractValue(entry.getValue()))
                      .append("<BR ALIGN=\"LEFT\"/>");
            }
            return mapStr.toString();
        }

        // 6. Default Fallback
        String s = value.toString().trim();
        if (s.length() > 60) {
            s = s.substring(0, 57).trim() + "...";
        }
        return xmlEscape(s);
    }

    private void writeToFile(String content) {
        try {
            File projectRoot = findProjectRoot();
            File buildDir = new File(projectRoot, "build");
            if (!buildDir.exists()) buildDir.mkdirs();

            File file = new File(buildDir, "spring-beans.dot");
            try (FileWriter writer = new FileWriter(file)) {
                writer.write(content);
            }

            String separator = "============================================================";
            System.out.println("\n" + separator);
            System.out.println("GRAPH GENERATION SUCCESSFUL");
            System.out.println("Project Root: " + projectRoot.getAbsolutePath());
            System.out.println("Click to open (IntelliJ): " + file.toURI().toString());
            System.out.println(separator + "\n");
        } catch (IOException e) {
            System.err.println("File Error: " + e.getMessage());
        }
    }

    private File findProjectRoot() {
        File current = new File(System.getProperty("user.dir"));
        while (current != null) {
            if (new File(current, "build.gradle").exists() || new File(current, "settings.gradle").exists()) {
                return current;
            }
            current = current.getParentFile();
        }
        return new File(System.getProperty("user.dir"));
    }

    private String xmlEscape(String input) {
        if (input == null) return "";
        return input.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
                    .replace("\"", "&quot;").replace("'", "&apos;")
                    .replace("&lt;BR ALIGN=&quot;LEFT&quot;/&gt;", "<BR ALIGN=\"LEFT\"/>");
    }

    @Override public int getPhase() { return Integer.MAX_VALUE; }
    @Override public boolean isAutoStartup() { return true; }
    @Override public void stop() { this.isRunning = false; }
    @Override public boolean isRunning() { return this.isRunning; }
    @Override public void stop(Runnable c) { stop(); c.run(); }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)