de.emc.plugin.Plugin.java Source code

Java tutorial

Introduction

Here is the source code for de.emc.plugin.Plugin.java

Source

/*
 * Copyright (C) 2015 Jonas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.emc.plugin;

import com.google.common.base.Charsets;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import de.emc.chat.Chat;
import de.emc.config.Store;
import de.emc.login.Skip;
import de.emc.premium.Ball;
import de.emc.premium.Fly;
import de.emc.sense.Sense;
import de.emc.speed.Speed;
import de.emc.team.Team;
import de.emc.ticket.Ticket;
import de.emc.utilities.Utilities;
import de.emc.warns.Warns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.messaging.PluginMessageListener;

/**
 *
 * @author Jonas
 */
public class Plugin extends JavaPlugin implements Listener, PluginMessageListener {
    public final Plugin plugin = this;
    public static boolean debug = false;
    private static final Logger LOG = Logger.getLogger(Plugin.class.getName());
    public Store Store = new Store(this);
    public Chat Chat;
    public Sense Sense;
    public Speed Speed;
    public Team Team;
    public Ticket Ticket;
    public Fly Fly;
    public Ball Ball;
    public Warns Warns;
    public Skip Skip;
    public static boolean Chat_loaded = false;
    public static boolean Sense_loaded = false;
    public static boolean Speed_loaded = false;
    public static boolean Team_loaded = false;
    public static boolean Ticket_loaded = false;
    public static boolean Fly_loaded = false;
    public static boolean Ball_loaded = false;
    public static boolean Warns_loaded = false;
    public static boolean Skip_loaded = false;
    public HashMap<String, ArrayList<org.bukkit.block.Sign>> signs = new HashMap<>();

    @Override
    public void onEnable() {
        this.getServer().getLogger().info("Performing Init");
        File f = new File(getDataFolder() + File.separator + "config.yml");
        if (!f.exists()) {
            this.saveDefaultConfig();
            this.getServer().getLogger().info("Saving Default Config");
        }
        File file = new File(getDataFolder() + File.separator + "load.dat");
        file.delete();
        if (!file.exists()) {
            copy(getResource("load.dat"), file);
            this.getServer().getLogger().info("Saving Default Loader");
        }
        File license = new File(getDataFolder() + File.separator + "license.txt");
        if (!file.exists()) {
            copy(getResource("license.txt"), license);
        }
        List<String> lines = null;
        try {
            lines = Files.readLines(file, Charsets.UTF_8);
        } catch (IOException ex) {
            Logger.getLogger(Plugin.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (lines != null) {
            for (String s : lines) {
                if (s.startsWith("//")) {
                    continue;
                }
                if (s.startsWith("Store.assign.add(\"")) {
                    String str = s.replace("Store.assign.add(\"", "");
                    str = str.replace("\");", "");
                    Store.assign.add(str);
                }
                if (s.startsWith("Store.load.add(\"")) {
                    String str = s.replace("Store.load.add(\"", "");
                    str = str.replace("\");", "");
                    Store.load.add(str);
                }
            }
        } else {
            this.getServer().getLogger().severe("Config Load FAILED! Disabling...");
            this.getServer().getPluginManager().disablePlugin(this);
        }
        this.getServer().getLogger().info("Done.");
        Store.onEnable();
        if (Store.getBool("chatstate")) {
            Chat = new Chat(this);
            Chat.onEnable();
            this.getServer().getPluginManager().registerEvents(Chat, this);
            getCommand("cc").setExecutor(Chat);
            getCommand("gbm").setExecutor(Chat);
        }
        if (Store.getBool("sensestate")) {
            Sense = new Sense(this);
            Sense.onEnable();
            this.getServer().getPluginManager().registerEvents(Sense, this);
            getCommand("sense").setExecutor(Sense);
        }
        if (Store.getBool("speedstate")) {
            Speed = new Speed(this);
            Speed.onEnable();
            this.getServer().getPluginManager().registerEvents(Speed, this);
            getCommand("inv").setExecutor(Speed);
        }
        if (Store.getBool("teamstate")) {
            Team = new Team(this);
            Team.onEnable();
            this.getServer().getPluginManager().registerEvents(Team, this);
            getCommand("team").setExecutor(Team);
        }
        if (Store.getBool("ticketstate")) {
            Ticket = new Ticket(this);
            Ticket.onEnable();
            this.getServer().getPluginManager().registerEvents(Ticket, this);
            getCommand("ticket").setExecutor(Ticket);
        }
        if (Store.getBool("flystate")) {
            Fly = new Fly(this);
            Fly.onEnable();
            this.getServer().getPluginManager().registerEvents(Fly, this);
            getCommand("pfly").setExecutor(Fly);
        }
        if (Store.getBool("ballstate")) {
            Ball = new Ball(this);
            Ball.onEnable();
            this.getServer().getPluginManager().registerEvents(Ball, this);
            getCommand("fire").setExecutor(Ball);
        }
        if (Store.getBool("warnsstate")) {
            Warns = new Warns(this);
            Warns.onEnable();
            this.getServer().getPluginManager().registerEvents(Warns, this);
            getCommand("warn").setExecutor(Warns);
            getCommand("warns").setExecutor(Warns);
        }
        if (Store.getBool("skipstate")) {
            Skip = new Skip(this);
            Skip.onEnable();
        }
        this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
        this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", this);
        this.getServer().getPluginManager().registerEvents(this, this);
        String[] load = loadSigns("signs.dat");
        ArrayList<org.bukkit.block.Sign> list = new ArrayList<org.bukkit.block.Sign>();
        for (String s : load) {
            if (s.isEmpty()) {
                continue;
            }
            if (s == "") {
                continue;
            }
            this.getServer().getLogger().info(s);
            String[] split = s.split(Pattern.quote("|"));
            this.getServer().getLogger().info("X: " + split[0]);
            double x = Double.valueOf(split[0]);
            this.getServer().getLogger().info("Y: " + split[1]);
            double y = Double.valueOf(split[1]);
            this.getServer().getLogger().info("Z: " + split[2]);
            double z = Double.valueOf(split[2]);
            this.getServer().getLogger().info("Name: " + split[3]);
            String name = split[3];
            Location loc = new Location(Bukkit.getWorld(Store.getString("world")), x, y, z);
            org.bukkit.block.Sign sign = (org.bukkit.block.Sign) Bukkit.getWorld(Store.getString("world"))
                    .getBlockAt(loc).getState();
            list.add(sign);
            signs.put(name, list);
        }
        this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
            @Override
            public void run() {
                ArrayList<String> strings = new ArrayList<>();
                for (String s : signs.keySet()) {
                    ByteArrayDataOutput out = ByteStreams.newDataOutput();
                    out.writeUTF("GetMotd");
                    out.writeUTF(s);
                    plugin.getServer().sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
                }
            }
        }, Utilities.ticks(2), Utilities.ticks(5));
        this.getServer().getLogger().info(String.valueOf(Store.config.get("pluginon")));
    }

    public static void send(String[] send) {
        System.out.println("Sending Plugin Message...");
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        for (String s : send) {
            out.writeUTF(s);
        }
    }

    @Override
    public void onDisable() {
        if (Store.getBool("warnsstate")) {
            Warns.onDisable();
        }
        if (Store.getBool("flystate")) {
            Fly.onDisable();
        }
        if (Store.getBool("ballstate")) {
            Ball.onDisable();
        }
        if (Store.getBool("chatstate")) {
            Chat.onDisable();
        }
        if (Store.getBool("sensestate")) {
            Sense.onDisable();
        }
        if (Store.getBool("speedstate")) {
            Speed.onDisable();
        }
        if (Store.getBool("teamstate")) {
            Team.onDisable();
        }
        if (Store.getBool("ticketstate")) {
            Ticket.onDisable();
        }
        Store.onDisable();
        File f = new File(getDataFolder() + File.separator + "signs.dat");
        ArrayList<String> strings = new ArrayList<>();
        for (String s : signs.keySet()) {
            ArrayList<org.bukkit.block.Sign> sig = signs.get(s);
            for (org.bukkit.block.Sign si : sig) {
                strings.add(si.getX() + "|" + si.getY() + "|" + si.getZ() + "|" + s);
            }
        }
        f.delete();
        try {
            PrintWriter out = new PrintWriter(getDataFolder() + File.separator + "signs.dat");
            for (String s : strings) {
                out.println(s);
            }
            out.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Plugin.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.getServer().getLogger().info(String.valueOf(Store.config.get("pluginoff")));
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        if (cmd.getName().equalsIgnoreCase("gbc")) {
            if (args.length < 2) {
                return false;
            }
            ByteArrayDataOutput out = ByteStreams.newDataOutput();
            out.writeUTF("Broadcast");
            out.writeUTF(args[0]);
            out.writeUTF(Store.getString("server"));
            String msg = "";
            for (int i = 1; i < args.length; i++) {
                msg = msg + " " + args[i];
            }
            msg = ChatColor.translateAlternateColorCodes('&', msg);
            out.writeUTF(msg);
            this.getServer().sendPluginMessage(this, "BungeeCord", out.toByteArray());
            sender.sendMessage(Store.getString("cmdexecuted"));
            return true;
        }
        return false;
    }

    @SuppressWarnings("NestedAssignment")
    private void copy(InputStream in, File file) {
        try {
            try (OutputStream out = new FileOutputStream(file)) {
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            in.close();
        } catch (IOException e) {
        }
    }

    public void save(String[] strings, String path) {

        try {
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
                for (String s : strings) {
                    oos.writeUTF(s);
                }
                oos.flush();
            }
        } catch (IOException e) {
        }
    }

    @EventHandler
    public void onSignChange(final SignChangeEvent evt) {
        if (evt.getLine(0).equals("[tps]")) {
            evt.setLine(0, "Pinging...");
            this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
                @Override
                public void run() {
                    ByteArrayDataOutput out = ByteStreams.newDataOutput();
                    out.writeUTF("GetMotd");
                    out.writeUTF(evt.getLine(1));
                    if (!signs.containsKey(evt.getLine(1))) {
                        signs.put(evt.getLine(1), new ArrayList<org.bukkit.block.Sign>());
                    }
                    ArrayList<org.bukkit.block.Sign> list = signs.get(evt.getLine(1));
                    org.bukkit.block.Sign s = (org.bukkit.block.Sign) plugin.getServer().getWorld("world")
                            .getBlockAt(evt.getBlock().getLocation()).getState();
                    list.add(s);
                    signs.put(evt.getLine(1), list);
                    plugin.getServer().sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
                }
            }, Utilities.ticks(5));
        }
    }

    public String[] loadSigns(String file) {
        File f = new File(plugin.getDataFolder() + File.separator + file);
        if (!f.exists()) {
            copy(plugin.getResource(file), f);
        }
        List<String> list = new ArrayList<>();
        List<String> lines = null;
        try {
            lines = Files.readLines(f, Charsets.UTF_8);
        } catch (IOException ex) {
            Logger.getLogger(Ball.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (String line : lines) {
            list.add(line);
        }
        String[] ret = list.toArray(new String[list.size()]);
        return ret;
    }

    @Override
    public void onPluginMessageReceived(String channel, Player player, byte[] message) {
        if (!channel.equals("BungeeCord")) {
            return;
        }
        ByteArrayDataInput in = ByteStreams.newDataInput(message);
        String subchannel = in.readUTF();
        if (subchannel.equals("GetMotd")) {
            String server = in.readUTF();
            ArrayList<org.bukkit.block.Sign> list = signs.get(server);
            String motd = in.readUTF();
            String players = in.readUTF();
            String max = in.readUTF();
            String line0 = Store.getString("signline0");
            line0 = line0.replaceAll("%motd%", motd);
            line0 = line0.replaceAll("%players%", players);
            line0 = line0.replaceAll("%max%", max);
            String line1 = Store.getString("signline1");
            line1 = line1.replaceAll("%motd%", motd);
            line1 = line1.replaceAll("%players%", players);
            line1 = line1.replaceAll("%max%", max);
            String line2 = Store.getString("signline2");
            line2 = line2.replaceAll("%motd%", motd);
            line2 = line2.replaceAll("%players%", players);
            line2 = line2.replaceAll("%max%", max);
            String line3 = Store.getString("signline3");
            line3 = line3.replaceAll("%motd%", motd);
            line3 = line3.replaceAll("%players%", players);
            line3 = line3.replaceAll("%max%", max);
            for (org.bukkit.block.Sign s : list) {
                if (line0 == "") {
                    line0 = s.getLine(0);
                }
                s.setLine(0, line0);
                if (line1 == "") {
                    line1 = s.getLine(0);
                }
                s.setLine(1, line1);
                if (line2 == "") {
                    line2 = s.getLine(0);
                }
                s.setLine(2, line2);
                if (line3 == "") {
                    line3 = s.getLine(0);
                }
                s.setLine(3, line3);
                s.update();
            }
        }
        if (subchannel.equals("Broadcast")) {
            String from = in.readUTF();
            String msg = in.readUTF();
            String conf = Store.getString("bcmsg");
            conf = conf.replaceAll("%msg%", msg);
            conf = conf.replaceAll("%from%", from);
            this.getServer().broadcastMessage(conf);
        }
        if (subchannel.equals("GBroadcast")) {
            String from = in.readUTF();
            String msg = in.readUTF();
            String conf = Store.getString("gbcmsg");
            conf = conf.replaceAll("%msg%", msg);
            conf = conf.replaceAll("%from%", from);
            this.getServer().broadcastMessage(conf);
        }
    }
}