org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java Source code

Java tutorial

Introduction

Here is the source code for org.abondar.industrial.videorouterdemo.client.MainEntryPoint.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.abondar.industrial.videorouterdemo.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.Window;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.sencha.gxt.data.shared.loader.ListLoadResult;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.form.PasswordField;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.FieldLabel;
import com.sencha.gxt.widget.core.client.form.FormPanel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Alex Bondar abondar@cisco.com
 */
public class MainEntryPoint implements EntryPoint {

    private VerticalPanel vp;
    private TextField address;
    private TextField username;
    private PasswordField password;
    private HorizontalPanel hp;
    private HorizontalPanel hpUser;
    private HorizontalPanel hpPwd;
    private FieldLabel addrLabel;
    private FieldLabel userLabel;
    private FieldLabel passwordLabel;
    private TextButton saveAddr;
    private TextButton update;
    private FieldLabel conTime;
    private HorizontalPanel hp1;
    private VerticalPanel vp1;
    private FramedPanel fp;
    private FormPanel form;
    private final ArrayList<String> monitorData = new ArrayList<>();
    private final ArrayList<SourceBean> sourcesData = new ArrayList<>();
    private final ArrayList<ConnectionBean> connections = new ArrayList<>();
    private String prevSourceName;

    private ArrayList<String> monitor;

    @Override
    public void onModuleLoad() {

        vp = new VerticalPanel();
        hp = new HorizontalPanel();
        hpUser = new HorizontalPanel();
        hpPwd = new HorizontalPanel();
        addrLabel = new FieldLabel(address, "IP address and port");
        address = new TextField();
        saveAddr = new TextButton("Save address");
        update = new TextButton("Update sources and monitors");
        conTime = new FieldLabel();
        username = new TextField();
        userLabel = new FieldLabel(username, "Username");
        password = new PasswordField();
        passwordLabel = new FieldLabel(password, "Password");
        fp = new FramedPanel();
        form = new FormPanel();

        RootPanel.get().add(fp);

        fp.setHeadingText("Video router demo");
        fp.add(form);
        form.add(vp, new MarginData(50));

        vp.add(hp);
        vp.add(hpUser);
        vp.add(hpPwd);

        hp.add(addrLabel);
        hp.add(address);
        hpUser.add(userLabel);
        hpUser.add(username);
        hpPwd.add(passwordLabel);
        hpPwd.add(password);
        vp.add(saveAddr);
        vp.add(update);

        saveAddr.addSelectHandler(new SelectEvent.SelectHandler() {

            @Override
            public void onSelect(SelectEvent event) {
                getMonitorsByRest();
                saveAddr.setEnabled(false);
            }
        });

        update.addSelectHandler(new SelectEvent.SelectHandler() {

            @Override
            public void onSelect(SelectEvent event) {

                vp1.clear();
                connections.clear();
                getMonitorsByRest();
            }
        });

    }

    public void showSourcesMonitors() {

        vp1 = new VerticalPanel();
        vp.add(vp1);
        vp.remove(update);
        for (int i = 0; i < monitorData.size(); i++) { //number of outputs loop;
            final Label out = new Label(monitorData.get(i));

            hp1 = new HorizontalPanel();
            hp1.add(out);

            for (final SourceBean sb : sourcesData) {

                vp1.add(hp1);

                final RadioButton rb = new RadioButton(sourcesData.get(i).getName(), sb.getName());

                hp1.add(rb);

                if (rb.getText().equals("")) {
                    hp1.remove(rb);
                }
                if (rb.getText().equals("Undefined Source")) {
                    rb.setEnabled(false);
                }

                for (ConnectionBean cb : connections) {
                    for (String s : cb.getSourceID()) {
                        for (String ss : cb.getDestnation()) {
                            if (out.getText().equals(ss) && sb.getId().equals(s)) {
                                rb.setValue(true);
                                prevSourceName = cb.getName().substring(7);
                                monitor = new ArrayList<>();
                                monitor.add(ss);
                            }
                        }

                    }
                }

                rb.addClickHandler(new ClickHandler() {

                    @Override
                    public void onClick(ClickEvent event) {

                        String sourceID = "";
                        if (sb.getName().equals(rb.getText())) {
                            sourceID = sb.getId();

                        }
                        if (monitor == null) {
                            monitor = new ArrayList<>();

                        } else if (prevSourceName.equals(rb.getText()) == false) {
                            monitor.clear();
                        }
                        monitor.add(out.getText());

                        if (rb.getText().equals(prevSourceName)) {
                            rb.setValue(Boolean.TRUE);
                        }
                        deleteConnection("Connect" + prevSourceName, sourceID, rb.getText());
                        prevSourceName = rb.getText();
                    }

                });

            }

        }
        vp.add(update);

    }

    public void getMonitorsByRest() {

        try {
            String url = URL.encode("http://localhost:8084/VideoRestService/vrService/monitors");

            RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

            builder.setRequestData(parseCredentialsToJSON());
            builder.setHeader("Content-type", "application/json");

            RequestCallback rc = new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {

                    try {

                        MonitorRootObjectAutoBeanFactory factory = GWT
                                .create(MonitorRootObjectAutoBeanFactory.class);
                        MonitorReader mr = new MonitorReader(factory, MonitorRootObject.class);
                        ListLoadResult<Device> mons = mr.read(null, response.getText());
                        List<Device> monList = mons.getData();

                        for (Device mn : monList) {
                            monitorData.add(mn.getName());
                        }

                    } catch (Exception e) {
                        Window.alert("Parsing error " + e.toString());

                    }

                    getSourcesByRest();
                    getConnected();

                }

                @Override
                public void onError(Request request, Throwable exception) {
                    Window.alert("Connection failed  " + exception.toString() + " " + showTime());
                }

            };

            builder.setCallback(rc);
            builder.send();

        } catch (RequestException ex) {

            Window.alert("Connection failed  " + ex.toString() + " " + showTime());

        }

    }

    public void getConnected() {
        try {
            String url = URL.encode("http://localhost:8084/VideoRestService/vrService/rules");

            RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

            builder.setRequestData(parseCredentialsToJSON());
            builder.setHeader("Content-type", "application/json");
            builder.setIncludeCredentials(true);

            RequestCallback rc = new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {

                    RuleRootObjectAutoBeanFactory factory = GWT.create(RuleRootObjectAutoBeanFactory.class);
                    RuleReader rr = new RuleReader(factory, RuleRootObject.class);
                    ListLoadResult<Rule> rll = rr.read(null, response.getText());
                    List<Rule> ruleList = rll.getData();

                    for (Rule r : ruleList) {
                        ConnectionBean cb = new ConnectionBean();

                        cb.setDestnation(r.getDevice());
                        cb.setSourceID(r.getSourcePort());
                        cb.setName(r.getName());
                        connections.add(cb);
                    }

                }

                @Override
                public void onError(Request request, Throwable exception) {

                    Window.alert("Can't get data  " + exception.toString() + " " + showTime());
                }

            };
            builder.setCallback(rc);
            builder.send();

        } catch (RequestException ex) {
            Window.alert("Can't get data  " + ex.toString() + " " + showTime());

        }

    }

    public void getSourcesByRest() {

        try {
            String url = URL.encode("http://localhost:8084/VideoRestService/vrService/sources");

            RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

            builder.setRequestData(parseCredentialsToJSON());
            builder.setHeader("Content-type", "application/json");
            builder.setIncludeCredentials(true);

            RequestCallback rc = new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {

                    hp.add(conTime);
                    conTime.setText("Connection time  " + showTime());

                    try {
                        SourcesRootObjectAutoBeanFactory factory = GWT
                                .create(SourcesRootObjectAutoBeanFactory.class);
                        SourceReader sr = new SourceReader(factory, SourcesRootObject.class);
                        ListLoadResult<Source> src = sr.read(null, response.getText());
                        List<Source> srcList = src.getData();

                        for (Source sc : srcList) {
                            SourceBean sb = new SourceBean();
                            sb.setId(sc.getNodeConnector());
                            if (sc.getMonitorPortType().equals("Edge-SPAN")) {
                                if (sc.getDescription().equals("") || sc.getDescription() == null) {
                                    sb.setName("Undefined Source");

                                } else {
                                    sb.setName(sc.getDescription());

                                }
                            }
                            sourcesData.add(sb);

                        }
                    } catch (Exception e) {
                        Window.alert("Parsing error " + e.toString());

                    }

                    showSourcesMonitors();

                    monitorData.clear();
                    sourcesData.clear();

                }

                @Override
                public void onError(Request request, Throwable exception) {

                    Window.alert("Connection failed  " + exception.toString() + " " + showTime());
                }

            };
            builder.setCallback(rc);
            builder.send();

        } catch (RequestException ex) {
            Window.alert("Connection failed  " + ex.toString() + " " + showTime());

        }

    }

    public void establishConnection(String sourceID, String source) {

        try {

            String url = URL.encode("http://localhost:8084/VideoRestService/vrService/connect");

            RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

            builder.setRequestData(parseRuleToJSON(sourceID, source));
            builder.setHeader("Content-type", "application/json");

            RequestCallback rc = new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {
                    if (response.getStatusCode() == 200 || response.getStatusCode() == 201) {
                        Window.alert("Connection established " + showTime() + "\n" + response.getText());

                    } else {
                        Window.alert(
                                "Can't establish a connection due to " + response.getText() + " " + showTime());

                    }
                }

                @Override
                public void onError(Request request, Throwable exception) {

                    Window.alert("Can't establish a connection  " + exception.toString());

                }

            };

            builder.setCallback(rc);
            builder.send();

        } catch (RequestException ex) {

            Window.alert("Can't establish a connection  " + ex.toString());

        }
    }

    public void deleteConnection(String srcNameTODelete, final String sourceID, final String srcnameToConnect) {

        try {
            String url = URL.encode("http://localhost:8084/VideoRestService/vrService/delete");

            RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

            builder.setRequestData(parseRuleNameToJSON(srcNameTODelete));
            builder.setHeader("Content-type", "application/json");

            RequestCallback rc = new RequestCallback() {

                @Override
                public void onResponseReceived(Request request, Response response) {
                    establishConnection(sourceID, srcnameToConnect);
                }

                @Override
                public void onError(Request request, Throwable exception) {

                    Window.alert("Can't delete a connection  " + exception.toString());

                }

            };

            builder.setCallback(rc);
            builder.send();

        } catch (RequestException ex) {

            Window.alert("Can't delete a connection  " + ex.toString());

        }
    }

    public String parseCredentialsToJSON() {

        JSONObject requestObject = new JSONObject();

        requestObject.put("address", new JSONString(address.getText()));
        requestObject.put("username", new JSONString(username.getText()));
        requestObject.put("password", new JSONString(password.getText()));

        return requestObject.toString();
    }

    public String parseRuleNameToJSON(String name) {
        JSONObject param = new JSONObject();

        JSONObject creds = new JSONObject();

        creds.put("address", new JSONString(address.getText()));
        creds.put("username", new JSONString(username.getText()));
        creds.put("password", new JSONString(password.getText()));

        param.put("creds", creds);

        JSONObject requestObject = new JSONObject();

        requestObject.put("name", new JSONString(name));

        param.put("ruleName", requestObject);
        return param.toString();
    }

    public String parseRuleToJSON(String sourceID, String source) {

        JSONObject param = new JSONObject();

        JSONObject creds = new JSONObject();

        creds.put("address", new JSONString(address.getText()));
        creds.put("username", new JSONString(username.getText()));
        creds.put("password", new JSONString(password.getText()));

        param.put("creds", creds);

        JSONObject requestObject = new JSONObject();

        requestObject.put("name", new JSONString("Connect" + source));
        JSONArray jsa1 = new JSONArray();
        jsa1.set(0, new JSONString("matchAll"));
        requestObject.put("allowFilter", jsa1);
        JSONArray jsa2 = new JSONArray();
        for (int i = 0; i < monitor.size(); i++) {
            jsa2.set(i, new JSONString(monitor.get(i)));
        }
        requestObject.put("device", jsa2);
        JSONArray jsa3 = new JSONArray();
        jsa3.set(0, new JSONString(sourceID));
        requestObject.put("sourcePort", jsa3);
        requestObject.put("installInHw", new JSONString("true"));

        param.put("rule", requestObject);

        return param.toString();
    }

    public native void consoleLog(String message) /*-{
                                                  console.log(  message );
                                                  }-*/;

    public String showTime() {

        Date date = new Date();
        String time = DateTimeFormat.getMediumDateTimeFormat().format(date);

        return time;
    }

}