is.brendan.WarpMarkers.WarpMarkers.java Source code

Java tutorial

Introduction

Here is the source code for is.brendan.WarpMarkers.WarpMarkers.java

Source

/*
MapMarkers Minecraft Bukkit plugin for showing Essentials warps 
and warp events on maps generated by Minecraft Overviewer.
Copyright (C) 2011 Brendan Johan Lee 
Email: brendan (at) vanntett.net
    
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
MA  02110-1301, USA.
*/

package is.brendan.WarpMarkers;

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.util.logging.*;
import java.util.Iterator;

import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.config.Configuration;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.command.Command;
import org.bukkit.Location;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.Warps;
import com.earth2me.essentials.User;

/**
 * WarpMarkers for Bukkit with Essentials
 *
 * @author Brendan Johan Lee - deadcyclo@vanntett.net
 */

public class WarpMarkers extends JavaPlugin {
    private final WarpMarkersSignPlayerListener signPlayerListener = new WarpMarkersSignPlayerListener(this);
    private final WarpMarkersPluginEnabledListener pluginEnabledListener = new WarpMarkersPluginEnabledListener(
            this);
    private final WarpMarkersPluginDisabledListener pluginDisabledListener = new WarpMarkersPluginDisabledListener(
            this);
    private Boolean hasUpdated = true;
    private Boolean previousUpdateWasEmpty = false;
    private PluginDescriptionFile pdfFile;
    protected Essentials essentialPlugin;
    private WarpMarkersWarpInfo warpInfo;
    private int updateLife = 15000;
    private int timer;
    private String updateFile;
    private boolean essentialsRunning = false;
    private boolean hasEssentialsRun = false;
    private String outputFile;
    private int interval;
    private PluginManager pm;

    private void fail(String message) {
        log(Level.SEVERE, message);
        getServer().getPluginManager().disablePlugin(this);
    }

    private boolean trapCommand(String command) {
        PluginCommand pc = getServer().getPluginCommand(command);
        if (pc != null) {
            if (pc.getPlugin().getDescription().getMain().contains("com.earth2me.essentials")) {
                essentialPlugin = (Essentials) pc.getPlugin();
                pc.setExecutor(new WarpMarkersCommandTrap(this, pc.getExecutor(), pc, this));
                return true;
            }
        }
        log(Level.INFO, "The Essentials plug-in not running. Will listen for it starting later.");
        return false;
    }

    protected void enableEssentialsListening() {
        if (!hasEssentialsRun) {
            if (!trapCommand("warp") || !trapCommand("delwarp") || !trapCommand("setwarp"))
                return;
        }
        hasEssentialsRun = true;
        warpInfo = new WarpMarkersWarpInfo(essentialPlugin.getWarps(), getServer(), getDataFolder(), this);
        essentialsRunning = true;
        timer = getServer().getScheduler().scheduleSyncRepeatingTask(this,
                new WarpMarkersTimerTask(this, outputFile, updateFile), interval, interval);
    }

    protected void disableEssentialsListening() {
        essentialsRunning = false;
        getServer().getScheduler().cancelTask(timer);
        warpInfo = null;
    }

    public boolean isEssentialsRunning() {
        return essentialsRunning;
    }

    public void onEnable() {
        pdfFile = this.getDescription();

        File configFile = new File(getDataFolder(), "config.yml");
        getDataFolder().mkdirs();
        Configuration config = new Configuration(configFile);
        if (!configFile.exists()) {
            config.setProperty("saveInterval", 3000);
            config.setProperty("updateLife", 15000);
            config.setProperty("outputFile", "world/warpmarkers.json");
            config.setProperty("updateFile", "world/warpupdates.json");
            config.save();
        } else {
            config.load();
        }

        interval = config.getInt("saveInterval", 3000);
        updateLife = config.getInt("updateLife", 15000);
        outputFile = config.getString("outputFile", "world/warpmarkers.json");
        updateFile = config.getString("updateFile", "world/warpupdates.json");

        //Convert from 1000 ms to 20 ticks-per-second
        interval /= 50;

        try {
            File file = new File(outputFile);
            file.createNewFile();
        } catch (IOException e) {
            fail("Unable to create " + outputFile + ": " + e.getMessage());
        }
        try {
            File file = new File(updateFile);
            file.createNewFile();
        } catch (IOException e) {
            fail("Unable to create " + updateFile + ": " + e.getMessage());
        }

        pm = getServer().getPluginManager();

        enableEssentialsListening();

        pm.registerEvent(Event.Type.PLUGIN_ENABLE, pluginEnabledListener, Priority.Normal, this);
        pm.registerEvent(Event.Type.PLUGIN_DISABLE, pluginDisabledListener, Priority.Normal, this);
        pm.registerEvent(Event.Type.PLAYER_INTERACT, signPlayerListener, Priority.Normal, this);

        log(Level.INFO, "Loaded " + pdfFile.getName() + " build " + pdfFile.getVersion()
                + " by Brendan Johan Lee <deadcyclo@vanntett.net>", "");
    }

    public void onDisable() {
        getServer().getScheduler().cancelTask(timer);
        try {
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(updateFile)));
            writer.print(new JSONArray());
            writer.close();
        } catch (java.io.IOException e) {
            log(Level.SEVERE, "Unable to write to " + updateFile + ": " + e.getMessage(), e);
            e.printStackTrace();
        }
        log(Level.INFO, "Unloading");
    }

    protected void handleSignWarp(String player, String warpname) {
        if (!hasWarpPermissions(getServer().getPlayer(player), null, warpname))
            return;
        hasUpdated = warpInfo.touch("accessed", warpname, player);
        if (hasUpdated)
            log(Level.INFO, warpname + " accessed by sign");
    }

    protected void handleCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        if (matchCommand("warp", commandLabel)) {
            hasUpdated = cmdWarp(sender, args);
            if (hasUpdated)
                log(Level.INFO, args[0] + " accessed by command");
        } else if (matchCommand("setwarp", commandLabel)) {
            hasUpdated = cmdSetWarp(sender, args);
            if (hasUpdated)
                log(Level.INFO, args[0] + " created or moved");
        } else if (matchCommand("delwarp", commandLabel)) {
            hasUpdated = cmdDelWarp(sender, args);
            if (hasUpdated)
                log(Level.INFO, args[0] + " deleted (if it existed)");
        }
    }

    private boolean matchCommand(String name, String commandLabel) {
        if (commandLabel.equalsIgnoreCase(name))
            return !essentialPlugin.getSettings().isCommandDisabled(name);
        for (Iterator<String> aliases = getServer().getPluginCommand(name).getAliases().iterator(); aliases
                .hasNext();) {
            if (commandLabel.equalsIgnoreCase(aliases.next()))
                return !essentialPlugin.getSettings().isCommandDisabled(name);
        }
        return false;
    }

    private boolean cmdDelWarp(CommandSender sender, String[] args) {
        /* Since allready deleted we cannot check if exists or not */
        if (args.length > 0) {
            try {
                if (!hasPermissions((Player) sender, "essentials.delwarp"))
                    return false;
                warpInfo.del(args[0], ((Player) sender).getName());
            } catch (java.lang.ClassCastException e) {
                /* Still need to update */
            }
            return true;
        }
        return false;
    }

    private boolean cmdSetWarp(CommandSender sender, String[] args) {
        if (args.length > 0) {
            try {
                if (!hasPermissions((Player) sender, "essentials.setwarp"))
                    return false;
                return warpInfo.touch("created", args[0], ((Player) sender).getName());
            } catch (java.lang.ClassCastException e) {
                return false;
            }
        }
        return false;
    }

    private boolean cmdWarp(CommandSender sender, String[] args) {
        if (args.length > 0) {
            Player warpee = null;
            Player warper = null;
            try {
                warpee = ((Player) sender);
            } catch (java.lang.ClassCastException e) {
                return false; /* System cannot warp as of now */
            }
            if (args.length > 1) { /* user warped a different user */
                warper = warpee;
                warpee = getServer().getPlayer(args[1]);
                if (warpee == null)
                    return false;
                if (!warpee.isOnline())
                    return false;
            }
            if (warpee != null) {
                if (!hasWarpPermissions(warpee, warper, args[0]))
                    return false;
                return warpInfo.touch("accessed", args[0], warpee.getName());
            }
        }
        return false;
    }

    protected boolean hasPermissions(Player player, String permission) {
        User user = essentialPlugin.getUser(player);
        return user.isAuthorized(permission);
    }

    protected boolean hasWarpPermissions(Player warpee, Player warper, String warp) {
        if (warper != null) {
            if (!hasPermissions(warper, "essentials.warp.otherplayers"))
                return false;
        }
        if (essentialPlugin.getSettings().getPerWarpPermission()) {
            if (!hasPermissions(warpee, "essentials.warp." + warp))
                return false;
        }
        if (!hasPermissions(warpee, "essentials.warp"))
            return false;
        return true;
    }

    protected JSONArray getJSON() {
        if (hasUpdated == false)
            return null;
        hasUpdated = false;
        return warpInfo.load();
    }

    protected JSONArray getUpdatesJSON() {
        if (warpInfo == null)
            return null; /* Essentials has been disabled */
        JSONArray result = warpInfo.getUpdates(updateLife);
        if (result.isEmpty()) {
            if (previousUpdateWasEmpty)
                return null;
            previousUpdateWasEmpty = true;
        } else {
            previousUpdateWasEmpty = false;
        }
        return result;
    }

    protected void log(Level level, String msg) {
        log(level, "[" + pdfFile.getName() + "]", msg);
    }

    protected void log(Level level, String msg, Throwable e) {
        log(level, "[" + pdfFile.getName() + "]", msg, e);
    }

    private void log(Level level, String prepend, String msg) {
        Logger.getLogger(this.getDescription().getName()).log(level, prepend + " " + msg);
    }

    private void log(Level level, String prepend, String msg, Throwable e) {
        Logger.getLogger(this.getDescription().getName()).log(level, prepend + " " + msg);
    }
}