JSON Import (org.json) Isn't Found, Maven Dependency

Discussion in 'Spigot Plugin Development' started by WolfLeader116, Jul 8, 2015.

  1. Hello! Sorry if this sounds a bit stupid, but I can't figure out how to make my JSON reader work. I have added the org.json dependency in the Maven pom.xml and when I build it, there are no errors. It seems to be fine in Eclipse too, but when I run the plugin, it says that it can't find the import org.json.x.
    Here is my code:
    Code (Java):

    package io.github.wolfleader116.wolfupdater;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URL;
    import java.nio.charset.Charset;

    import org.json.JSONObject;

    public class JsonReader {

        private static String readAll(Reader rd) {
            StringBuilder sb = new StringBuilder();
            int cp;
            try {
                while ((cp = rd.read()) != -1) {
                    sb.append((char) cp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return sb.toString();
        }

        public static JSONObject readJsonFromUrl(String url) {
            try {
                InputStream is = new URL(url).openStream();
                try {
                    BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                    String jsonText = readAll(rd);
                    JSONObject json = new JSONObject(jsonText);
                    return json;
                } finally {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
     
    Code (Java):

    package io.github.wolfleader116.wolfupdater;

    import java.io.File;
    import java.net.URL;

    import org.apache.commons.io.FileUtils;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerLoginEvent;
    import org.bukkit.event.player.PlayerLoginEvent.Result;
    import org.bukkit.event.player.PlayerQuitEvent;
    import org.bukkit.plugin.Plugin;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.json.JSONObject;

    public class WolfUpdater extends JavaPlugin implements Listener {
       
        public static int updatesfound = 0;
       
        public static boolean restartnoplayers = true;
        public static boolean loginfail = false;
       
        public static WolfUpdater plugin;
       
        @Override
        public void onEnable() {
            plugin = this;
            this.saveDefaultConfig();
            if (this.getConfig().getInt("Version") != 1) {
                File config = new File(this.getDataFolder(), "config.yml");
                config.delete();
                this.saveDefaultConfig();
            }
            if (this.getConfig().getBoolean("CheckOnStartup")) {
                updateCheck(true);
            }
        }
       
        @Override
        public void onDisable() {
            plugin = null;
        }
       
        @EventHandler(priority = EventPriority.HIGHEST)
        public void onPlayerLeave(PlayerQuitEvent e) {
            Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
                public void run() {
                    if (Bukkit.getServer().getOnlinePlayers().size() == 0) {
                        restart(true);
                    }
                }
            }, 20);
        }
       
        @EventHandler(priority = EventPriority.HIGHEST)
        public void onPlayerLogin(PlayerLoginEvent e) {
            if (loginfail) {
                e.disallow(Result.KICK_OTHER, "§cServer is restarting soon! Please come back in a few minutes.");
            }
        }
       
        public static void startUpdateCheckLoop() {
            Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                public void run() {
                    updateCheck(true);
                }
            }, Long.valueOf(plugin.getConfig().getInt("UpdateCheckTime")));
        }
       
        public static void update(Plugin plugin) {
            File file = new File(Bukkit.getServer().getUpdateFolder() + "/..");
            try {
                FileUtils.copyURLToFile(new URL("https://drone.io/github.com/WolfLeader116/" + plugin.getName() + "/files/target/" + plugin.getName() + ".jar"), file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
        public static void updateSelf() {
            File file = new File(Bukkit.getServer().getUpdateFolder());
            try {
                FileUtils.copyURLToFile(new URL("https://drone.io/github.com/WolfLeader116/WolfUpdater/files/target/WolfUpdater.jar"), file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
        public static void restart(boolean noplayers) {
            if (noplayers == false) {
                if (plugin.getConfig().getBoolean("RestartNoPlayers") && Bukkit.getServer().getOnlinePlayers().size() != 0) {
                    restartnoplayers = true;
                } else {
                    Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "broadcast &c&lSERVER RESTARTING IN 1 MINUTE TO PERFORM UPDATES!");
                    loginfail = true;
                    Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                        public void run() {
                            Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "broadcast &c&lSERVER RESTARTING NOW TO PERFORM UPDATES!");
                            Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                                public void run() {
                                    for (Player p : Bukkit.getOnlinePlayers()) {
                                        p.kickPlayer("§cServer is restarting! Please come back in a few minutes.");
                                    }
                                    Bukkit.getServer().shutdown();
                                }
                            }, 20);
                        }
                    }, 1200);
                }
            } else {
                Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "broadcast &c&lSERVER RESTARTING NOW TO PERFORM UPDATES!");
                Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                    public void run() {
                        for (Player p : Bukkit.getOnlinePlayers()) {
                            p.kickPlayer("§cServer is restarting! Please come back in a few minutes.");
                        }
                        Bukkit.getServer().shutdown();
                    }
                }, 20);
            }
        }
       
        public static void reload() {
            Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "broadcast &c&lSERVER RELOADING NOW TO PERFORM UPDATES!");
            Bukkit.getServer().reload();
        }
       
        public static void updateCheckComplete() {
            if (plugin.getConfig().getString("Action").equalsIgnoreCase("restart")) {
                for (Player p : Bukkit.getServer().getOnlinePlayers()) {
                    if (p.isOp() || p.hasPermission("wolfupdater.notify") && plugin.getConfig().getBoolean("UpdateNotify")) {
                        if (updatesfound == 0) {
                            p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has completed checking for plugin updates. There were no updates found.");
                        } else if (updatesfound > 0) {
                            p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has completed checking for plugin updates. " + String.valueOf(updatesfound) + " updates were found and downloaded. Server will now restart.");
                        }
                    }
                }
                if (updatesfound > 0) {
                    restart(false);
                }
            } else if (plugin.getConfig().getString("Action").equalsIgnoreCase("reload")) {
                for (Player p : Bukkit.getServer().getOnlinePlayers()) {
                    if (p.isOp() || p.hasPermission("wolfupdater.notify") && plugin.getConfig().getBoolean("UpdateNotify")) {
                        if (updatesfound == 0) {
                            p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has completed checking for plugin updates. There were no updates found.");
                        } else if (updatesfound > 0) {
                            p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has completed checking for plugin updates. " + String.valueOf(updatesfound) + " updates were found and downloaded. Server will now reload.");
                        }
                    }
                }
                if (updatesfound > 0) {
                    reload();
                }
            } else if (plugin.getConfig().getString("Action").equalsIgnoreCase("none")) {
                for (Player p : Bukkit.getServer().getOnlinePlayers()) {
                    if (p.isOp() || p.hasPermission("wolfupdater.notify") && plugin.getConfig().getBoolean("UpdateNotify")) {
                        if (updatesfound == 0) {
                            p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has completed checking for plugin updates. There were no updates found.");
                        } else if (updatesfound > 0) {
                            p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has completed checking for plugin updates. " + String.valueOf(updatesfound) + " updates were found and downloaded.");
                        }
                    }
                }
            }
        }
       
        public static void updateCheck(boolean automatic) {
            for (Player p : Bukkit.getServer().getOnlinePlayers()) {
                if (p.isOp() || p.hasPermission("wolfupdater.notify") && plugin.getConfig().getBoolean("UpdateNotify")) {
                    p.sendMessage(ChatColor.BLUE + "WolfUpdater> " + ChatColor.GREEN + "Server has started checking for updates.");
                }
            }
            Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins();
            for(int i = 0; i < plugins.length; i++) {
                if (plugins[i].getClass().getCanonicalName().startsWith("io.github.wolfleader116") && plugins[i].getName() != "WolfUpdater") {
                    String version = plugins[i].getDescription().getVersion();
                    JSONObject json = JsonReader.readJsonFromUrl("https://api.github.com/repos/WolfLeader116/"+ plugins[i].getDescription().getName() + "/releases");
                    String ver;
                    try {
                        ver = json.getString("tag_name");
                    } catch (Exception e) {
                        ver = "0";
                        e.printStackTrace();
                    }
                    String[] versions = version.split(".");
                    String[] vers = ver.split(".");
                    if (vers[0] != null && versions[0] != null && Integer.valueOf(vers[0]) > Integer.valueOf(versions[0])) {
                        update(plugins[i]);
                    } else if (vers[0] != null && versions[0] == null) {
                        update(plugins[i]);
                    } else {
                        if (vers[1] != null && versions[1] != null && Integer.valueOf(vers[1]) > Integer.valueOf(versions[1])) {
                            update(plugins[i]);
                        } else if (vers[1] != null && versions[1] == null) {
                            update(plugins[i]);
                        } else {
                            if (vers[2] != null && versions[2] != null && Integer.valueOf(vers[2]) > Integer.valueOf(versions[2])) {
                                update(plugins[i]);
                            } else if (vers[2] != null && versions[1] == null) {
                                update(plugins[i]);
                            } else {
                                if (vers[3] != null && versions[3] != null && Integer.valueOf(vers[3]) > Integer.valueOf(versions[3])) {
                                    update(plugins[i]);
                                } else if (vers[3] != null && versions[3] == null) {
                                    update(plugins[i]);
                                } else {
                                    if (vers[4] != null && versions[4] != null && Integer.valueOf(vers[4]) > Integer.valueOf(versions[4])) {
                                        update(plugins[i]);
                                    } else if (vers[4] != null && versions[4] == null) {
                                        update(plugins[i]);
                                    } else {
                                        if (vers[5] != null && versions[5] != null && Integer.valueOf(vers[5]) > Integer.valueOf(versions[5])) {
                                            update(plugins[i]);
                                        } else if (vers[5] != null && versions[5] == null) {
                                            update(plugins[i]);
                                        } else {
                                            if (vers[6] != null && versions[6] != null && Integer.valueOf(vers[6]) > Integer.valueOf(versions[6])) {
                                                update(plugins[i]);
                                            } else if (vers[6] != null && versions[6] == null) {
                                                update(plugins[i]);
                                            } else {
                                                update(plugins[i]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            String version = plugin.getDescription().getVersion();
            JSONObject json = JsonReader.readJsonFromUrl("https://api.github.com/repos/WolfLeader116/WolfUpdater/releases");
            String ver;
            try {
                ver = json.getString("tag_name");
            } catch (Exception e) {
                ver = "0";
                e.printStackTrace();
            }
            String[] versions = version.split(".");
            String[] vers = ver.split(".");
            if (vers[0] != null && versions[0] != null && Integer.valueOf(vers[0]) > Integer.valueOf(versions[0])) {
                updateSelf();
            } else if (vers[0] != null && versions[0] == null) {
                updateSelf();
            } else {
                if (vers[1] != null && versions[1] != null && Integer.valueOf(vers[1]) > Integer.valueOf(versions[1])) {
                    updateSelf();
                } else if (vers[1] != null && versions[1] == null) {
                    updateSelf();
                } else {
                    if (vers[2] != null && versions[2] != null && Integer.valueOf(vers[2]) > Integer.valueOf(versions[2])) {
                        updateSelf();
                    } else if (vers[2] != null && versions[1] == null) {
                        updateSelf();
                    } else {
                        if (vers[3] != null && versions[3] != null && Integer.valueOf(vers[3]) > Integer.valueOf(versions[3])) {
                            updateSelf();
                        } else if (vers[3] != null && versions[3] == null) {
                            updateSelf();
                        } else {
                            if (vers[4] != null && versions[4] != null && Integer.valueOf(vers[4]) > Integer.valueOf(versions[4])) {
                                updateSelf();
                            } else if (vers[4] != null && versions[4] == null) {
                                updateSelf();
                            } else {
                                if (vers[5] != null && versions[5] != null && Integer.valueOf(vers[5]) > Integer.valueOf(versions[5])) {
                                    updateSelf();
                                } else if (vers[5] != null && versions[5] == null) {
                                    updateSelf();
                                } else {
                                    if (vers[6] != null && versions[6] != null && Integer.valueOf(vers[6]) > Integer.valueOf(versions[6])) {
                                        updateSelf();
                                    } else if (vers[6] != null && versions[6] == null) {
                                        updateSelf();
                                    } else {
                                        updateSelf();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (automatic && plugin.getConfig().getBoolean("AutoCheck")) {
                startUpdateCheckLoop();
            }
            updateCheckComplete();
        }
       
    }
     

    If there is any other code you would like to see, it is available here.

    Also, if there are any mistakes or suggestions for other things (such as the version checker, I couldn't think of a better way, especially because the version might not contain a minor or build number, or for some odd reason, more numbers than just that...) I would be happy to hear them and make the code better. Also, I am sorry that I didn't put the code from the main class into multiple classes to make it more organized.
    Thanks and have a nice day!
     
  2. Try use code which I pull on github. :)
     
  3. Uhh Sorry, but how exactly would removing 2 important dependencies fix the problem? The commons-io dependency is for FileUtils and the json dependency is for the org.json.x imports. Without those 2 dependencies, it won't work. I was thinking it may be something to do with plugin.yml or maybe the fact that Bukkit actually doesn't have the code available, but how can I get Bukkit to HAVE that code available? The pom.xml is only for Maven to test the build, not give Bukkit some code that my plugin can hook into and use.
     
    • Informative Informative x 1
  4. Thanks! Adding
    Code (Text):

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.4</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <artifactSet>
                                    <excludes>
                                        <exclude>org.spigotmc</exclude>
                                    </excludes>
                                </artifactSet>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
     
    worked, but now I can't figure out how to fix this problem:
    Code (Text):

    java.lang.UnsupportedClassVersionError: org/json/JSONObject : Unsupported major.minor version 52.0
        at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.7.0_51]
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800) ~[?:1.7.0_51]
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[?:1.7.0_51]
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) ~[?:1.7.0_51]
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71) ~[?:1.7.0_51]
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[?:1.7.0_51]
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[?:1.7.0_51]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:1.7.0_51]
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[?:1.7.0_51]
        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:101) ~[spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.plugin.java.JavaPluginLoader.getClassByName(JavaPluginLoader.java:195) ~[spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:97) ~[spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:86) ~[spigot.jar:git-Spigot-044d928-e8c6403]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425) ~[?:1.7.0_51]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ~[?:1.7.0_51]
        at io.github.wolfleader116.wolfupdater.JsonReader.readJsonFromUrl(JsonReader.java:33) ~[?:?]
        at io.github.wolfleader116.wolfupdater.WolfUpdater.updateCheck(WolfUpdater.java:181) ~[?:?]
        at io.github.wolfleader116.wolfupdater.WolfUpdater.onEnable(WolfUpdater.java:39) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:356) [spigot.jar:git-Spigot-044d928-e8c6403]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:316) [spigot.jar:git-Spigot-044d928-e8c6403]
        at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:418) [spigot.jar:git-Spigot-044d928-e8c6403]
        at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:382) [spigot.jar:git-Spigot-044d928-e8c6403]
        at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:337) [spigot.jar:git-Spigot-044d928-e8c6403]
        at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:256) [spigot.jar:git-Spigot-044d928-e8c6403]
        at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:528) [spigot.jar:git-Spigot-044d928-e8c6403]
        at java.lang.Thread.run(Thread.java:744) [?:1.7.0_51]

    Sorry, I don't know much about Maven yet. Can you help figure this out too? Thanks.
     
  5. It says you compiled with java 8, but are running it on something lower.
     
    • Like Like x 1
  6. That's weird. The build server says it's compiling on Java 1.7.0_25 and the default Eclipse JRE is for Java 7. I asked the host what version of Java they are running and it was also Java 7. Every other plugin I have made works too. I just realized that the compiler in Eclipse was set to 1.8, but I don't think that should matter because I am compiling it on a build server? I have set it to 1.7 now and will test it. Never mind that... I think the problem is that org.json is for Java 8, not 7... I will try an earlier version of json.
     
  7. Yup that was the problem. Thanks! :) I was having issues with an ArrayIndexOutOfBoundsException, but it is fixed now.
     
    #8 WolfLeader116, Jul 9, 2015
    Last edited: Jul 9, 2015
  8. Um do you have any idea what this happens?
    Code (Text):
    Current version of plugin WolfAPI is 2.7.2 and found online version is 2.7.3
    ?? According to my code here:

    Code (Java):

    Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins();
            for(int i = 0; i < plugins.length; i++) {
                if (plugins[i].getClass().getCanonicalName().startsWith("io.github.wolfleader116") && plugins[i].getDescription().getName() != "WolfUpdater") {
                    String version = plugins[i].getDescription().getVersion();
                    JSONObject json = JsonReader.readJsonFromUrl("https://api.github.com/repos/WolfLeader116/"+ plugins[i].getDescription().getName() + "/releases/latest");
                    String ver;
                    try {
                        ver = json.getString("tag_name");
                    } catch (Exception e) {
                        ver = "0";
                        e.printStackTrace();
                    }
                    String[] versions = version.split(".");
                    String[] vers = ver.split(".");
                    log.info("Current version of plugin " + plugins[i].getDescription().getName() + " is " + version + " and found online version is " + ver);
                    try {
                        for (int a = 0; a < vers.length; a++) {
                            if (Integer.valueOf(vers[a]) > Integer.valueOf(versions[a])) {
                                update(plugins[i]);
                                break;
                            }
                        }
                    } catch (ArrayIndexOutOfBoundsException e) {
                        update(plugins[i]);
                    }
                }
            }
     

    it should iterate through each version number and if the online version number is greater than the local one, it cancels the for loop and it tells the plugin to update...