eu.wordnice.wnconsole.WNCUtils.java Source code

Java tutorial

Introduction

Here is the source code for eu.wordnice.wnconsole.WNCUtils.java

Source

/*
 The MIT License (MIT)
    
 Copyright (c) 2015, Dalibor Drgo <emptychannelmc@gmail.com>
    
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
    
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
    
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 */

package eu.wordnice.wnconsole;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.json.simple.JSONObject;

import eu.wordnice.api.Api;
import eu.wordnice.api.Handler;
import eu.wordnice.api.Map;
import eu.wordnice.api.Set;
import eu.wordnice.sockets.HIO;
import eu.wordnice.sockets.HIOServer;

public class WNCUtils {

    private static long tid = 0;

    public static void writeHeaders(HIO hio, String status, int len) throws IOException {
        hio.out.write(new String(hio.REQTYPE + " " + status + "\r\nContent-Type: application/json"
                + "\r\nContent-Length: " + len + "\r\nConnection: close\r\n\r\n").getBytes());
    }

    public static String replaceBuiltinVars(String in) {
        String nev = Api.getColoredString(in).replace("$n", "\n").replace("$t", "    ").replace("\t", "    ")
                .replace("$server_ip", Bukkit.getIp()).replace("$port", "" + Bukkit.getPort())
                .replace("$motd", Bukkit.getMotd()).replace("$max_players", "" + Bukkit.getMaxPlayers())
                .replace("$time", "" + System.currentTimeMillis())
                /*
                 * When compiling for newer versions, change to
                 * .replace("$players", "" + Bukkit.getOnlinePlayers().size());
                 */
                .replace("$players", "" + Bukkit.getOnlinePlayers().length);

        int befend = 0;
        while (true) {
            int start = nev.indexOf("$date[[", befend);
            if (start != -1) {
                int end = nev.lastIndexOf("]]", start + 7);
                if (end != -1) {
                    if (end == start + 7) {
                        String formatdate = new Date().toString();
                        befend = start + formatdate.length();
                        nev = nev.substring(0, start) + formatdate + nev.substring(end + 2, nev.length());
                    }
                    try {
                        DateFormat tf = new SimpleDateFormat(nev.substring(start + 7, end));
                        String formatdate = tf.format(new Date());
                        befend = start + formatdate.length();
                        nev = nev.substring(0, start) + formatdate + nev.substring(end + 2, nev.length());
                    } catch (Throwable t) {
                        String formatdate = new Date().toString();
                        befend = start + formatdate.length();
                        nev = nev.substring(0, start) + formatdate + nev.substring(end + 2, nev.length());
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        return nev.replace("$date", new Date().toString());
    }

    public static String replacePlayerVars(Player cur_player, String in) {
        return in.replace("$name", cur_player.getName()).replace("$dname", cur_player.getDisplayName())
                .replace("$ip", cur_player.getAddress().getAddress().getHostAddress());
    }

    public static Set<Player> getOnlinePlayers() {
        Set<Player> players_set = new Set<Player>();
        /*
         * When compiling for newer versions, change to
         * player_set.addAllWC(Bukkit.getOnlinePlayers());
         */
        players_set.addAllXWC(Bukkit.getOnlinePlayers());
        return players_set;
    }

    public static Set<Plugin> getPlugins() {
        Set<Plugin> set = new Set<Plugin>();
        set.addAllXWC(Bukkit.getPluginManager().getPlugins());
        return set;
    }

    public static Set<World> getWorlds() {
        Set<World> set = new Set<World>();
        set.addAllWC(Bukkit.getWorlds());
        return set;
    }

    public static String addOnlinePlayer(Set<Player> set, String name) {
        Player cur_player = null;
        Player loop_player = null;
        Set<Player> players_set = getOnlinePlayers();
        int i3 = 0;
        for (; i3 < players_set.size(); i3++) {
            loop_player = players_set.get(i3);
            if (loop_player.getName().equals(name)) {
                cur_player = loop_player;
                break;
            }
        }
        if (cur_player == null) {
            return null;
        }
        set.add(cur_player);
        return cur_player.getName();
    }

    public static String addOnlinePlayerUUID(Set<Player> set, String uid) {
        try {
            java.util.UUID unq = java.util.UUID.fromString(uid);
            Player cur_player = null;
            Player loop_player = null;
            Set<Player> players_set = getOnlinePlayers();
            int i3 = 0;
            for (; i3 < players_set.size(); i3++) {
                loop_player = players_set.get(i3);
                if (loop_player.getUniqueId().equals(unq)) {
                    cur_player = loop_player;
                    break;
                }
            }
            if (cur_player == null) {
                return null;
            }
            set.add(cur_player);
            return cur_player.getName();
        } catch (Throwable t) {
        }
        return WNCUtils.addOnlinePlayer(set, uid);
    }

    public static String addPlugin(Set<Plugin> set, String name) {
        Plugin cur = null;
        Plugin loope = null;
        Set<Plugin> allset = getPlugins();
        int i3 = 0;
        for (; i3 < allset.size(); i3++) {
            loope = allset.get(i3);
            if (loope.getName().equals(name)) {
                cur = loope;
                break;
            }
        }
        if (cur == null) {
            return null;
        }
        set.add(cur);
        return cur.getName();
    }

    public static String addWorld(Set<World> set, String name) {
        World cur = null;
        World loope = null;
        Set<World> allset = getWorlds();
        int i3 = 0;
        for (; i3 < allset.size(); i3++) {
            loope = allset.get(i3);
            if (loope.getName().equals(name)) {
                cur = loope;
                break;
            }
        }
        if (cur == null) {
            return null;
        }
        set.add(cur);
        return cur.getName();
    }

    public static String addWorldUUID(Set<World> set, String name) {
        try {
            UUID uid = UUID.fromString(name);
            World cur = null;
            World loope = null;
            Set<World> allset = getWorlds();
            int i3 = 0;
            for (; i3 < allset.size(); i3++) {
                loope = allset.get(i3);
                if (loope.getUID().equals(uid)) {
                    cur = loope;
                    break;
                }
            }
            if (cur == null) {
                return null;
            }
            set.add(cur);
            return cur.getName();
        } catch (Throwable t) {
        }
        return WNCUtils.addWorld(set, name);
    }

    public static Map<String, Object> sortObject(JSONObject jo) {
        Object[] names = new Object[jo.size()];
        Object[] values = new Object[jo.size()];
        boolean[] used = new boolean[jo.size()];
        boolean curHas = false;
        Object[] in = jo.keySet().toArray();
        int i = 0;
        int i2 = 0;
        for (; i < jo.size(); i++) {
            curHas = false;
            for (i2 = 0; i2 < jo.size(); i2++) {
                String cname = (String) in[i2];
                if (!used[i2] && cname.startsWith("get")) {
                    names[i] = ("" + cname);
                    values[i] = jo.get(cname);
                    used[i2] = true;
                    curHas = true;
                    break;
                }
            }
            if (!curHas) {
                break;
            }
        }

        i2 = 0;
        for (/* continue */; i < jo.size(); i++) {
            for (/* continue */; i2 < jo.size(); i2++) {
                String cname = (String) in[i2];
                if (!used[i2]) {
                    names[i] = cname;
                    values[i] = jo.get(cname);
                    used[i2] = true;
                    curHas = true;
                    break;
                }
            }
        }
        Map<String, Object> map = new Map<String, Object>();
        map.names = names;
        map.values = values;
        map.size = names.length;
        return map;
    }

    /*** PROTECTED ***/
    protected static Handler.OneVoidHandler<Logger> createOnDisable(final ServerSocket sock) {
        return new Handler.OneVoidHandler<Logger>() {
            @Override
            public void handle(Logger lg) {
                try {
                    sock.close();
                    lg.info("WNConsole was disabled!");
                } catch (Throwable tr) {
                    lg.severe("Ups, cannot close server service! Details:");
                    tr.printStackTrace();
                }
            }
        };
    }

    protected static Thread createHIOThread(final HIOServer serv, final Handler.TwoVoidHandler<Thread, HIO> handl,
            final boolean debug, final long timeout, final Logger lg) {
        return new Thread() {
            @Override
            public void run() {
                serv.onAcceptRaw(new Handler.OneVoidHandler<Socket>() {
                    @Override
                    public void handle(Socket sock) {
                        try {
                            final HIO hio = new HIO(sock);
                            Thread rt = new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        hio.decode(false, timeout);
                                        handl.handle(this, hio);
                                    } catch (Throwable th) {
                                        if (debug) {
                                            lg.info("Error while accepting client from "
                                                    + hio.sock.getInetAddress().toString() + ", path [" + hio.PATH
                                                    + "], error " + th.getMessage());
                                        }
                                    }
                                    try {
                                        hio.close();
                                    } catch (Throwable tign) {
                                    }
                                }
                            };
                            tid++;
                            rt.setName("WNC HIO Handle " + tid);
                            rt.start();
                        } catch (Throwable t) {
                        }
                    }
                });
            }
        };
    }

    public static Object checkYaml(Object in) {
        if (in instanceof Configuration) {
            return WNCUtils.YamlToMap((Configuration) in);
        } else if (in instanceof Map<?, ?>) {
            Map<String, Object> retv = new Map<String, Object>();
            java.util.Map<?, ?> inm = (java.util.Map<?, ?>) in;
            java.util.Set<?> keys = inm.keySet();
            int size = keys.size();
            Object[] keys_arr = keys.toArray();
            Object key = null;
            int i = 0;
            for (; i < size; i++) {
                key = keys_arr[i];
                retv.addWC(("" + key), WNCUtils.checkYaml(inm.get(key)));
            }
            return retv;
        } else if (in instanceof Collection<?>) {
            Set<Object> retv = new Set<Object>();
            Collection<?> inc = (Collection<?>) in;
            int size = inc.size();
            Object[] keys_arr = inc.toArray();
            int i = 0;
            for (; i < size; i++) {
                retv.addWC(WNCUtils.checkYaml(keys_arr[i]));
            }
            return retv;
        }
        return in;
    }

    public static Map<String, Object> YamlToMap(Configuration cf) {
        Map<String, Object> retv = new Map<String, Object>();
        java.util.Set<String> keys = cf.getKeys(false);
        int size = keys.size();
        Object[] keys_arr = keys.toArray();
        String key = null;
        int i = 0;
        for (; i < size; i++) {
            key = (String) keys_arr[i];
            retv.addWC(key, WNCUtils.checkYaml(cf.get(key)));
        }
        return retv;
    }

}