com.conwet.silbops.examples.gui.MainFrame.java Source code

Java tutorial

Introduction

Here is the source code for com.conwet.silbops.examples.gui.MainFrame.java

Source

package com.conwet.silbops.examples.gui;

/*
 * #%L
 * SilboPS GUI Client
 * %%
 * Copyright (C) 2011 - 2014 CoNWeT Lab., Universidad Politcnica de Madrid
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * #L%
 */

import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.conwet.silbops.api.AdvertiseListener;
import com.conwet.silbops.api.ConnectionFactory;
import com.conwet.silbops.api.EndPointException;
import com.conwet.silbops.api.IConnectionFactory;
import com.conwet.silbops.api.NotificationListener;
import com.conwet.silbops.api.PubEndpoint;
import com.conwet.silbops.api.SubEndpoint;
import com.conwet.silbops.model.Advertise;
import com.conwet.silbops.model.ContextFunction;
import com.conwet.silbops.model.Subscription;
import com.conwet.silbops.model.Notification;

/**
 *
 * @author sortega
 */
public class MainFrame extends JFrame implements NotificationListener, AdvertiseListener {
    private static final long serialVersionUID = 1L;

    private boolean connected = false;
    private transient PubEndpoint pubEndpoint = null;
    private transient SubEndpoint subEndpoint = null;

    private final DefaultListModel<String> logModel;
    private transient Runnable clearLines;

    public MainFrame() {

        this.logModel = new DefaultListModel<>();
        initComponents();
        tglSub.setSelected(true);
        this.clearLines = new Runnable() {

            @Override
            public void run() {
                logModel.clear();
            }
        };
    }

    private void subscriptionTemplate() {

        txtMessage.setText("{\n" + "\"id\":\"\",\n" + "\"constraints\":{\n"
                + "    \"attr1:str\": [{\"=\": \"val1\"}],\n" + "    \"attr2:long\": [{\"exists\": \"\"}]\n"
                + "    },\n" + "\"contextFunction\":{}\n" + "}");
    }

    private void notificationTemplate() {

        txtMessage.setText("{\n" + "   \"attr1:str\": \"val1\",\n" + "   \"attr2:long\": 3\n" + "}");
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        messageGroup = new javax.swing.ButtonGroup();
        protocolGroup = new javax.swing.ButtonGroup();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        labelHostname = new javax.swing.JLabel();
        labelPort = new javax.swing.JLabel();
        labelProtocol = new javax.swing.JLabel();
        txtHostname = new javax.swing.JTextField();
        txtPort = new javax.swing.JTextField();
        jsp = new javax.swing.JRadioButton();
        xjsp = new javax.swing.JRadioButton();
        cmdConnect = new javax.swing.JButton();
        cmdClear = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        tglSub = new javax.swing.JToggleButton();
        tglUnsub = new javax.swing.JToggleButton();
        tglPub = new javax.swing.JToggleButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtMessage = new javax.swing.JTextArea();
        cmdSend = new javax.swing.JButton();
        listScroll = new javax.swing.JScrollPane();
        listLog = new javax.swing.JList<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(800, 400));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        labelHostname.setText("Hostname");

        labelPort.setText("Port");

        labelProtocol.setText("Protocol");

        txtHostname.setText("localhost");

        txtPort.setText("3333");

        protocolGroup.add(jsp);
        jsp.setSelected(true);
        jsp.setText("JSP (binary)");
        jsp.setActionCommand("silbops-jsp");

        protocolGroup.add(xjsp);
        xjsp.setText("XJSP (text)");
        xjsp.setActionCommand("silbops");

        cmdConnect.setText("Connect");
        cmdConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdConnectActionPerformed(evt);
            }
        });

        cmdClear.setText("Clear");
        cmdClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdClearActionPerformed(evt);
            }
        });

        messageGroup.add(tglSub);
        tglSub.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 10)); // NOI18N
        tglSub.setText("Subscribe");
        tglSub.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tglSubStateChanged(evt);
            }
        });

        messageGroup.add(tglUnsub);
        tglUnsub.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 10)); // NOI18N
        tglUnsub.setText("Unsubscribe");
        tglUnsub.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tglUnsubStateChanged(evt);
            }
        });

        messageGroup.add(tglPub);
        tglPub.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 10)); // NOI18N
        tglPub.setText("Publish");
        tglPub.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                tglPubStateChanged(evt);
            }
        });

        txtMessage.setColumns(20);
        txtMessage.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N
        txtMessage.setRows(5);
        jScrollPane1.setViewportView(txtMessage);

        cmdSend.setText("Send");
        cmdSend.setEnabled(false);
        cmdSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout
                .setHorizontalGroup(
                        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
                                        .addGroup(jPanel1Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jScrollPane1).addComponent(jSeparator2)
                                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                                        jPanel1Layout.createSequentialGroup()
                                                                .addGap(0, 0, Short.MAX_VALUE)
                                                                .addComponent(cmdSend))
                                                .addGroup(jPanel1Layout.createSequentialGroup()
                                                        .addGroup(jPanel1Layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addComponent(labelHostname).addComponent(labelPort)
                                                                .addComponent(labelProtocol))
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addGroup(jPanel1Layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addComponent(txtHostname,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 129,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jsp).addComponent(xjsp)
                                                                .addComponent(txtPort,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 69,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addGroup(jPanel1Layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addGroup(jPanel1Layout.createSequentialGroup()
                                                                        .addComponent(cmdConnect,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                108,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addGap(0, 0, Short.MAX_VALUE))
                                                                .addComponent(cmdClear,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        Short.MAX_VALUE)))
                                                .addGroup(jPanel1Layout.createSequentialGroup().addComponent(tglSub)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(tglUnsub)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(tglPub)))
                                        .addContainerGap()));
        jPanel1Layout
                .setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
                                .addGroup(jPanel1Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(labelHostname)
                                                .addComponent(txtHostname, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(jPanel1Layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(labelPort).addComponent(txtPort,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addComponent(cmdConnect, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(labelProtocol).addComponent(jsp))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(xjsp))
                                        .addComponent(cmdClear))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(tglSub).addComponent(tglUnsub).addComponent(tglPub))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdSend)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        listLog.setModel(this.logModel);
        listLog.setDoubleBuffered(true);
        listScroll.setViewportView(listLog);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(listScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup().addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(listScroll, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING))
                                .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmdConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdConnectActionPerformed
        if (connected) {
            this.disconnect();
        } else {
            this.connect();
        }
    }//GEN-LAST:event_cmdConnectActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (connected) {
            this.disconnect();
        }
    }//GEN-LAST:event_formWindowClosing

    private void cmdSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSendActionPerformed
        try {
            if (tglSub.isSelected()) {
                Subscription subscription = Subscription.fromJSON(this.getMessageAsJSON());
                subEndpoint.subscribe(subscription, new ContextFunction());
                log("Subscribing to " + subscription);
            } else if (tglUnsub.isSelected()) {
                Subscription subscription = Subscription.fromJSON(this.getMessageAsJSON());
                subEndpoint.unsubscribe(subscription, new ContextFunction());
                log("Unsubscribing from " + subscription);
            } else if (tglPub.isSelected()) {
                Notification not = Notification.fromJSON(this.getMessageAsJSON());
                pubEndpoint.advertise(Advertise.asAdvertise(not));
                pubEndpoint.publish(not);
                log("Publishing " + not);
            }
        } catch (EndPointException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_cmdSendActionPerformed

    private void tglSubStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tglSubStateChanged
        if (tglSub.isSelected()) {
            subscriptionTemplate();
        }
    }//GEN-LAST:event_tglSubStateChanged

    private void tglUnsubStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tglUnsubStateChanged
        if (tglUnsub.isSelected()) {
            subscriptionTemplate();
        }
    }//GEN-LAST:event_tglUnsubStateChanged

    private void tglPubStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tglPubStateChanged
        if (tglPub.isSelected()) {
            notificationTemplate();
        }
    }//GEN-LAST:event_tglPubStateChanged

    private void cmdClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdClearActionPerformed
        SwingUtilities.invokeLater(clearLines);
    }//GEN-LAST:event_cmdClearActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws Exception {
        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdClear;
    private javax.swing.JButton cmdConnect;
    private javax.swing.JButton cmdSend;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JRadioButton jsp;
    private javax.swing.JLabel labelHostname;
    private javax.swing.JLabel labelPort;
    private javax.swing.JLabel labelProtocol;
    private javax.swing.JList<String> listLog;
    private javax.swing.JScrollPane listScroll;
    private javax.swing.ButtonGroup messageGroup;
    private javax.swing.ButtonGroup protocolGroup;
    private javax.swing.JToggleButton tglPub;
    private javax.swing.JToggleButton tglSub;
    private javax.swing.JToggleButton tglUnsub;
    private javax.swing.JTextField txtHostname;
    private javax.swing.JTextArea txtMessage;
    private javax.swing.JTextField txtPort;
    private javax.swing.JRadioButton xjsp;
    // End of variables declaration//GEN-END:variables

    private void disconnect() {
        try {
            //Close the subscriber
            this.subEndpoint.close();
            this.subEndpoint = null;

            //Close the publisher
            this.pubEndpoint.close();
            this.pubEndpoint = null;

            this.setConnected(false);
        } catch (Throwable ex) {
            log(ex.getMessage());
        }
    }

    private void connect() {
        try {
            String protocol = protocolGroup.getSelection().getActionCommand();
            URI url = URI.create(protocol + "://" + txtHostname.getText() + ":" + txtPort.getText());
            IConnectionFactory factory = ConnectionFactory.createFactory(url);
            this.pubEndpoint = factory.openPubEndpoint();
            this.subEndpoint = factory.openSubEndpoint(this);
            this.subEndpoint.addNotificationListener(this);
            this.setConnected(true);
        } catch (Throwable ex) {
            log(ex.getMessage());
            ex.printStackTrace(System.out);
        }
    }

    @Override
    public void receiveNotification(Notification notification) {
        this.log("Received " + notification.toJSONString());
    }

    @Override
    public void receiveAdvertise(Advertise advertise) {

        this.log("Advertise " + advertise.toString());
    }

    @Override
    public void receiveUnadvertise(Advertise advertise) {
        this.log("Unadvertise " + advertise.toString());
    }

    private void log(String line) {

        String time = new SimpleDateFormat("HH:mm:ss - ").format(new Date());
        SwingUtilities.invokeLater(new AddLine(time + line));
    }

    private class AddLine implements Runnable {

        private String line;

        public AddLine(String line) {
            this.line = line;
        }

        @Override
        public void run() {
            logModel.addElement(line);
            listLog.ensureIndexIsVisible(logModel.size() - 1);
        }
    }

    private void setConnected(boolean connected) {

        this.connected = connected;
        cmdSend.setEnabled(connected);
        cmdConnect.setText(connected ? "Disconnect" : "Connect");
    }

    private JSONObject getMessageAsJSON() {
        try {
            JSONParser parser = new JSONParser();
            return (JSONObject) parser.parse(txtMessage.getText());
        } catch (Throwable ex) {
            log(ex.getMessage());
            throw new IllegalStateException();
        }
    }
}