com.mhs.hboxmaintenanceserver.HBoxMaintenanceServer.java Source code

Java tutorial

Introduction

Here is the source code for com.mhs.hboxmaintenanceserver.HBoxMaintenanceServer.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 com.mhs.hboxmaintenanceserver;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mhs.hboxmaintenanceserver.bean.Editor;
import com.mhs.hboxmaintenanceserver.bean.HBox;
import com.mhs.hboxmaintenanceserver.bean.Log;
import com.mhs.hboxmaintenanceserver.config.DefaultConfig;
import com.mhs.hboxmaintenanceserver.interf.ProcessInterface;
import com.mhs.hboxmaintenanceserver.utils.DCXLogger;
import com.mhs.hboxmaintenanceserver.utils.HBox_Actions;
import com.mhs.hboxmaintenanceserver.utils.Utils;
import com.mhs.hboxmaintenanceserver.utils.Utils.Host;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.ParseException;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.server.Session;
import org.glassfish.grizzly.http.server.accesslog.AccessLogBuilder;
import org.java_websocket.WebSocket;

/**
 *
 * @author Zulhaizat
 */
public class HBoxMaintenanceServer implements ProcessInterface {

    public static String DEFAULT_P;

    private final int webserver_port;
    private final int websocket_port;

    private HBoxMaintenanceWebsocketServer hbmws;
    private HttpServer httpServer;
    private Host[] hosts;
    private String[] actions;
    private ThreadGroup threadGroup_LOG;

    public HBoxMaintenanceServer(String default_p) throws Exception {
        DEFAULT_P = default_p;
        Utils.checkFoldersAvailability();
        Utils.encodeAllPropValues(Utils.createDefaultPropFile());
        Utils.encodeAllPropValues(Utils.createHBoxPropFile());
        Utils.encodeAllPropValues(Utils.createWIFI_PROP_file());

        webserver_port = Integer.parseInt(Utils.getDefaultPropValues("web-server-port"));
        websocket_port = Integer.parseInt(Utils.getDefaultPropValues("web-socket-port"));
    }

    private byte[] getContent(String uri, Response response, Request request)
            throws IOException, URISyntaxException, ParseException {
        String ext = uri.substring(uri.lastIndexOf('.') + 1).toLowerCase();
        byte[] b;
        switch (ext) {
        case "htm":
        case "html":
            response.setContentType("text/html; charset=UTF-8");
            b = processString(uri, request);
            break;
        case "css":
            response.setContentType("text/css");
            b = processByte(uri);
            break;
        case "js":
            response.setContentType("text/javascript");
            b = processByte(uri);
            break;
        case "png":
        case "gif":
        case "jpg":
        case "jpeg":
        case "bitmap":
            response.setContentType("image/" + Utils.getExt(ext));
            b = processByte(uri);
            break;
        case "ttf":
            response.setContentType("application/x-font-ttf");
            b = processByte(uri);
            break;
        case "otf":
            response.setContentType("application/x-font-opentype");
            b = processByte(uri);
            break;
        default:
            response.setContentType("text/html; charset=UTF-8");
            if (getLoginSession(request.getSession()) != null) {
                b = processString("/index.html", request);
            } else {
                b = processString("/login.html", request);
            }
        }

        return b;
    }

    private byte[] processByte(String uri) throws IOException {
        return Utils.getBytesFromResource("/HBoxMaintenanceServer_GUI/public_html" + uri);
    }

    private byte[] processString(String uri, Request request) throws IOException, URISyntaxException {
        byte[] b = processByte(uri);
        if (b == null) {
            return null;
        }
        String content = new String(b, "UTF-8");
        switch (uri) {
        case "/index.html":
            content = content.replace("<websocket_port>", Utils.getDefaultPropValues("web-socket-port"))
                    .replace("<code-editor-theme>", Utils.getDefaultPropValues("code-editor-theme"));
            break;
        }
        if (content.contains("__editor-theme__")) {
            String[] themes = Utils
                    .getResourceListing("HBoxMaintenanceServer_GUI/public_html/css/codemirror/theme/");
            String themeCSS = "";
            if (themes != null) {
                for (String theme : themes) {
                    themeCSS += "<div class='dcx-editor-theme'>/css/codemirror/theme/"
                            + theme.replace("/dcx/public_html", "") + "</div>\n";
                }
                content = content.replaceAll("__editor-theme__", themeCSS);
            }
        }
        return content.getBytes("UTF-8");
    }

    private class Login {

        /**
         * @return the username
         */
        public String getUsername() {
            return username;
        }

        /**
         * @return the password
         */
        public String getPassword() {
            return password;
        }

        private final String username;
        private final String password;

        public Login(String username, String password) {
            this.username = username;
            this.password = password;
        }

    }

    private Login getLoginSession(Session session) {
        if (session.getAttribute("user-login") == null) {
            return null;
        }
        return (Login) session.getAttribute("user-login");
    }

    private boolean saveLoginSession(Session session, String _username, String _password) {
        String username = Utils.getDefaultPropValues("login-username");
        String password = Utils.getDefaultPropValues("login-password");

        if (username.trim().equals(_username.trim()) && password.trim().equals(_password.trim())) {
            session.setAttribute("user-login", new Login(username, password));

            return true;
        } else {
            return false;
        }
    }

    public void start() {
        try {
            hbmws = new HBoxMaintenanceWebsocketServer(this, websocket_port);
            hbmws.start();
            hbmws.sendListOfHBoxBy_Interval();

            httpServer = HttpServer.createSimpleServer(null, webserver_port);
            AccessLogBuilder logBuilder = new AccessLogBuilder(DefaultConfig.GRIZZLY_LOG);
            logBuilder.rotatedDaily().instrument(httpServer.getServerConfiguration());

            HBoxMaintenanceServer hbms = this;
            httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() {

                private void sendGSON_to_web(OutputStream gos, Gson gson, Object obj) {
                    try (PrintWriter pw = new PrintWriter(gos)) {
                        pw.write(gson.toJson(obj));
                        pw.close();
                    }
                }

                @Override
                public void service(Request request, Response response) throws Exception {
                    OutputStream gos = response.getOutputStream();
                    String uri = request.getRequestURI();
                    String path = uri.substring(uri.lastIndexOf("/") + 1).trim().toLowerCase();
                    Gson gson = (new GsonBuilder()).create();
                    String ip_address, hostname;
                    HBox_Actions hba;
                    Thread thread;
                    Editor editor;

                    switch (path) {
                    case "list_drivers":
                        String[] __paths = new String[0];
                        File driverFolder = new File(DefaultConfig.DRIVERS_FOLDER);
                        if (driverFolder.exists()) {
                            File[] paths = driverFolder.listFiles((File pathname) -> {
                                String ext = pathname.getAbsolutePath();
                                ext = ext.substring(ext.lastIndexOf(".") + 1).trim().toLowerCase();

                                return ext.equals("kar");
                            });
                            __paths = new String[paths.length];
                            int k = 0;
                            for (File _path : paths) {
                                __paths[k] = _path.getName();
                                k++;
                            }
                        }
                        sendGSON_to_web(gos, gson, __paths);
                        break;
                    case "reboot_hbox":
                        hostname = request.getParameter("hostname");
                        ip_address = request.getParameter("ip_address");

                        if (hostname != null && ip_address != null) {
                            hba = new HBox_Actions(ip_address, hostname,
                                    hbmws.getConns().toArray(new WebSocket[hbmws.getConns().size()]),
                                    new String[] { "hbox_reboot" }, threadGroup_LOG, hbms);
                            thread = new Thread(hba);
                            thread.start();
                        }
                        break;
                    case "start":
                        String result1 = request.getParameter("result");
                        String[] drivers = null;
                        if (request.getParameter("drivers") != null) {
                            drivers = (String[]) gson.fromJson(request.getParameter("drivers"), String[].class);
                        }
                        HBox hb = (HBox) gson.fromJson(result1, HBox.class);
                        hosts = hb.getHosts();
                        actions = hb.getActions();
                        for (Host host : hosts) {
                            try {
                                HBox_Actions hba1 = new HBox_Actions(host.getIp_address(), host.getHost_name(),
                                        hbmws.getConns().toArray(new WebSocket[hbmws.getConns().size()]), actions,
                                        threadGroup_LOG, hbms);
                                if (drivers != null) {
                                    hba1.setDrivers(drivers);
                                }
                                thread = new Thread(hba1);
                                thread.start();
                            } catch (Exception ex) {
                                DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex);
                            }
                        }
                        break;
                    case "crontab":
                        editor = new Editor(DefaultConfig.HBOX_CRONTAB,
                                FileUtils.readFileToString(new File(DefaultConfig.HBOX_CRONTAB), "UTF-8"));
                        sendGSON_to_web(gos, gson, editor);
                        break;
                    case "wpa_supplicant":
                        editor = new Editor(DefaultConfig.HBOX_WIFI,
                                FileUtils.readFileToString(new File(DefaultConfig.HBOX_WIFI), "UTF-8"));
                        sendGSON_to_web(gos, gson, editor);
                        break;
                    case "apply_changes":
                        String file = request.getParameter("file");
                        String content = request.getParameter("content");

                        if (file != null && content != null) {
                            String[] contents;
                            if (content.contains("\r\n")) {
                                contents = content.split("\r\n");
                            } else if (content.contains("\n\r")) {
                                contents = content.split("\n\r");
                            } else {
                                contents = content.split("\r");
                            }
                            if (file.equals("wpa_supplicant.conf") || file.equals("crontab")) {
                                try (BufferedWriter bw = Files.newBufferedWriter(
                                        Paths.get(DefaultConfig.HBOX_FOLDER + File.separator + file),
                                        Charset.forName("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING)) {
                                    for (String s : contents) {
                                        bw.write(s);
                                        bw.write("\n");
                                    }
                                    bw.close();
                                }
                            }
                        }
                        break;
                    case "logout":
                        request.getSession().removeAttribute("user-login");
                        try (PrintWriter pw = new PrintWriter(gos)) {
                            pw.write("1");
                        }
                        break;
                    case "login":
                        String username = request.getParameter("username");
                        String password = request.getParameter("password");

                        try (PrintWriter pw = new PrintWriter(gos)) {
                            if (username != null && password != null) {
                                if (saveLoginSession(request.getSession(), username, password)) {
                                    pw.write("1");
                                } else {
                                    pw.write("0");
                                }
                            } else {
                                pw.write("0");
                            }
                        }
                        break;
                    default:
                        gos.write(getContent(uri, response, request));
                    }
                }
            });

            httpServer.start();
        } catch (IOException ex) {
            DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex);
        }
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            try {
                HBoxMaintenanceServer hbms = new HBoxMaintenanceServer(args[0].trim());
                if (args.length == 1) {
                    hbms.start();
                }
            } catch (Exception ex) {
                DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex);
            }
        }
    }

    @Override
    public void processCompleted(String hostname) {
        hbmws.getConns().stream().filter((socket) -> (!socket.isClosed())).forEachOrdered((socket) -> {
            if (!socket.isClosed()) {
                while (true) {
                    if (!socket.hasBufferedData()) {
                        socket.send("-done-");
                        break;
                    }
                }
            }
        });
    }

    @Override
    public void logOutput(Log log) {
        hbmws.getConns().stream().filter((socket) -> (!socket.isClosed())).forEachOrdered((socket) -> {
            if (!socket.isClosed()) {
                while (true) {
                    if (!socket.hasBufferedData()) {
                        socket.send((new GsonBuilder().create()).toJson(log));
                        break;
                    }
                }
            }
        });
    }

    /**
     * @return the threadGroup_LOG
     */
    public ThreadGroup getThreadGroup_LOG() {
        return threadGroup_LOG;
    }

    /**
     * @param threadGroup_LOG the threadGroup_LOG to set
     */
    public void setThreadGroup_LOG(ThreadGroup threadGroup_LOG) {
        this.threadGroup_LOG = threadGroup_LOG;
    }
}