Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

6.9 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * The state of a form as plain text: every editable control under a root,
 * keyed by where it sits in the tree. Taking it from one form and applying it
 * to another of the same kind copies the configuration across, and the same
 * map can be written to a file and read back.
 *
 * <p>Applying is done in a few passes, because choosing an item in one control
 * can rebuild the controls beneath another (a payload type, for one); the
 * later passes set what the earlier ones brought into being.
 */
public final class FormState {
    private FormState() {}

    private static final char SEP = '\u001F';

    /** Client property: a component (and everything under it) left out of the state. */
    public static final String SKIP = "opensuite.formState.skip";

    public static Map<String, String> capture(Component root) {
        Map<String, String> out = new LinkedHashMap<>();
        walk(root, "", out, null);
        return out;
    }

    public static void apply(Component root, Map<String, String> state) {
        for (int pass = 0; pass < 4; pass++) walk(root, "", null, state);
    }

    private static void walk(Component c, String path, Map<String, String> out, Map<String, String> in) {
        if (c instanceof JComponent jc && Boolean.TRUE.equals(jc.getClientProperty(SKIP))) return;
        String key = path + c.getClass().getSimpleName();
        if (c instanceof JTextComponent t) {
            if (t.isEditable() && !(c instanceof JPasswordField)) {
                if (out != null) out.put(key, "T" + t.getText());
                else if (in.get(key) instanceof String v && v.startsWith("T") && !t.getText().equals(v.substring(1))) t.setText(v.substring(1));
            }
            return;
        }
        if (c instanceof JCheckBox || c instanceof JRadioButton || c instanceof JToggleButton) {
            AbstractButton b = (AbstractButton) c;
            if (out != null) out.put(key, b.isSelected() ? "B1" : "B0");
            else if (in.get(key) instanceof String v && v.startsWith("B")) {
                boolean want = v.equals("B1");
                // A click, so that code listening for the action hears it; a radio is only ever switched on.
                if (b.isSelected() != want && (want || !(c instanceof JRadioButton))) {
                    boolean enabled = b.isEnabled();
                    b.setEnabled(true);
                    b.doClick(0);
                    b.setEnabled(enabled);
                }
            }
            return;
        }
        if (c instanceof JComboBox<?> combo) {
            if (out != null) {
                Object ed = combo.isEditable() ? combo.getEditor().getItem() : null;
                out.put(key, "C" + combo.getSelectedIndex() + SEP + (ed == null ? "" : ed));
            } else if (in.get(key) instanceof String v && v.startsWith("C")) {
                int cut = v.indexOf(SEP);
                try {
                    int index = Integer.parseInt(v.substring(1, cut));
                    if (index >= 0 && index < combo.getItemCount() && combo.getSelectedIndex() != index) combo.setSelectedIndex(index);
                    else if (index < 0 && combo.isEditable() && !v.substring(cut + 1).equals(String.valueOf(combo.getEditor().getItem()))) {
                        combo.getEditor().setItem(v.substring(cut + 1));
                    }
                } catch (RuntimeException ignored) { }
            }
            return;
        }
        if (c instanceof JSpinner sp) {
            if (out != null) out.put(key, "S" + sp.getValue());
            else if (in.get(key) instanceof String v && v.startsWith("S") && !v.substring(1).equals(String.valueOf(sp.getValue()))) {
                try {
                    Object cur = sp.getValue();
                    String s = v.substring(1);
                    if (cur instanceof Integer) sp.setValue(Integer.parseInt(s));
                    else if (cur instanceof Long) sp.setValue(Long.parseLong(s));
                    else if (cur instanceof Double) sp.setValue(Double.parseDouble(s));
                    else if (cur instanceof String) sp.setValue(s);
                } catch (RuntimeException ignored) { }
            }
            return;
        }
        if (c instanceof JTable table) {
            if (table.getModel() instanceof DefaultTableModel m) {
                if (out != null) out.put(key, "R" + rows(m));
                else if (in.get(key) instanceof String v && v.startsWith("R") && !v.substring(1).equals(rows(m))) setRows(m, v.substring(1));
            }
            return;
        }
        if (c instanceof Container k) {
            Component[] kids = k.getComponents();
            for (int i = 0; i < kids.length; i++) walk(kids[i], path + i + "/", out, in);
        }
    }

    /** Rows parted by a record mark, cells by a unit mark; a cell is a letter for its type and its text. */
    private static String rows(DefaultTableModel m) {
        StringBuilder sb = new StringBuilder();
        for (int r = 0; r < m.getRowCount(); r++) {
            if (r > 0) sb.append('\u001E');
            for (int col = 0; col < m.getColumnCount(); col++) {
                if (col > 0) sb.append('\u001D');
                Object v = m.getValueAt(r, col);
                sb.append(v instanceof Boolean ? 'b' : v instanceof Integer ? 'i' : v == null ? 'n' : 's').append(v == null ? "" : v);
            }
        }
        return sb.toString();
    }

    private static void setRows(DefaultTableModel m, String text) {
        m.setRowCount(0);
        if (text.isEmpty()) return;
        for (String row : text.split("\u001E", -1)) {
            String[] cells = row.split("\u001D", -1);
            Object[] values = new Object[m.getColumnCount()];
            for (int col = 0; col < values.length && col < cells.length; col++) {
                String cell = cells[col];
                if (cell.isEmpty()) continue;
                String body = cell.substring(1);
                values[col] = switch (cell.charAt(0)) {
                    case 'b' -> Boolean.valueOf(body);
                    case 'i' -> { try { yield Integer.valueOf(body); } catch (NumberFormatException e) { yield body; } }
                    case 'n' -> null;
                    default -> body;
                };
            }
            m.addRow(values);
        }
    }

    /** The state as lines of {@code key=value}, for a file. */
    public static java.util.Properties toProperties(Map<String, String> state) {
        java.util.Properties p = new java.util.Properties();
        p.putAll(state);
        return p;
    }

    public static Map<String, String> fromProperties(java.util.Properties p) {
        Map<String, String> out = new LinkedHashMap<>();
        for (String k : p.stringPropertyNames()) out.put(k, p.getProperty(k));
        return out;
    }
}