1. Welcome to LilyPad. Download the project, explore the forums, and create your own LilyPad network.


    If you use the software and enjoy it or have a question, or would like to contribute to the future of the software directly or through resources, please sign up and join our little community.

Would this send a request to all servers?

Discussion in 'Development' started by ZapChance, Mar 3, 2014.

  1. ZapChance

    ZapChance New Member

    Request Method:
    Code (java):
    public void request(String message, String channelname) {
            Connect c = getLilyPad();
            MessageRequest request = null;
            try {
                request = new MessageRequest(Collections.EMPTY_LIST, channelname, message); //servername, channelname (short), message
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            FutureResult<MessageResult> futureResult = null;
            try {
                futureResult = c.request(request);
            } catch (RequestException e) {
                e.printStackTrace();
            }
        }
    Listener Class:
    Code (java):
    public class MessageListener {

        private ReportRTS plugin;

        public MessageListener(ReportRTS plugin) {
            this.plugin = plugin;
        }

        @EventListener
        public void onMessage(MessageEvent messageEvent) {
            String channel = messageEvent.getChannel();
            if (channel.equals("RTSJoin")) {
                try {
                    String messageAsString = messageEvent.getMessageAsString();
                    plugin.moderatorMap.add(messageAsString);
                } catch (UnsupportedEncodingException exception) {

                }
            } else if (channel.equals("RTSJoin")) {
                try {
                    String messageAsString = messageEvent.getMessageAsString();
                    plugin.moderatorMap.remove(messageAsString);
                } catch (UnsupportedEncodingException exception) {

                }
            }
        }
    }
    I'm fairly new to LilyPad and its API, and any help is much appreciated! :)
    Last edited by a moderator: Mar 3, 2014
  2. Coelho

    Coelho Software Engineer Staff Member Administrator Maintainer

    That would send a message to all servers, correct :)
  3. ZapChance

    ZapChance New Member

    Code (text):
    package com.zapchance.reportrts;

    @SuppressWarnings({ "unused", "deprecation" })
    public class ReportRTS extends JavaPlugin implements Listener {

        private static ReportRTS plugin;
        private final Logger log = getLogger();
        private static MessageHandler messageHandler = new MessageHandler();
        private VersionChecker versionChecker = new VersionChecker();
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Map<Integer, HelpRequest> requestMap = new LinkedHashMap();
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Map<Integer, String> notificationMap = new HashMap();
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public ArrayList<String> moderatorMap = new ArrayList();
        public boolean notifyStaffOnNewRequest;
        public boolean hideNotification;
        public boolean hideWhenOffline;
        public boolean debugMode;
        public boolean outdated;
        public boolean vanishSupport;
        public int maxRequests;
        public int requestDelay;
        public int requestMinimumWords;
        public int requestsPerPage;
        public int storagePort;
        public long requestNagging;
        public String storageType;
        public String storageHostname;
        public String storageDatabase;
        public String storageUsername;
        public String storagePassword;
        public String versionString;
        public static Permission permission = null;
        private Connect connect;

        public void onDisable() {
            DatabaseManager.getDatabase().disconnect();
            messageHandler.saveMessageConfig();
            Connect connect = plugin.getServer().getServicesManager()
                    .getRegistration(Connect.class).getProvider();
            connect.unregisterEvents(this);
        }

        public void onEnable() {
            plugin = this;
            reloadSettings();
            PluginManager pm = getServer().getPluginManager();
            this.connect = ((Connect) Bukkit.getServer().getServicesManager()
                    .getRegistration(Connect.class).getProvider());
            this.connect.registerEvents(this);
            pm.registerEvents(new RTSListener(plugin), plugin);
            if (!DatabaseManager.load()) {
                this.log.severe("Encountered an error while attempting to connect to the database.  Disabling...");
                pm.disablePlugin(this);
            }
            reloadPlugin();
            this.outdated = (!this.versionChecker.upToDate());
            getCommand("modreq").setExecutor(new ModreqCommand(plugin));
            getCommand("check").setExecutor(new CheckCommand(plugin));
            getCommand("complete").setExecutor(new CompleteCommand(plugin));
            getCommand("reopen").setExecutor(new ReopenCommand(plugin));
            getCommand("tp-id").setExecutor(new TeleportCommand(plugin));
            getCommand("reportrts").setExecutor(new ReportRTSCommand(plugin));
            getCommand("hold").setExecutor(new HoldCommand(plugin));
            getCommand("claim").setExecutor(new ClaimCommand(plugin));
            getCommand("unclaim").setExecutor(new UnclaimCommand(plugin));
            getCommand("modlist").setExecutor(new ModlistCommand());
            getCommand("mod-broadcast")
                    .setExecutor(new ModBroadcastCommand(plugin));
            getCommand("assign").setExecutor(new AssignCommand(plugin));
            if (getServer().getPluginManager().getPlugin("Vault") != null) {
                setupPermissions();
            }
            try {
                MetricsLite metrics = new MetricsLite(this);
                metrics.start();
            } catch (IOException e) {
                this.log.info("Unable to submit stats!");
            }
            if (this.requestNagging > 0L) {
                getServer().getScheduler().scheduleSyncRepeatingTask(plugin,
                        new Runnable() {
                            public void run() {
                                int openRequests = ReportRTS.this.requestMap.size();
                                if (openRequests > 0) {
                                    RTSFunctions.messageMods(Message.parse(
                                            "generalOpenRequests",
                                            new Object[] { Integer
                                                    .valueOf(openRequests) }),
                                            false);
                                }
                            }
                        }, 120L, this.requestNagging * 60L * 20L);
            }
            getServer().getScheduler().scheduleSyncRepeatingTask(this,
                    new Runnable() {
                        public void run() {
                            ReportRTS.this.requestMap.clear();
                            ReportRTS.this.notificationMap.clear();
                            ReportRTS.this.moderatorMap.clear();
                            DatabaseManager.getDatabase().populateRequestMap();
                            RTSFunctions.populateHeldRequestsWithData();
                            RTSFunctions.populateNotificationMapWithData();
                            RTSFunctions.populateModeratorMapWithData();
                        }
                    }, 100L, 100L);
        }

        public void reloadPlugin() {
            this.requestMap.clear();
            this.notificationMap.clear();
            this.moderatorMap.clear();
            reloadSettings();
            DatabaseManager.getDatabase().populateRequestMap();
            RTSFunctions.populateHeldRequestsWithData();
            RTSFunctions.populateNotificationMapWithData();
            RTSFunctions.populateModeratorMapWithData();
        }

        public void reloadSettings() {
            reloadConfig();
            getConfig().options().copyDefaults(true);
            saveConfig();
            messageHandler.reloadMessageConfig();
            messageHandler.saveMessageConfig();
            messageHandler.reloadMessageMap();
            this.notifyStaffOnNewRequest = getConfig().getBoolean("notifyStaff");
            this.hideNotification = getConfig().getBoolean("hideMessageIfEmpty");
            this.hideWhenOffline = getConfig().getBoolean("request.hideOffline");
            this.maxRequests = getConfig().getInt("request.max");
            this.requestDelay = getConfig().getInt("request.delay");
            this.requestMinimumWords = getConfig().getInt("request.minimumWords");
            this.requestsPerPage = getConfig().getInt("request.perPage");
            this.requestNagging = getConfig().getLong("request.nag");
            this.storageType = getConfig().getString("storage.type", "sqlite");
            this.storagePort = getConfig().getInt("storage.port");
            this.storageHostname = getConfig().getString("storage.hostname");
            this.storageDatabase = getConfig().getString("storage.database");
            this.storageUsername = getConfig().getString("storage.username");
            this.storagePassword = getConfig().getString("storage.password");
            this.debugMode = getConfig().getBoolean("debug");
            this.vanishSupport = getConfig().getBoolean("VanishSupport", false);
        }

        public static ReportRTS getPlugin() {
            return plugin;
        }

        public static MessageHandler getMessageHandler() {
            return messageHandler;
        }

        private Boolean setupPermissions() {
            RegisteredServiceProvider<Permission> permissionProvider = getServer()
                    .getServicesManager().getRegistration(Permission.class);
            if (permissionProvider != null) {
                permission = (Permission) permissionProvider.getProvider();
            }
            return Boolean.valueOf(permission != null);
        }

        public Connect getLilyPad() {
            return (Connect) getServer().getServicesManager()
                    .getRegistration(Connect.class).getProvider();
        }

        @SuppressWarnings("unchecked")
        public void request(String message, String channelname) {
            Connect c = getLilyPad();
            MessageRequest request = null;
            try {
                request = new MessageRequest(Collections.EMPTY_LIST, channelname,
                        message); // servername, channelname (short), message
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            FutureResult<MessageResult> futureResult = null;
            try {
                futureResult = c.request(request);
            } catch (RequestException e) {
                e.printStackTrace();
            }
        }
       
        @EventListener
        public void onLilyPadMessageEvent(MessageEvent event) {
            String channel = event.getChannel();
            if (channel.equals("RTSJoin")) {
                try {
                    String messageAsString = event.getMessageAsString();
                    plugin.moderatorMap.add(messageAsString);
                } catch (UnsupportedEncodingException exception) {

                }
            } else if (channel.equals("RTSJoin")) {
                try {
                    String messageAsString = event.getMessageAsString();
                    plugin.moderatorMap.remove(messageAsString);
                } catch (UnsupportedEncodingException exception) {

                }
            } else if (channel.equals("RTSPlayerSync")) {
                try {
                    String messageAsString = event.getMessageAsString();
                    RTSFunctions.messageMods(ReportRTS.getMessageHandler().getMessageConfig().getString("modreqFiledMod"), true);
                } catch (UnsupportedEncodingException exception) {

                }
            }
        }
    }
     
  4. ZapChance

    ZapChance New Member

    Code (text):
    package com.zapchance.reportrts;

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Map;

    import org.bukkit.block.Block;
    import org.bukkit.block.Sign;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.SignChangeEvent;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerQuitEvent;

    import com.btilm305.meep.meepteleport.CrossServerLocation;
    import com.zapchance.reportrts.data.HelpRequest;
    import com.zapchance.reportrts.persistance.DatabaseManager;
    import com.zapchance.reportrts.util.Message;

    public class RTSListener implements Listener {

        private final ReportRTS plugin;

        public RTSListener(ReportRTS plugin) {
            this.plugin = plugin;
        }

        @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
        public void onPlayerJoin(PlayerJoinEvent event) {
            if (this.plugin.notificationMap.size() > 0) {
                @SuppressWarnings({ "unchecked", "rawtypes" })
                ArrayList<Integer> keys = new ArrayList();
                for (Map.Entry<Integer, String> entry : this.plugin.notificationMap
                        .entrySet()) {
                    if (((String) entry.getValue()).equals(event.getPlayer()
                            .getName())) {
                        ResultSet rs = DatabaseManager.getDatabase().getTicketById(
                                ((Integer) entry.getKey()).intValue());
                        try {
                            if (this.plugin.storageType.equalsIgnoreCase("mysql")) {
                                rs.first();
                            }
                            event.getPlayer().sendMessage(
                                    Message.parse("completedUserOffline",
                                            new Object[0]));
                            String comment = rs.getString("mod_comment");
                            if (comment == null) {
                                comment = "";
                            }
                            event.getPlayer().sendMessage(
                                    Message.parse("completedText", new Object[] {
                                            rs.getString("text"), comment }));
                            rs.close();
                            if (!DatabaseManager.getDatabase()
                                    .setNotificationStatus(
                                            ((Integer) entry.getKey()).intValue(),
                                            1)) {
                                this.plugin.getLogger().warning(
                                        "Unable to set notification status to 1.");
                            }
                            keys.add(entry.getKey());
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
                int key;
                for (@SuppressWarnings("rawtypes")
                Iterator i$ = keys.iterator(); i$.hasNext(); this.plugin.notificationMap
                        .remove(Integer.valueOf(key))) {
                    key = ((Integer) i$.next()).intValue();
                }
            }
            if (!RTSPermissions.isModerator(event.getPlayer())) {
                return;
            }
            if (!this.plugin.moderatorMap.contains(event.getPlayer().getName())) {
                this.plugin.moderatorMap.add(event.getPlayer().getName());
                this.plugin.request(event.getPlayer().getName(), "RTSJoin");
            }
            int openRequests = this.plugin.requestMap.size();
            if ((openRequests < 1) && (!this.plugin.hideNotification)) {
                event.getPlayer().sendMessage(
                        Message.parse("generalNoRequests", new Object[0]));
            }
            if (openRequests > 0) {
                event.getPlayer().sendMessage(
                        Message.parse("generalOpenRequests",
                                new Object[] { Integer.valueOf(openRequests) }));
            }
            if ((event.getPlayer().isOp()) && (this.plugin.outdated)) {
                event.getPlayer().sendMessage(
                        Message.parse("outdatedPlugin",
                                new Object[] { this.plugin.versionString }));
            }
        }

        @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
        public void onSignChange(SignChangeEvent event) {
            Block block = event.getBlock();
            if (!(block.getState() instanceof Sign)) {
                return;
            }
            if (!event.getLine(0).equalsIgnoreCase("[help]")) {
                return;
            }
            if (!RTSPermissions.canFileRequest(event.getPlayer())) {
                block.breakNaturally();
                return;
            }
            String[] text = new String[3];
            System.arraycopy(event.getLines(), 1, text, 0, 3);
            String message = RTSFunctions.cleanUpSign(text);
            if (message.length() == 0) {
                event.getPlayer().sendMessage(
                        Message.parse("generalInternalError",
                                new Object[] { "Help signs can't be empty." }));
                block.breakNaturally();
                return;
            }
            if ((RTSFunctions.getOpenRequestsByUser(event.getPlayer()) >= this.plugin.maxRequests)
                    && (ReportRTS.permission != null ? !ReportRTS.permission
                            .has(event.getPlayer(),
                                    "reportrts.command.modreq.unlimited") : !event
                            .getPlayer().hasPermission(
                                    "reportrts.command.modreq.unlimited"))) {
                event.getPlayer().sendMessage(
                        Message.parse("modreqTooManyOpen", new Object[0]));
                block.breakNaturally();
                return;
            }
            int userId = DatabaseManager.getDatabase().getUserId(
                    event.getPlayer().getName(), true);
            if (DatabaseManager.getDatabase().fileRequest(
                    event.getPlayer().getName(),
                    new CrossServerLocation(event.getPlayer().getLocation()),
                    message, userId)) {
                int ticketId = DatabaseManager.getDatabase()
                        .getLatestTicketIdByUser(userId);
                this.plugin.requestMap.put(Integer.valueOf(ticketId),
                        new HelpRequest(event.getPlayer().getName(), ticketId,
                                System.currentTimeMillis() / 1000L, message, 0,
                                event.getPlayer().getLocation().getBlockX(), event
                                        .getPlayer().getLocation().getBlockY(),
                                event.getPlayer().getLocation().getBlockZ(), event
                                        .getPlayer().getLocation().getYaw(), event
                                        .getPlayer().getLocation().getPitch(),
                                event.getPlayer().getWorld().getName(),
                                CrossServerLocation.getCurrentServer()));
                event.getPlayer().sendMessage(
                        Message.parse("modreqFiledUser", new Object[0]));
                RTSFunctions.messageMods(
                        Message.parse(
                                "modreqFiledMod",
                                new Object[] { event.getPlayer().getName(),
                                        Integer.valueOf(ticketId) }), true);
            }
        }

        @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
        public void onPlayerQuit(PlayerQuitEvent event) {
            if (this.plugin.moderatorMap.contains(event.getPlayer().getName())) {
                this.plugin.moderatorMap.remove(event.getPlayer().getName());
                this.plugin.request(event.getPlayer().getName(), "RTSQuit");
            }
        }
    }
     
  5. ZapChance

    ZapChance New Member

    This isn't sending to the servers, either that or I f'd up (This one!). I need it to request the string of the player name to either add or remove the player from the modlist. :)

Share This Page