id
stringlengths
36
36
text
stringlengths
1
1.25M
e9b1be05-8c22-4a2f-b365-24e7db727b7e
public Metrics(final Plugin plugin) throws IOException { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } this.plugin = plugin; // load the config configurationFile = getConfigFile(); configuration = YamlConfiguration.loadConfiguration(configurationFile); // add some defaults configuration.addDefault("opt-out", false); configuration.addDefault("guid", UUID.randomUUID().toString()); configuration.addDefault("debug", false); // Do we need to create the file? if (configuration.get("guid", null) == null) { configuration.options().header("http://mcstats.org").copyDefaults(true); configuration.save(configurationFile); } // Load the guid then guid = configuration.getString("guid"); debug = configuration.getBoolean("debug", false); }
aa45e1c3-a378-407f-a9e4-84c2fa6754e7
public Graph createGraph(final String name) { if (name == null) { throw new IllegalArgumentException("Graph name cannot be null"); } // Construct the graph object final Graph graph = new Graph(name); // Now we can add our graph graphs.add(graph); // and return back return graph; }
cd7864f8-4730-4611-8f45-1d73a1aec8ca
public void addGraph(final Graph graph) { if (graph == null) { throw new IllegalArgumentException("Graph cannot be null"); } graphs.add(graph); }
224816b6-3a87-45ff-9d02-7b81763dd25e
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
56d845ff-558f-49e5-a21f-45fd60ed216f
public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } }
20784703-3a1c-4711-8e7a-7c539b76cbab
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
38130bf7-a4e4-43d2-9815-dbcf823782a8
public void enable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (isOptOut()) { configuration.set("opt-out", false); configuration.save(configurationFile); } // Enable Task, if it is not running if (task == null) { start(); } } }
e52ac769-f117-442c-b846-f8b4bc6e1d7f
public void disable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (!isOptOut()) { configuration.set("opt-out", true); configuration.save(configurationFile); } // Disable Task, if it is running if (task != null) { task.cancel(); task = null; } } }
ddf62d23-7090-46bb-95aa-5a4e7f2a9868
public File getConfigFile() { // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use // is to abuse the plugin object we already have // plugin.getDataFolder() => base/plugins/PluginA/ // pluginsFolder => base/plugins/ // The base is not necessarily relative to the startup directory. File pluginsFolder = plugin.getDataFolder().getParentFile(); // return => base/plugins/PluginMetrics/config.yml return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); }
ccec443b-796f-4586-aadb-4e58b4039d1c
private void postPlugin(final boolean isPing) throws IOException { // Server software specific section PluginDescriptionFile description = plugin.getDescription(); String pluginName = description.getName(); boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled String pluginVersion = description.getVersion(); String serverVersion = Bukkit.getVersion(); int playersOnline = Bukkit.getServer().getOnlinePlayers().length; // 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"); } if (graphs.size() > 0) { synchronized (graphs) { json.append(','); json.append('"'); json.append("graphs"); json.append('"'); json.append(':'); json.append('{'); boolean firstGraph = true; final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { Graph graph = iter.next(); StringBuilder graphJson = new StringBuilder(); graphJson.append('{'); for (Plotter plotter : graph.getPlotters()) { appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); } graphJson.append('}'); if (!firstGraph) { json.append(','); } json.append(escapeJSON(graph.getName())); json.append(':'); json.append(graphJson); firstGraph = false; } json.append('}'); } } // 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; // Mineshafter creates a socks proxy, so we can safely bypass it // 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); } else { // Is this the first update this hour? if (response.equals("1") || response.contains("This is your first update this hour")) { synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } }
2611a598-cb48-4428-8bbb-5b9da6ca4a85
public static byte[] gzip(String input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(baos); gzos.write(input.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { if (gzos != null) try { gzos.close(); } catch (IOException ignore) { } } return baos.toByteArray(); }
7141ea81-b6cf-4942-84d5-26b6fc1f3254
private boolean isMineshafterPresent() { try { Class.forName("mineshafter.MineServer"); return true; } catch (Exception e) { return false; } }
ad0f0c5c-d8ef-4bf9-94a2-c10504d4ad4d
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
c7093e73-0889-427d-80a9-3a9c70104b3a
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
9d9214c3-d5a4-4824-be4f-7b41b171a1e9
private static String urlEncode(final String text) throws UnsupportedEncodingException { return URLEncoder.encode(text, "UTF-8"); }
5f37ed68-f6d6-4e3d-90e8-a15cacedb7d5
private Graph(final String name) { this.name = name; }
3ecbb797-c6f2-4c4b-92a5-7ce3f09e98f9
public String getName() { return name; }
a488d710-4f9a-455b-9853-cf3c41e3279b
public void addPlotter(final Plotter plotter) { plotters.add(plotter); }
9d756d6a-6d9d-4a25-b9af-69c4587ca070
public void removePlotter(final Plotter plotter) { plotters.remove(plotter); }
597a992c-a534-4417-aa4d-655d0a404e27
public Set<Plotter> getPlotters() { return Collections.unmodifiableSet(plotters); }
f6ff9fbe-8d1b-4b6d-8898-105532917258
@Override public int hashCode() { return name.hashCode(); }
f5347f26-3790-4fa9-b1a0-545312f5ab4c
@Override public boolean equals(final Object object) { if (!(object instanceof Graph)) { return false; } final Graph graph = (Graph) object; return graph.name.equals(name); }
f8671c9e-07f6-4997-8b0b-f68dde95e07d
protected void onOptOut() { }
ab03338f-4ac2-4559-aba9-0534894490e8
public Plotter() { this("Default"); }
75bb036d-ae35-45a6-98c9-26c8e3060026
public Plotter(final String name) { this.name = name; }
a806bfc1-98fb-4b2d-a1c3-57cdfb2d46a2
public abstract int getValue();
c9fccc22-d290-4c9c-b176-08caa4658b70
public String getColumnName() { return name; }
10066a3e-9d00-4d60-a362-1af2f590368b
public void reset() { }
ede48afa-da7f-49fa-b8e5-05327e6e4c3e
@Override public int hashCode() { return getColumnName().hashCode(); }
7a99b7bc-a572-49cb-ac51-d4f421240854
@Override public boolean equals(final Object object) { if (!(object instanceof Plotter)) { return false; } final Plotter plotter = (Plotter) object; return plotter.name.equals(name) && plotter.getValue() == getValue(); }
1e056834-7911-426a-ac4e-ee66ef3d43f7
public Configuration(ButtonWarpRandom plugin){ Configuration.plugin = plugin; plugin.getConfig().options().copyDefaults(true); plugin.getLogger().info("Configuration loaded!"); List<?> biomesInc = plugin.getConfig().getList("included-biomes"); for (Object b : biomesInc){ String biome = ((String)b).toUpperCase(); // Convert to upper try{ plugin.getLogger().info("Default Include Biome: " + biome); BiomesIncluded.add(Biome.valueOf(biome)); }catch (Exception ex){ plugin.getLogger().severe("Unknown Biome in configuration! '" + b + "'"); ex.printStackTrace(); } } List<?> biomesExcl = plugin.getConfig().getList("excluded-biomes"); for (Object b : biomesExcl){ String biome = ((String)b).toUpperCase(); // Convert to upper try{ plugin.getLogger().info("Default Exclude Biome: " + biome); BiomesExcluded.add(Biome.valueOf(biome)); }catch (Exception ex){ plugin.getLogger().severe("Unknown Biome in configuration! '" + biome + "'"); ex.printStackTrace(); } } plugin.saveConfig(); }
83f5acda-e17b-4fcf-8fe7-9f9e733b8b14
public static void reloadConfig(){ BiomesExcluded = new ArrayList<Biome>(); // Reset BiomesIncluded = new ArrayList<Biome>(); // Reset plugin.reloadConfig(); List<?> biomesInc = plugin.getConfig().getList("included-biomes"); for (Object b : biomesInc){ String biome = ((String)b).toUpperCase(); // Convert to upper try{ plugin.getLogger().info("Default Include Biome: " + biome); BiomesIncluded.add(Biome.valueOf(biome)); }catch (Exception ex){ plugin.getLogger().severe("Unknown Biome in configuration! '" + b + "'"); ex.printStackTrace(); } } List<?> biomesExcl = plugin.getConfig().getList("excluded-biomes"); for (Object b : biomesExcl){ String biome = ((String)b).toUpperCase(); // Convert to upper try{ plugin.getLogger().info("Default Exclude Biome: " + biome); BiomesExcluded.add(Biome.valueOf(biome)); }catch (Exception ex){ plugin.getLogger().severe("Unknown Biome in configuration! '" + biome + "'"); ex.printStackTrace(); } } }
6f24fa49-151e-41e9-884a-9e3dbf468afe
public Converter(){ Collection<Warp> warps = ButtonWarp.getWarps(); for (Warp warp : warps){ // Check if warp contains bwr if (warp.commands.size() != 0){ String cmd = warp.commands.getFirst(); if (cmd.startsWith("bwr") && !cmd.contains("-")){ String args[] = cmd.split("\\s+"); // Try to parse try{ String newCmd = "bwr randomize " + args[2] + " -min " + args[3] + " -max " + args[4] + " -p <player>"; warp.commands.set(0, newCmd); warp.save(); Bukkit.getLogger().info("[ButtonWarpRandom] Converted old warp '" + warp.name + "'"); }catch (Exception ex){ } } } } }
05ce576c-8e1e-4471-80b0-5213eb7bda89
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); final File pluginFile = plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); if (!updaterFile.exists()) { updaterFile.mkdir(); } if (!updaterConfigFile.exists()) { try { updaterConfigFile.createNewFile(); } catch (final IOException e) { plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } this.config = YamlConfiguration.loadConfiguration(updaterConfigFile); this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); this.config.addDefault("api-key", "PUT_API_KEY_HERE"); this.config.addDefault("disable", false); if (this.config.get("api-key", null) == null) { this.config.options().copyDefaults(true); try { this.config.save(updaterConfigFile); } catch (final IOException e) { plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } if (this.config.getBoolean("disable")) { this.result = UpdateResult.DISABLED; return; } String key = this.config.getString("api-key"); if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } this.apiKey = key; try { this.url = new URL(Updater.HOST + Updater.QUERY + id); } catch (final MalformedURLException e) { plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); this.result = UpdateResult.FAIL_BADID; e.printStackTrace(); } this.thread = new Thread(new UpdateRunnable()); this.thread.start(); }
814933b1-51eb-443a-a4c5-9a16d81972b4
public Updater.UpdateResult getResult() { this.waitForThread(); return this.result; }
14af42d6-56dc-4f5b-b503-4ab26b637214
public String getLatestType() { this.waitForThread(); return this.versionType; }
43404b2a-1e8c-4c6e-b359-e46ed84ac3f7
public String getLatestGameVersion() { this.waitForThread(); return this.versionGameVersion; }
4ab57723-46a7-4ebd-ac09-815a2d486122
public String getLatestName() { this.waitForThread(); return this.versionName; }
74081386-58c0-44d8-8d55-ab2c8490d7ed
public String getLatestFileLink() { this.waitForThread(); return this.versionLink; }
bf80b321-9a7c-4ad6-91be-81beed0c415c
private void waitForThread() { if ((this.thread != null) && this.thread.isAlive()) { try { this.thread.join(); } catch (final InterruptedException e) { e.printStackTrace(); } } }
4a73ae1b-02a7-449b-92fb-4a3aaca55698
private void saveFile(File folder, String file, String u) { if (!folder.exists()) { folder.mkdir(); } BufferedInputStream in = null; FileOutputStream fout = null; try { // Download the file final URL url = new URL(u); final int fileLength = url.openConnection().getContentLength(); in = new BufferedInputStream(url.openStream()); fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); final byte[] data = new byte[Updater.BYTE_SIZE]; int count; if (this.announce) { this.plugin.getLogger().info("About to download a new update: " + this.versionName); } long downloaded = 0; while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); final int percent = (int) ((downloaded * 100) / fileLength); if (this.announce && ((percent % 10) == 0)) { this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } //Just a quick check to make sure we didn't leave any files from last time... for (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) { if (xFile.getName().endsWith(".zip")) { xFile.delete(); } } // Check to see if it's a zip file, if it is, unzip it. final File dFile = new File(folder.getAbsolutePath() + "/" + file); if (dFile.getName().endsWith(".zip")) { // Unzip this.unzip(dFile.getCanonicalPath()); } if (this.announce) { this.plugin.getLogger().info("Finished updating."); } } catch (final Exception ex) { this.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { try { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } catch (final Exception ex) { } } }
492ffade-b93a-4a27-9579-18b8bebcc99b
private void unzip(String file) { try { final File fSourceZip = new File(file); final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte buffer[] = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginFile(name)) { destinationFilePath.renameTo(new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name)); } } entry = null; destinationFilePath = null; } e = null; zipFile.close(); zipFile = null; // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. for (final File dFile : new File(zipPath).listFiles()) { if (dFile.isDirectory()) { if (this.pluginFile(dFile.getName())) { final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir final File[] contents = oFile.listFiles(); // List of existing files in the current dir for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir { boolean found = false; for (final File xFile : contents) // Loop through contents to see if it exists { if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); } else { // This file already exists, so we don't need it anymore. cFile.delete(); } } } } dFile.delete(); } new File(zipPath).delete(); fSourceZip.delete(); } catch (final IOException ex) { this.plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; ex.printStackTrace(); } new File(file).delete(); }
6233f11d-3953-4077-b0aa-4a8274e92110
private boolean pluginFile(String name) { for (final File file : new File("plugins").listFiles()) { if (file.getName().equals(name)) { return true; } } return false; }
13577885-9682-4084-b952-5d8e2da94efe
private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String version = this.plugin.getDescription().getVersion(); if (title.split(" v").length == 2) { final String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get the newest file's version number if (this.hasTag(version) || version.equalsIgnoreCase(remoteVersion)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
f533d3b0-cb05-4e34-aaed-00bd62c7aa0f
private boolean hasTag(String version) { for (final String string : Updater.NO_UPDATE_TAG) { if (version.contains(string)) { return true; } } return false; }
7379f53b-3668-4b6d-a7e9-669405ceccaf
private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
15e6772b-0d90-4d98-91d3-d9ab4f5c02fb
@Override public void run() { if (Updater.this.url != null) { // Obtain the results of the project's file feed if (Updater.this.read()) { if (Updater.this.versionCheck(Updater.this.versionName)) { if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { String name = Updater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (Updater.this.versionLink.endsWith(".zip")) { final String[] split = Updater.this.versionLink.split("/"); name = split[split.length - 1]; } Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); } else { Updater.this.result = UpdateResult.UPDATE_AVAILABLE; } } } } }
751d0f0e-5f8e-4fdc-902b-1fc156b0a33a
Board(int boardSize, int boxHight, int boxLength, int[] boardLine, SudokuBuffer buffer) { board = new Square[boardSize][boardSize]; Column[] column = new Column[boardSize]; Row[] row = new Row[boardSize]; Box[][] box = new Box[boxLength][boxHight]; this.boardSize = boardSize; this.boardLine = boardLine; this.buffer = buffer; // Making column-, row- and box pointers for (int i = 0; i < boardSize; i++) { column[i] = new Column(boardSize); row[i] = new Row(boardSize); box[i/boxHight][i%boxHight] = new Box(boardSize); } int boardCounter = 0; //variables.clear(); for (int r = 0; r < 9; r++) { for (int c = 0; c < 9; c++) { int number = boardLine[boardCounter++]; board[r][c] = new Square(number, row[r], column[c], box[r/boxHight][c/boxLength], this); //System.out.println(board[r][c].value); } } Square previous = null; // Making the next pointers for (int r = boardSize-1; r >= 0; r--){ for (int c = boardSize-1; c >= 0; c--) { board[r][c].next = previous; previous = board[r][c]; } } board[0][0].setNumber(); }
71b66aff-ce13-4222-9974-cf8034c7400d
public void saveSolution() { solCount++; if (solCount > 1) { return; } solution = new int[81]; int counter = 0; for(int i = 0; i < board.length; i++) { for (int j = 0; j < board.length; j++) { solution[counter++] = board[i][j].value; //System.out.print(board[i][j].value); } }//System.out.print("added solution\n"); buffer.add(solution); //return; }
ccff3d7c-0966-403a-9dcf-1ca3e2132775
Column(int size) { super(size); }
46640142-823d-49ed-a618-f0bc6ab3af97
Box(int size) { super(size); }
3a7b2d44-4bdd-4786-840e-cae380e82a5f
Row(int size) { super(size); }
670771b4-e983-45b1-bd13-68f1cb0ca92e
Container(int size) { number = new boolean[size]; }
1dedf0c5-4bd6-46c5-956c-5f61a59d02e1
public boolean checkNumber(int i) { return !number[i-1]; }
f143effd-1c0e-4eac-a47d-9689b311185e
public void setValue(int i, boolean take) { if (i != 0 && i != -1) { number[i-1] = take; } }
23755a89-064f-4413-a747-e1732797770d
SudokuBuffer() { solutionBuffer = new ArrayList<int[]>(); }
00596791-a4ab-4dd1-bd67-0c6498f08079
public void add(int[] solution) { solutionBuffer.add(solution); }
3719622f-4485-49cd-b445-f8b0bc87950b
public int[] get(int index) { return solutionBuffer.get(index); }
7f8137de-cff9-4583-a4ab-69135562fdbe
public static void main(String[] args) { String infile = args[0]; String outfile = args[1]; ScannerReadFile read = new ScannerReadFile(); read.readFile(infile, outfile); }
25a1de57-7b1d-4799-a2de-11c3055d45fe
public void readFile(String infile, String outfile) { filename = infile; outfilename = outfile; // Location of file to read and write File file = new File(filename); File out = new File(outfilename); SudokuBuffer buffer = new SudokuBuffer(); try { System.out.println("---CSP Solver---"); System.out.println("Trying to find solution(s) for sudoku puzzles in the file: " + filename); System.out.println("Writing solutions to the file: " + outfilename); Scanner scanner = new Scanner(file); long startTime = System.currentTimeMillis(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); //System.out.println(line); int[] convertedLine = splitLine(line); if (convertedLine.length == 81) { Board board = new Board(9, 3 ,3, convertedLine, buffer); } } long endTime = System.currentTimeMillis(); System.out.print("Time to solve: " + (endTime - startTime) + " milliseconds --> "); System.out.println((endTime - startTime) / 1000.0 + " seconds."); System.out.println("----------------"); //System.out.print("ferdig med sol\n"); writeFile(buffer, out); scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
19993c7d-f74f-48ce-9379-643b7b8f7f64
public int[] splitLine(String line) { int[] board = new int[line.length()]; char[] temp = new char[line.length()]; temp = line.toCharArray(); for (int i = 0; i < temp.length; i++) { if (temp[i] == '.') { board[i] = 0; } else { board[i] = Character.getNumericValue(temp[i]); } //System.out.print(board[i]); } //System.out.println(" "); return board; }
c19e705a-eafd-4923-8e81-f854f55003b0
public void writeFile(SudokuBuffer buffer, File out) { String print; try { Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out), "utf-8")); //DataOutputStream writer = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(out))); //System.out.println("in write"); for(int i = 0; i < buffer.solutionBuffer.size(); i++) { print = ""; for (int j = 0; j < buffer.solutionBuffer.get(i).length; j++ ) { //writer.write(buffer.solutionBuffer.get(i)[j]); print += Integer.toString(buffer.solutionBuffer.get(i)[j]); //System.out.print(buffer.solutionBuffer.get(i)[j]); } //System.out.print("\n"); writer.write(print + "\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } }
21e7f619-4b6f-445d-a150-54c73f68683a
Square(int value, Row r, Column c, Box b, Board board) { this.value = value; this.r = r; this.c = c; this.b = b; this.board = board; this.setValue(value); }
0b01210c-ea91-4c1b-b90d-64c10fc55b43
Square(Row r, Column c, Box b, Board board) { this.r = r; this.c = c; this.b = b; this.board = board; }
bc4e81bc-03bf-4c90-809a-ad5976eb555d
public void setNumber() { /*if (solutionCounter > 1) { if (solutionFound == true) { System.out.println("sol found square"); return; } }*/ if (value > 0) { if (next == null) { foundSolution(); } else { next.setNumber(); } } else { //Could be improved by adding domain to the square and //only check values in the domain. for (int i = 1; i <= r.number.length; i++) { if (legal(i)) { setValue(i); if (next == null) { foundSolution(); } else { next.setNumber(); } releaseValue(); } } } }
6800bc1e-2ad1-44f1-989e-2345890eb5be
public boolean legal(int number) { if (r.checkNumber(number) && b.checkNumber(number) && c.checkNumber(number)) { return true; } return false; }
02a5c1f8-33be-4ae5-94ab-f9b5b514fe7c
public void foundSolution() { //System.out.println("solfound square"); solutionCounter++; solutionFound = true; if (solutionCounter > 1) { return; } board.saveSolution(); //return; }
fc24da6d-98cb-432a-bb6c-3475e4026191
public void setValue(int i) { r.setValue(i, true); c.setValue(i, true); b.setValue(i, true); value = i; }
4bf9a5a8-3f82-47ef-9fdb-e7d04994c2bf
public void releaseValue() { r.setValue(value, false); c.setValue(value, false); b.setValue(value, false); value = 0; }
e0fb8e20-38bf-4c91-8791-b4f51196a30d
@RequestMapping(value = {"/", "/welcome**"},method = RequestMethod.GET) public ModelAndView defaultPage(){ ModelAndView model = new ModelAndView(); model.addObject("title","My Call Sheet Login"); model.addObject("message"," This is default page"); model.setViewName("hello"); return model; }
f00805c2-12a5-4fae-a510-e097940f68ee
@RequestMapping(value="/admin**", method=RequestMethod.GET) public ModelAndView adminPage(){ ModelAndView model = new ModelAndView(); model.addObject("title","My Call Sheet Login"); model.addObject("message","This is for ROLE_ADMIN only"); return model; }
c0bdab31-aae6-48fc-9506-b14e26f74c71
@RequestMapping(value="/login", method=RequestMethod.GET) public ModelAndView login(@RequestParam(value="error",required=false) String error, @RequestParam(value="logout",required=false) String logout, HttpServletRequest request){ ModelAndView model = new ModelAndView(); if(error != null){ model.addObject("error",getErrorMessage(request,"SPRING_SECURITY_LAST_EXCEPTION")); } if(logout != null){ model.addObject("msg","You have been loggedout successfully."); } model.setViewName("login"); return model; }
1bfe7c4a-698c-4e4b-95e3-0005ddd29570
private String getErrorMessage(HttpServletRequest request,String key){ Exception exception = (Exception) request.getSession().getAttribute(key); String error=null; if(exception instanceof BadCredentialsException){ error = "Invalid Username or Password !"; }else if(exception instanceof LockedException){ error = exception.getMessage(); }else{ error = "Invalid Username or Password !!"; } return error; }
e728f3b8-66ff-49eb-aa51-0108000e819f
@RequestMapping(value="/403") public ModelAndView accessDenied(){ ModelAndView model = new ModelAndView(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(!(auth instanceof AnonymousAuthenticationToken)){ UserDetails userDetail = (UserDetails) auth.getPrincipal(); System.out.println(userDetail); model.addObject("userName",userDetail.getUsername()); } model.setViewName("403"); return model; }
42e2da33-eb21-41b0-b104-93fa5f10796a
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException{ try{ Authentication auth = super.authenticate(authentication); userDetailsDao.resetFailAttempts(authentication.getName()); return auth; }catch(BadCredentialsException e){ userDetailsDao.updateFailAttempts(authentication.getName()); throw e; }catch(LockedException e){ String error=null; UserAttempts userAttempts = userDetailsDao.getUserAttempts(authentication.getName()); if(userAttempts != null){ Date lastAttempts = userAttempts.getLastModified(); error = "User Account is Locked !! <br><br> Username : "+authentication.getName() +"Last Attempts : "+lastAttempts; }else{ error = e.getMessage(); } throw new LockedException(error); } }
a6f92b85-e3e8-4968-825c-0db14933ce76
public UserDetailsDao getUserDetailsDao() { return userDetailsDao; }
eb528981-9f2d-4cde-a4c8-5b23a81dc831
public void setUserDetailsDao(UserDetailsDao userDetailsDao) { this.userDetailsDao = userDetailsDao; }
e8409e8f-0f26-4323-a2e8-5e5ed22a9bf5
public int getId() { return id; }
5603071e-a196-43bc-87e5-fe1965043e52
public void setId(int id) { this.id = id; }
eb778b5d-6011-4360-b405-d3f7f621c703
public String getUserName() { return userName; }
973a5669-0d63-40ed-9efa-dbbbf71b5ddd
public void setUserName(String userName) { this.userName = userName; }
fb3abc74-3bf0-40f9-b9b3-f9409dbb7dc9
public int getAttempts() { return attempts; }
f532793b-cb0e-4c77-94d0-bb4922f22b0d
public void setAttempts(int attempts) { this.attempts = attempts; }
eee0672b-eea8-4a50-9975-1987f78b5ce7
public Date getLastModified() { return lastModified; }
413394b9-5f11-44bb-a0db-c5171c169032
public void setLastModified(Date lastModified) { this.lastModified = lastModified; }
190518ff-a829-44b6-9a68-5f85c8d73ace
void updateFailAttempts(String userName);
44aa12f5-78d0-4e5f-8341-ac8549475d89
void resetFailAttempts(String userName);
6cffa87d-e565-45d1-b276-4321a0953d67
UserAttempts getUserAttempts(String userName);
1ae2e1fc-3da0-4084-a6d7-3750c2a65e3d
@PostConstruct private void initialize(){ setDataSource(dataSource); }
c9bea7ee-b5aa-4ea8-abf1-ce874a9f9c99
@Override public void updateFailAttempts(String userName) { UserAttempts user = getUserAttempts(userName); if(user == null){ if(isUserExists(userName)){ //If no record insert a new record getJdbcTemplate().update(SQL_USER_ATTEMPTS_INSERT,new Object[] {userName,1,new Date()}); } } else { if(isUserExists(userName)){ //Update attempts count+1 getJdbcTemplate().update(SQL_USER_ATTEMPTS_UPDATE_ATTEMPTS, new Object[]{new Date(),userName}); } if(user.getAttempts() +1 >= MAX_ATTEMPTS){ //locked user getJdbcTemplate().update(SQL_USERS_UPDATE_LOCKED, new Object[]{false,userName}); //throw exception throw new LockedException("User Account is Locked !"); } } }
5d5560fd-ab02-4db4-b734-198d600308e2
@Override public void resetFailAttempts(String userName) { getJdbcTemplate().update(SQL_USER_ATTEMPTS_RESET_ATTEMPTS,new Object[]{userName}); }
c2ac99ee-801f-491c-af10-01a13c9e4db4
@Override public UserAttempts getUserAttempts(String userName) { try{ UserAttempts userAttempts = getJdbcTemplate().queryForObject( SQL_USER_ATTEMPTS_GET, new Object[]{userName}, new RowMapper<UserAttempts> (){ @Override public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException { UserAttempts user = new UserAttempts(); user.setId(rs.getInt("id")); user.setUserName(rs.getString("username")); user.setAttempts(rs.getInt("attempts")); user.setLastModified(rs.getDate("lastModified")); return user; } }); return userAttempts; }catch(Exception e){ return null; } }
99ebf755-5d14-4239-b3e2-9a2ad51179ab
@Override public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException { UserAttempts user = new UserAttempts(); user.setId(rs.getInt("id")); user.setUserName(rs.getString("username")); user.setAttempts(rs.getInt("attempts")); user.setLastModified(rs.getDate("lastModified")); return user; }
424cd05c-696c-4619-a7d8-2f93330fef9f
public boolean isUserExists(String userName){ boolean result = false; int count = getJdbcTemplate().queryForObject(SQL_USERS_COUNT, new Object[] {userName}, Integer.class ); if(count > 0 ){ result = true; } return result; }
074d6be1-2656-4794-b332-13a0defa8096
@Override public void setUsersByUsernameQuery(String usersByUsernameQueryString){ super.setUsersByUsernameQuery(usersByUsernameQueryString); }
eb6be77e-4662-4946-8a6c-c6619067b7b8
@Override public void setAuthoritiesByUsernameQuery(String queryString){ super.setAuthoritiesByUsernameQuery(queryString); }
e0489d90-08dc-4b0a-8d5f-50fd1facddda
@Override public List<UserDetails> loadUsersByUsername(String userName){ return getJdbcTemplate().query(super.getUsersByUsernameQuery(), new String[]{userName}, new RowMapper<UserDetails>(){ @Override public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException { String userName = rs.getString("username"); String password = rs.getString("password"); boolean enabled = rs.getBoolean("enabled"); boolean accountNonExpired = rs.getBoolean("accountNonExpired"); boolean credentialsNonExpired = rs.getBoolean("credentialsNonExpired"); boolean accountNonLocked = rs.getBoolean("accountNonLocked"); return new User(userName, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,AuthorityUtils.NO_AUTHORITIES); } }); }
25b25f7d-39b2-4f12-816f-b6467da2428b
@Override public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException { String userName = rs.getString("username"); String password = rs.getString("password"); boolean enabled = rs.getBoolean("enabled"); boolean accountNonExpired = rs.getBoolean("accountNonExpired"); boolean credentialsNonExpired = rs.getBoolean("credentialsNonExpired"); boolean accountNonLocked = rs.getBoolean("accountNonLocked"); return new User(userName, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,AuthorityUtils.NO_AUTHORITIES); }
d88bdd91-a141-42d5-98f6-955a576068a0
@Override public UserDetails createUserDetails(String userName,UserDetails userFromUserQuery, List<GrantedAuthority> combinedAuthorities){ String returnUserName = userFromUserQuery.getUsername(); if(super.isUsernameBasedPrimaryKey()){ returnUserName = userName; } return new User(returnUserName, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), userFromUserQuery.isAccountNonExpired(),userFromUserQuery.isCredentialsNonExpired(), userFromUserQuery.isAccountNonLocked(),combinedAuthorities); }
9c06e3f0-049a-41a0-9cc2-d2e52f8e004c
public static void first() { int[] array = new int[SIZE]; for (int i = 0; i < SIZE; i++) { array[i] = i; } }