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 session. They may only be fired
030 * on the {@link org.jgrapes.webconsole.base.ConsoleSession#responsePipeline()}
031 * (usually with 
032 * {@link org.jgrapes.webconsole.base.ConsoleSession#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    public abstract void toJson(Writer writer)
045            throws InterruptedException, IOException;
046
047    /**
048     * Creates a JSON notification from the given data.
049     * Closes the `writer`.
050     * 
051     * @param writer the writer
052     * @throws IOException 
053     */
054    protected void toJson(Writer writer, String method, Object... params)
055            throws IOException {
056        JsonRpc rpc = JsonRpc.create();
057        rpc.setMethod(method);
058        if (params.length > 0) {
059            for (Object obj : params) {
060                rpc.addParam(obj);
061            }
062        }
063        JsonBeanEncoder.create(writer).writeObject(rpc).flush();
064    }
065}