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.portal.base.events;
020
021import java.io.IOException;
022import java.io.Writer;
023
024import org.jdrupes.json.JsonBeanEncoder;
025import org.jdrupes.json.JsonRpc;
026import org.jgrapes.core.Event;
027
028/**
029 * Events derived from this class are transformed to JSON messages
030 * that are sent to the portal session. They may only be fired
031 * on the {@link org.jgrapes.portal.base.PortalSession#responsePipeline()}
032 * (usually with 
033 * {@link org.jgrapes.portal.base.PortalSession#respond(org.jgrapes.core.Event)}).
034 */
035public abstract class PortalCommand extends Event<Void> {
036
037    /**
038     * Writes the event as JSON notification to the given writer.
039     * Derived classes usually simply call 
040     * {@link #toJson(Writer, String, Object...)} with the method
041     * name and parameters.
042     * 
043     * @param writer the writer
044     */
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    protected void toJson(Writer writer, String method, Object... params)
056            throws IOException {
057        JsonRpc rpc = JsonRpc.create();
058        rpc.setMethod(method);
059        if (params.length > 0) {
060            for (Object obj : params) {
061                rpc.addParam(obj);
062            }
063        }
064        JsonBeanEncoder.create(writer).writeObject(rpc).flush();
065    }
066}