001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.webconsole.base.events;
020
021import java.io.IOException;
022import java.io.Writer;
023import org.jdrupes.json.JsonBeanEncoder;
024import org.jdrupes.json.JsonRpc;
025import org.jgrapes.core.Event;
026
027/**
028 * Events derived from this class are transformed to JSON messages
029 * that are sent to the web console page. They may only be fired
030 * on the {@link org.jgrapes.webconsole.base.ConsoleConnection#responsePipeline()}
031 * (usually with 
032 * {@link org.jgrapes.webconsole.base.ConsoleConnection#respond(org.jgrapes.core.Event)}).
033 */
034public abstract class ConsoleCommand extends Event<Void> {
035
036    /**
037     * Writes the event as JSON notification to the given writer.
038     * Derived classes usually simply call 
039     * {@link #toJson(Writer, String, Object...)} with the method
040     * name and parameters.
041     * 
042     * @param writer the writer
043     */
044    @SuppressWarnings("PMD.LinguisticNaming")
045    public abstract void toJson(Writer writer)
046            throws InterruptedException, IOException;
047
048    /**
049     * Creates a JSON notification from the given data.
050     * Closes the `writer`.
051     * 
052     * @param writer the writer
053     * @throws IOException 
054     */
055    @SuppressWarnings("PMD.LinguisticNaming")
056    protected void toJson(Writer writer, String method, Object... params)
057            throws IOException {
058        JsonRpc rpc = JsonRpc.create();
059        rpc.setMethod(method);
060        if (params.length > 0) {
061            for (Object obj : params) {
062                rpc.addParam(obj);
063            }
064        }
065        JsonBeanEncoder.create(writer).writeObject(rpc).flush();
066    }
067}