Search in sources :

Example 11 with PluginDescriptionFile

use of org.bukkit.plugin.PluginDescriptionFile in project Prism-Bukkit by prism.

the class Metrics method postPlugin.

/**
     * Generic method that posts a plugin to the metrics website
     */
private void postPlugin(final boolean isPing) throws IOException {
    // Server software specific section
    final PluginDescriptionFile description = plugin.getDescription();
    final String pluginName = description.getName();
    // TRUE
    final boolean onlineMode = Bukkit.getServer().getOnlineMode();
    // if
    // online
    // mode
    // is
    // enabled
    final String pluginVersion = description.getVersion();
    final String serverVersion = Bukkit.getVersion();
    final int playersOnline = Bukkit.getServer().getOnlinePlayers().size();
    // END server software specific section -- all code below does not use
    // any code outside of this class / Java
    // Construct the post data
    final StringBuilder data = new StringBuilder();
    // The plugin's description file containg all of the plugin data such as
    // name, version, author, etc
    data.append(encode("guid")).append('=').append(encode(guid));
    encodeDataPair(data, "version", pluginVersion);
    encodeDataPair(data, "server", serverVersion);
    encodeDataPair(data, "players", Integer.toString(playersOnline));
    encodeDataPair(data, "revision", String.valueOf(REVISION));
    // New data as of R6
    final String osname = System.getProperty("os.name");
    String osarch = System.getProperty("os.arch");
    final String osversion = System.getProperty("os.version");
    final String java_version = System.getProperty("java.version");
    final int coreCount = Runtime.getRuntime().availableProcessors();
    // normalize os arch .. amd64 -> x86_64
    if (osarch.equals("amd64")) {
        osarch = "x86_64";
    }
    encodeDataPair(data, "osname", osname);
    encodeDataPair(data, "osarch", osarch);
    encodeDataPair(data, "osversion", osversion);
    encodeDataPair(data, "cores", Integer.toString(coreCount));
    encodeDataPair(data, "online-mode", Boolean.toString(onlineMode));
    encodeDataPair(data, "java_version", java_version);
    // If we're pinging, append it
    if (isPing) {
        encodeDataPair(data, "ping", "true");
    }
    // inside of the graph (e.g plotters)
    synchronized (graphs) {
        for (final Graph graph : graphs) {
            for (final Plotter plotter : graph.getPlotters()) {
                // The key name to send to the metrics server
                // The format is C-GRAPHNAME-PLOTTERNAME where separator -
                // is defined at the top
                // Legacy (R4) submitters use the format Custom%s, or
                // CustomPLOTTERNAME
                final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName());
                // The value to send, which for the foreseeable future is
                // just the string
                // value of plotter.getValue()
                final String value = Integer.toString(plotter.getValue());
                // Add it to the http post data :)
                encodeDataPair(data, key, value);
            }
        }
    }
    // Create the url
    final URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(pluginName)));
    // Connect to the website
    URLConnection connection;
    // It does not reroute POST requests so we need to go around it
    if (isMineshafterPresent()) {
        connection = url.openConnection(Proxy.NO_PROXY);
    } else {
        connection = url.openConnection();
    }
    connection.setDoOutput(true);
    // Write the data
    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(data.toString());
    writer.flush();
    // Now read the response
    final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    final String response = reader.readLine();
    // close resources
    writer.close();
    reader.close();
    if (response == null || response.startsWith("ERR")) {
        // Throw the exception
        throw new IOException(response);
    } else {
        // Is this the first update this hour?
        if (response.contains("OK This is your first update this hour")) {
            synchronized (graphs) {
                for (final Graph graph : graphs) {
                    for (final Plotter plotter : graph.getPlotters()) {
                        plotter.reset();
                    }
                }
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter)

Example 12 with PluginDescriptionFile

use of org.bukkit.plugin.PluginDescriptionFile in project Denizen-For-Bukkit by DenizenScript.

the class MetricsLite method postPlugin.

/**
     * Generic method that posts a plugin to the metrics website
     */
private void postPlugin(boolean isPing) throws IOException {
    // Server software specific section
    PluginDescriptionFile description = plugin.getDescription();
    String pluginName = description.getName();
    // TRUE if online mode is enabled
    boolean onlineMode = Bukkit.getServer().getOnlineMode();
    String pluginVersion = description.getVersion();
    String serverVersion = Bukkit.getVersion();
    // DENIZEN - correct player count system for .17.10
    int playersOnline = Bukkit.getServer().getOnlinePlayers().size();
    // END server software specific section -- all code below does not use any code outside of this class / Java
    // Construct the post data
    StringBuilder json = new StringBuilder(1024);
    json.append('{');
    // The plugin's description file containg all of the plugin data such as name, version, author, etc
    appendJSONPair(json, "guid", guid);
    appendJSONPair(json, "plugin_version", pluginVersion);
    appendJSONPair(json, "server_version", serverVersion);
    appendJSONPair(json, "players_online", Integer.toString(playersOnline));
    // New data as of R6
    String osname = System.getProperty("os.name");
    String osarch = System.getProperty("os.arch");
    String osversion = System.getProperty("os.version");
    String java_version = System.getProperty("java.version");
    int coreCount = Runtime.getRuntime().availableProcessors();
    // normalize os arch .. amd64 -> x86_64
    if (osarch.equals("amd64")) {
        osarch = "x86_64";
    }
    appendJSONPair(json, "osname", osname);
    appendJSONPair(json, "osarch", osarch);
    appendJSONPair(json, "osversion", osversion);
    appendJSONPair(json, "cores", Integer.toString(coreCount));
    appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
    appendJSONPair(json, "java_version", java_version);
    // If we're pinging, append it
    if (isPing) {
        appendJSONPair(json, "ping", "1");
    }
    // close json
    json.append('}');
    // Create the url
    URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
    // Connect to the website
    URLConnection connection;
    // It does not reroute POST requests so we need to go around it
    if (isMineshafterPresent()) {
        connection = url.openConnection(Proxy.NO_PROXY);
    } else {
        connection = url.openConnection();
    }
    byte[] uncompressed = json.toString().getBytes();
    byte[] compressed = gzip(json.toString());
    // Headers
    connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Content-Encoding", "gzip");
    connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.setDoOutput(true);
    if (debug) {
        System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
    }
    // Write the data
    OutputStream os = connection.getOutputStream();
    os.write(compressed);
    os.flush();
    // Now read the response
    final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String response = reader.readLine();
    // close resources
    os.close();
    reader.close();
    if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
        if (response == null) {
            response = "null";
        } else if (response.startsWith("7")) {
            response = response.substring(response.startsWith("7,") ? 2 : 1);
        }
        throw new IOException(response);
    }
}
Also used : GZIPOutputStream(java.util.zip.GZIPOutputStream) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) URL(java.net.URL) URLConnection(java.net.URLConnection)

Example 13 with PluginDescriptionFile

use of org.bukkit.plugin.PluginDescriptionFile in project Bukkit by Bukkit.

the class JavaPluginLoader method getPluginDescription.

public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException {
    Validate.notNull(file, "File cannot be null");
    JarFile jar = null;
    InputStream stream = null;
    try {
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry("plugin.yml");
        if (entry == null) {
            throw new InvalidDescriptionException(new FileNotFoundException("Jar does not contain plugin.yml"));
        }
        stream = jar.getInputStream(entry);
        return new PluginDescriptionFile(stream);
    } catch (IOException ex) {
        throw new InvalidDescriptionException(ex);
    } catch (YAMLException ex) {
        throw new InvalidDescriptionException(ex);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }
}
Also used : InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) YAMLException(org.yaml.snakeyaml.error.YAMLException) InvalidDescriptionException(org.bukkit.plugin.InvalidDescriptionException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry)

Example 14 with PluginDescriptionFile

use of org.bukkit.plugin.PluginDescriptionFile in project Dragonet-Legacy by DragonetMC.

the class MixedPluginManager method loadPlugins.

/**
     * Loads the array of plugins
     *
     * @param files Array of plugin files to load
     * @param sourceFolder Containing folder path name string for error messages
     * @return
     */
public Plugin[] loadPlugins(File[] files, String sourceFolder) {
    List<Plugin> result = new ArrayList<Plugin>();
    Set<Pattern> filters = fileAssociations.keySet();
    Map<String, File> plugins = new HashMap<String, File>();
    Set<String> loadedPlugins = new HashSet<String>();
    Map<String, Collection<String>> dependencies = new HashMap<String, Collection<String>>();
    Map<String, Collection<String>> softDependencies = new HashMap<String, Collection<String>>();
    // This is where it figures out all possible plugins
    for (File file : files) {
        // Skip plugins in the ignore set
        try {
            URL url = file.toURI().toURL();
            if (ignoreURLs != null && ignoreURLs.contains(file.toURI().toURL())) {
                continue;
            }
        } catch (MalformedURLException ex) {
        // ignore
        }
        PluginLoader loader = null;
        for (Pattern filter : filters) {
            Matcher match = filter.matcher(file.getName());
            if (match.find()) {
                loader = fileAssociations.get(filter);
            }
        }
        if (loader == null)
            continue;
        PluginDescriptionFile description = null;
        try {
            description = loader.getPluginDescription(file);
            String name = description.getName();
            if (name.equalsIgnoreCase("bukkit") || name.equalsIgnoreCase("minecraft") || name.equalsIgnoreCase("mojang")) {
                server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + sourceFolder + "': Restricted Name");
                continue;
            } else if (description.getRawName().indexOf(' ') != -1) {
                server.getLogger().warning(String.format("Plugin `%s' uses the space-character (0x20) in its name `%s' - this is discouraged", description.getFullName(), description.getRawName()));
            }
        } catch (InvalidDescriptionException ex) {
            server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + sourceFolder + "'", ex);
            continue;
        }
        File replacedFile = plugins.put(description.getName(), file);
        if (replacedFile != null) {
            server.getLogger().severe(String.format("Ambiguous plugin name `%s' for files `%s' and `%s' in `%s'", description.getName(), file.getPath(), replacedFile.getPath(), sourceFolder));
        }
        Collection<String> softDependencySet = description.getSoftDepend();
        if (softDependencySet != null && !softDependencySet.isEmpty()) {
            if (softDependencies.containsKey(description.getName())) {
                // Duplicates do not matter, they will be removed together if applicable
                softDependencies.get(description.getName()).addAll(softDependencySet);
            } else {
                softDependencies.put(description.getName(), new LinkedList<String>(softDependencySet));
            }
        }
        Collection<String> dependencySet = description.getDepend();
        if (dependencySet != null && !dependencySet.isEmpty()) {
            dependencies.put(description.getName(), new LinkedList<String>(dependencySet));
        }
        Collection<String> loadBeforeSet = description.getLoadBefore();
        if (loadBeforeSet != null && !loadBeforeSet.isEmpty()) {
            for (String loadBeforeTarget : loadBeforeSet) {
                if (softDependencies.containsKey(loadBeforeTarget)) {
                    softDependencies.get(loadBeforeTarget).add(description.getName());
                } else {
                    // softDependencies is never iterated, so 'ghost' plugins aren't an issue
                    Collection<String> shortSoftDependency = new LinkedList<String>();
                    shortSoftDependency.add(description.getName());
                    softDependencies.put(loadBeforeTarget, shortSoftDependency);
                }
            }
        }
    }
    while (!plugins.isEmpty()) {
        boolean missingDependency = true;
        Iterator<String> pluginIterator = plugins.keySet().iterator();
        while (pluginIterator.hasNext()) {
            String plugin = pluginIterator.next();
            if (dependencies.containsKey(plugin)) {
                Iterator<String> dependencyIterator = dependencies.get(plugin).iterator();
                while (dependencyIterator.hasNext()) {
                    String dependency = dependencyIterator.next();
                    // Dependency loaded
                    if (loadedPlugins.contains(dependency)) {
                        dependencyIterator.remove();
                    // We have a dependency not found
                    } else if (!plugins.containsKey(dependency)) {
                        missingDependency = false;
                        File file = plugins.get(plugin);
                        pluginIterator.remove();
                        softDependencies.remove(plugin);
                        dependencies.remove(plugin);
                        server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + sourceFolder + "'", new UnknownDependencyException(dependency));
                        break;
                    }
                }
                if (dependencies.containsKey(plugin) && dependencies.get(plugin).isEmpty()) {
                    dependencies.remove(plugin);
                }
            }
            if (softDependencies.containsKey(plugin)) {
                Iterator<String> softDependencyIterator = softDependencies.get(plugin).iterator();
                while (softDependencyIterator.hasNext()) {
                    String softDependency = softDependencyIterator.next();
                    // Soft depend is no longer around
                    if (!plugins.containsKey(softDependency)) {
                        softDependencyIterator.remove();
                    }
                }
                if (softDependencies.get(plugin).isEmpty()) {
                    softDependencies.remove(plugin);
                }
            }
            if (!(dependencies.containsKey(plugin) || softDependencies.containsKey(plugin)) && plugins.containsKey(plugin)) {
                // We're clear to load, no more soft or hard dependencies left
                File file = plugins.get(plugin);
                pluginIterator.remove();
                missingDependency = false;
                try {
                    result.add(loadPlugin(file));
                    loadedPlugins.add(plugin);
                    continue;
                } catch (InvalidPluginException ex) {
                    server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + sourceFolder + "'", ex);
                }
            }
        }
        if (missingDependency) {
            // We now iterate over plugins until something loads
            // This loop will ignore soft dependencies
            pluginIterator = plugins.keySet().iterator();
            while (pluginIterator.hasNext()) {
                String plugin = pluginIterator.next();
                if (!dependencies.containsKey(plugin)) {
                    softDependencies.remove(plugin);
                    missingDependency = false;
                    File file = plugins.get(plugin);
                    pluginIterator.remove();
                    try {
                        result.add(loadPlugin(file));
                        loadedPlugins.add(plugin);
                        break;
                    } catch (InvalidPluginException ex) {
                        server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + sourceFolder + "'", ex);
                    }
                }
            }
            // We have no plugins left without a depend
            if (missingDependency) {
                softDependencies.clear();
                dependencies.clear();
                Iterator<File> failedPluginIterator = plugins.values().iterator();
                while (failedPluginIterator.hasNext()) {
                    File file = failedPluginIterator.next();
                    failedPluginIterator.remove();
                    server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + sourceFolder + "': circular dependency detected");
                }
            }
        }
    }
    return result.toArray(new Plugin[result.size()]);
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) WeakHashMap(java.util.WeakHashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) URL(java.net.URL) InvalidPluginException(org.bukkit.plugin.InvalidPluginException) PluginLoader(org.bukkit.plugin.PluginLoader) HashSet(java.util.HashSet) Pattern(java.util.regex.Pattern) InvalidDescriptionException(org.bukkit.plugin.InvalidDescriptionException) LinkedList(java.util.LinkedList) UnknownDependencyException(org.bukkit.plugin.UnknownDependencyException) Collection(java.util.Collection) File(java.io.File) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) Plugin(org.bukkit.plugin.Plugin)

Example 15 with PluginDescriptionFile

use of org.bukkit.plugin.PluginDescriptionFile in project AuthMeReloaded by AuthMe.

the class AuthMeInitializationTest method initAuthMe.

@Before
public void initAuthMe() throws IOException {
    dataFolder = temporaryFolder.newFolder();
    File settingsFile = new File(dataFolder, "config.yml");
    JavaPluginLoader pluginLoader = new JavaPluginLoader(server);
    Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "config.test.yml"), settingsFile);
    // Mock / wire various Bukkit components
    given(server.getLogger()).willReturn(mock(Logger.class));
    ReflectionTestUtils.setField(Bukkit.class, null, "server", server);
    given(server.getPluginManager()).willReturn(pluginManager);
    // PluginDescriptionFile is final: need to create a sample one
    PluginDescriptionFile descriptionFile = new PluginDescriptionFile("AuthMe", "N/A", AuthMe.class.getCanonicalName());
    // Initialize AuthMe
    authMe = new AuthMe(pluginLoader, descriptionFile, dataFolder, null);
}
Also used : JavaPluginLoader(org.bukkit.plugin.java.JavaPluginLoader) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) Logger(java.util.logging.Logger) File(java.io.File) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile) Before(org.junit.Before)

Aggregations

PluginDescriptionFile (org.bukkit.plugin.PluginDescriptionFile)15 URL (java.net.URL)7 IOException (java.io.IOException)6 URLConnection (java.net.URLConnection)6 File (java.io.File)5 BufferedReader (java.io.BufferedReader)4 InputStreamReader (java.io.InputStreamReader)4 GZIPOutputStream (java.util.zip.GZIPOutputStream)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 OutputStream (java.io.OutputStream)3 ArrayList (java.util.ArrayList)3 InvalidDescriptionException (org.bukkit.plugin.InvalidDescriptionException)3 Minigame (au.com.mineauz.minigames.minigame.Minigame)2 JarFile (java.util.jar.JarFile)2 Player (org.bukkit.entity.Player)2 InvalidPluginException (org.bukkit.plugin.InvalidPluginException)2 Plugin (org.bukkit.plugin.Plugin)2 UnknownDependencyException (org.bukkit.plugin.UnknownDependencyException)2 PotionEffect (org.bukkit.potion.PotionEffect)2