001package org.javasimon.console.action;
002
003import org.javasimon.Sample;
004import org.javasimon.console.ActionContext;
005import org.javasimon.console.json.ArrayJS;
006import org.javasimon.console.json.JsonStringifierFactory;
007import org.javasimon.console.json.ObjectJS;
008import org.javasimon.console.json.SimpleJS;
009
010import java.io.IOException;
011import java.io.PrintWriter;
012
013/**
014 * Export Simons as a flat JSON array to be displayed in data-table.
015 * Each JSON-ized simon as all attributes even if not present on real Simon.
016 * Only a subset (defined in {@link AbstractTableAction#columns}) of attributes are exported.
017 *
018 * @author gquintana
019 */
020public class TableJsonAction extends AbstractTableAction {
021
022        public static final String PATH = "/data/table.json";
023
024        public TableJsonAction(ActionContext context) {
025                super(context, "application/json");
026                this.stringifierFactory = new JsonStringifierFactory();
027                this.numberPattern = JsonStringifierFactory.INTEGER_NUMBER_PATTERN;
028        }
029
030        /** Current array of JSON-ized Simons. */
031        private ArrayJS simonsJS;
032        /** Current JSON-ized Simon. */
033        private ObjectJS simonJS;
034
035        @Override
036        protected void printTable(PrintWriter writer) throws IOException {
037                simonsJS = new ArrayJS();
038                super.printTable(writer);
039                simonsJS.write(writer);
040                simonJS = null;
041        }
042
043        @Override
044        protected void printHeaderRow(PrintWriter writer) throws IOException {
045                // No header
046        }
047
048        @Override
049        protected void printBodyRow(Sample sample, PrintWriter writer) throws IOException {
050                simonJS = new ObjectJS();
051                simonsJS.addElement(simonJS);
052                super.printBodyRow(sample, writer);
053                simonJS = null;
054        }
055
056        @Override
057        @SuppressWarnings("unchecked")
058        protected void printBodyCell(Column column, Sample sample, PrintWriter writer) {
059                simonJS.setAttribute(column.getName(), new SimpleJS(column.getValue(sample), column.getStringifier(sample)));
060        }
061}