001package org.javasimon.console.action;
002
003import java.io.IOException;
004
005import org.javasimon.Simon;
006import org.javasimon.console.ActionContext;
007import org.javasimon.console.json.ArrayJS;
008import org.javasimon.console.json.ObjectJS;
009
010/**
011 * Export Simons as a hierarchical JSON object for display in a tree-table.
012 * All attributes of simons are exported.
013 *
014 * @author gquintana
015 */
016public class TreeJsonAction extends AbstractJsonAction {
017
018        public static final String PATH = "/data/tree.json";
019
020        /**
021         * Name of the simon from where to start.
022         * {@code null} means root.
023         */
024        private String name;
025
026        /** @noinspection WeakerAccess*/
027        public TreeJsonAction(ActionContext context) {
028                super(context);
029        }
030
031        @Override
032        public void readParameters() {
033                super.readParameters();
034                name = getContext().getParameterAsString("name", null);
035        }
036
037        @Override
038        protected ObjectJS createObjectJS(Simon simon) {
039                ObjectJS simonJS = super.createObjectJS(simon);
040                ArrayJS childrenJS = new ArrayJS();
041                for (Simon child : simon.getChildren()) {
042                        ObjectJS childJS = createObjectJS(child);
043                        childrenJS.addElement(childJS);
044                }
045                simonJS.setAttribute("children", childrenJS);
046                return simonJS;
047        }
048
049        @Override
050        public void execute() throws IOException {
051                getContext().setContentType("application/json");
052                Simon simon = name == null ? getContext().getManager().getRootSimon() : getContext().getManager().getSimon(name);
053                ObjectJS simonRootJS = createObjectJS(simon);
054                simonRootJS.write(getContext().getWriter());
055        }
056}