List of usage examples for com.google.common.collect Multiset add
@Override
boolean add(E element);
From source file:org.apache.twill.internal.appmaster.RunningContainers.java
/** * Handle completion of container./*from w w w . ja v a 2s.com*/ * * @param status The completion status. * @param restartRunnables Set of runnable names that requires restart. */ void handleCompleted(YarnContainerStatus status, Multiset<String> restartRunnables) { containerLock.lock(); String containerId = status.getContainerId(); int exitStatus = status.getExitStatus(); ContainerState state = status.getState(); try { removeContainerInfo(containerId); Map<String, TwillContainerController> lookup = containers.column(containerId); if (lookup.isEmpty()) { // It's OK because if a container is stopped through stopByIdAndWait(), this would be empty. return; } if (lookup.size() != 1) { LOG.warn("More than one controller found for container {}", containerId); } boolean containerStopped = false; final String runnableName = lookup.keySet().iterator().next(); int instanceId = 0; for (Map.Entry<String, TwillContainerController> completedEntry : lookup.entrySet()) { TwillContainerController controller = completedEntry.getValue(); instanceId = controller.getInstanceId(); // TODO: Can there be multiple controllers for a single container? // TODO: What is the best way to determine whether to restart container when there are multiple controllers? // See if the controller is stopped (this is to decide whether to retry the failed containers or not) // In case of multiple controllers, even if one is stopped we will not re-request the container containerStopped = containerStopped || isControllerStopped(controller); controller.completed(exitStatus); if (exitStatus == ContainerExitCodes.SUCCESS) { if (!completedContainerCount.containsKey(runnableName)) { completedContainerCount.put(runnableName, 0); } completedContainerCount.put(runnableName, completedContainerCount.get(runnableName) + 1); } // TODO: should we remove the completed instance from instanceId and resource report even on failures? // TODO: won't they get added back when the container is re-requested? removeInstanceId(runnableName, controller.getInstanceId()); resourceReport.removeRunnableResources(runnableName, containerId); eventHandler.containerStopped(runnableName, instanceId, containerId, exitStatus); } if (exitStatus != ContainerExitCodes.SUCCESS) { LOG.warn("Container {} exited abnormally with state {}, exit code {}.", containerId, state, exitStatus); if (!containerStopped && shouldRetry(runnableName, instanceId, exitStatus)) { LOG.info("Re-request the container {} for exit code {}.", containerId, exitStatus); restartRunnables.add(runnableName); } else if (containerStopped) { LOG.info("Container {} is being stopped, will not re-request", containerId); } } else { LOG.info("Container {} exited normally with state {}", containerId, state); } lookup.clear(); containerChange.signalAll(); } finally { containerLock.unlock(); } }
From source file:com.wasteofplastic.acidisland.commands.AdminCmd.java
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] split) { // Console commands Player player;//from w w w . j a v a 2s. c o m if (sender instanceof Player) { player = (Player) sender; if (split.length > 0) { // Admin-only commands : reload, register, delete and purge if (split[0].equalsIgnoreCase("reload") || split[0].equalsIgnoreCase("register") || split[0].equalsIgnoreCase("delete") || split[0].equalsIgnoreCase("purge") || split[0].equalsIgnoreCase("confirm") || split[0].equalsIgnoreCase("setspawn") || split[0].equalsIgnoreCase("deleteisland") || split[0].equalsIgnoreCase("setrange") || split[0].equalsIgnoreCase("unregister")) { if (!checkAdminPerms(player, split)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission); return true; } } else { // Mod commands if (!checkModPerms(player, split)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission); return true; } } } } // Check for zero parameters e.g., /asadmin switch (split.length) { case 0: help(sender, label); return true; case 1: if (Settings.teamChat && split[0].equalsIgnoreCase("spy")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; if (VaultHelper.checkPerm(player, Settings.PERMPREFIX + "mod.spy") || player.isOp()) { if (plugin.getChatListener().toggleSpy(player.getUniqueId())) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().teamChatStatusOn); } else { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().teamChatStatusOff); } return true; } } else if (split[0].equalsIgnoreCase("lock")) { // Just /asadmin lock if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; Island island = plugin.getGrid().getIslandAt(player.getLocation()); // Check if island exists if (island == null) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNotOnIsland); return true; } else { Player owner = plugin.getServer().getPlayer(island.getOwner()); if (island.isLocked()) { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockUnlocking); island.setLocked(false); if (owner != null) { owner.sendMessage(plugin.myLocale(owner.getUniqueId()).adminLockadminUnlockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminUnlockedIsland); } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockLocking); island.setLocked(true); if (owner != null) { owner.sendMessage(plugin.myLocale(owner.getUniqueId()).adminLockadminLockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminLockedIsland); } } return true; } } else // Find farms if (split[0].equalsIgnoreCase("topbreeders")) { // Go through each island and find how many farms there are sender.sendMessage(plugin.myLocale().adminTopBreedersFinding); //TreeMap<Integer, List<UUID>> topEntityIslands = new TreeMap<Integer, List<UUID>>(); // Generate the stats sender.sendMessage(plugin.myLocale().adminTopBreedersChecking.replace("[number]", String.valueOf(plugin.getGrid().getOwnershipMap().size()))); // Try just finding every entity final List<Entity> allEntities = ASkyBlock.getIslandWorld().getEntities(); final World islandWorld = ASkyBlock.getIslandWorld(); final World netherWorld = ASkyBlock.getNetherWorld(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { Map<UUID, Multiset<EntityType>> result = new HashMap<UUID, Multiset<EntityType>>(); // Find out where the entities are for (Entity entity : allEntities) { //System.out.println("DEBUG " + entity.getType().toString()); if (entity.getLocation().getWorld().equals(islandWorld) || entity.getLocation().getWorld().equals(netherWorld)) { //System.out.println("DEBUG in world"); if (entity instanceof Creature && !(entity instanceof Player)) { //System.out.println("DEBUG creature"); // Find out where it is Island island = plugin.getGrid().getIslandAt(entity.getLocation()); if (island != null && !island.isSpawn()) { //System.out.println("DEBUG on island"); // Add to result UUID owner = island.getOwner(); Multiset<EntityType> count = result.get(owner); if (count == null) { // New entry for owner //System.out.println("DEBUG new entry for owner"); count = HashMultiset.create(); } count.add(entity.getType()); result.put(owner, count); } } } } // Sort by the number of entities on each island TreeMap<Integer, List<UUID>> topEntityIslands = new TreeMap<Integer, List<UUID>>(); for (Entry<UUID, Multiset<EntityType>> entry : result.entrySet()) { int numOfEntities = entry.getValue().size(); List<UUID> players = topEntityIslands.get(numOfEntities); if (players == null) { players = new ArrayList<UUID>(); } players.add(entry.getKey()); topEntityIslands.put(numOfEntities, players); } final TreeMap<Integer, List<UUID>> topBreeders = topEntityIslands; final Map<UUID, Multiset<EntityType>> finalResult = result; // Now display results in sync thread plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { if (topBreeders.isEmpty()) { sender.sendMessage(plugin.myLocale().adminTopBreedersNothing); return; } int rank = 1; // Display, largest first for (int numOfEntities : topBreeders.descendingKeySet()) { // Only bother if there's more that 5 animals if (numOfEntities > 5) { // There can be multiple owners in the same position List<UUID> owners = topBreeders.get(numOfEntities); // Go through the owners one by one for (UUID owner : owners) { sender.sendMessage("#" + rank + " " + plugin.getPlayers().getName(owner) + " = " + numOfEntities); String content = ""; Multiset<EntityType> entityCount = finalResult.get(owner); for (EntityType entity : entityCount.elementSet()) { int num = entityCount.count(entity); String color = ChatColor.GREEN.toString(); if (num > 10 && num <= 20) { color = ChatColor.YELLOW.toString(); } else if (num > 20 && num <= 40) { color = ChatColor.GOLD.toString(); } else if (num > 40) { color = ChatColor.RED.toString(); } content += Util.prettifyText(entity.toString()) + " x " + color + num + ChatColor.WHITE + ", "; } int lastComma = content.lastIndexOf(","); // plugin.getLogger().info("DEBUG: last comma " + // lastComma); if (lastComma > 0) { content = content.substring(0, lastComma); } sender.sendMessage(" " + content); } rank++; if (rank > 10) { break; } } } // If we didn't show anything say so if (rank == 1) { sender.sendMessage(plugin.myLocale().adminTopBreedersNothing); } } }); } }); return true; } // Delete island if (split[0].equalsIgnoreCase("deleteisland")) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminDeleteIslandError); return true; } // Set spawn if (split[0].equalsIgnoreCase("setspawn")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } player = (Player) sender; // Island spawn must be in the island world if (!player.getLocation().getWorld().getName().equals(Settings.worldName)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorWrongWorld); return true; } // The island location is calculated based on the grid Location closestIsland = getClosestIsland(player.getLocation()); Island oldSpawn = plugin.getGrid().getSpawn(); Island newSpawn = plugin.getGrid().getIslandAt(closestIsland); if (newSpawn != null && newSpawn.isSpawn()) { // Already spawn, so just set the world spawn coords plugin.getGrid().setSpawnPoint(player.getLocation()); //ASkyBlock.getIslandWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetSpawnset); return true; } // Space otherwise occupied - find if anyone owns it if (newSpawn != null && newSpawn.getOwner() != null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnownedBy.replace("[name]", plugin.getPlayers().getName(newSpawn.getOwner()))); sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnmove); return true; } if (oldSpawn != null) { sender.sendMessage(ChatColor.GOLD + "Changing spawn island location. Warning: old spawn island location at " + oldSpawn.getCenter().getBlockX() + "," + oldSpawn.getCenter().getBlockZ() + " will be at risk of being overwritten with new islands. Recommend to clear that old area."); plugin.getGrid().deleteSpawn(); } // New spawn site is free, so make it official if (newSpawn == null) { // Make the new spawn newSpawn = plugin.getGrid().addIsland(closestIsland.getBlockX(), closestIsland.getBlockZ()); } plugin.getGrid().setSpawn(newSpawn); plugin.getGrid().setSpawnPoint(player.getLocation()); //ASkyBlock.getIslandWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); player.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetSpawnsetting.replace("[location]", player.getLocation().getBlockX() + "," + player.getLocation().getBlockZ())); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawncenter.replace("[location]", newSpawn.getCenter().getBlockX() + "," + newSpawn.getCenter().getBlockZ())); player.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawnlimits.replace("[min]", newSpawn.getMinX() + "," + newSpawn.getMinZ())).replace("[max]", (newSpawn.getMinX() + newSpawn.getIslandDistance() - 1) + "," + (newSpawn.getMinZ() + newSpawn.getIslandDistance() - 1))); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnrange.replace("[number]", String.valueOf(newSpawn.getProtectionSize()))); player.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawncoords.replace("[min]", newSpawn.getMinProtectedX() + ", " + newSpawn.getMinProtectedZ())).replace("[max]", +(newSpawn.getMinProtectedX() + newSpawn.getProtectionSize() - 1) + ", " + (newSpawn.getMinProtectedZ() + newSpawn.getProtectionSize() - 1))); if (newSpawn.isLocked()) { player.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnlocked); } return true; } else if (split[0].equalsIgnoreCase("info") || split[0].equalsIgnoreCase("setrange")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } Location closestIsland = getClosestIsland(((Player) sender).getLocation()); if (closestIsland == null) { sender.sendMessage(ChatColor.RED + "Sorry, could not find an island. Move closer?"); return true; } Island island = plugin.getGrid().getIslandAt(closestIsland); if (island != null && island.isSpawn()) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminInfotitle); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawncenter.replace( "[location]", island.getCenter().getBlockX() + "," + island.getCenter().getBlockZ())); sender.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawnlimits.replace("[min]", island.getMinX() + "," + island.getMinZ())).replace("[max]", (island.getMinX() + island.getIslandDistance() - 1) + "," + (island.getMinZ() + island.getIslandDistance() - 1))); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnrange.replace("[number]", String.valueOf(island.getProtectionSize()))); sender.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawncoords.replace("[min]", island.getMinProtectedX() + ", " + island.getMinProtectedZ())).replace("[max]", +(island.getMinProtectedX() + island.getProtectionSize() - 1) + ", " + (island.getMinProtectedZ() + island.getProtectionSize() - 1))); if (island.isLocked()) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnlocked); } return true; } if (island == null) { plugin.getLogger().info("Get island at was null" + closestIsland); } UUID target = plugin.getPlayers().getPlayerFromIslandLocation(closestIsland); if (target == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminInfounowned); return true; } showInfo(target, sender); return true; } else if (split[0].equalsIgnoreCase("resetsign")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } player = (Player) sender; if (!VaultHelper.checkPerm(player, Settings.PERMPREFIX + "mod.signadmin") && !player.isOp()) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission); return true; } // Find out whether the player is looking at a warp sign // Look at what the player was looking at BlockIterator iter = new BlockIterator(player, 10); Block lastBlock = iter.next(); while (iter.hasNext()) { lastBlock = iter.next(); if (lastBlock.getType() == Material.AIR) continue; break; } if (!lastBlock.getType().equals(Material.SIGN_POST)) { sender.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminResetSignNoSign); return true; } // Check if it is a warp sign Sign sign = (Sign) lastBlock.getState(); sender.sendMessage(ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).adminResetSignFound); // Find out whose island this is // plugin.getLogger().info("DEBUG: closest bedrock: " + // closestBedRock.toString()); UUID target = plugin.getPlayers().getPlayerFromIslandLocation(player.getLocation()); if (target == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminInfounowned); return true; } if (plugin.getWarpSignsListener().addWarp(target, lastBlock.getLocation())) { // Change sign color to green sign.setLine(0, ChatColor.GREEN + plugin.myLocale().warpswelcomeLine); sign.update(); sender.sendMessage(ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).adminResetSignRescued .replace("[name]", plugin.getPlayers().getName(target))); return true; } // Warp already exists sender.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminResetSignErrorExists .replace("[name]", plugin.getWarpSignsListener().getWarpOwner(lastBlock.getLocation()))); return true; } else if (split[0].equalsIgnoreCase("reload")) { plugin.reloadConfig(); plugin.loadPluginConfig(); plugin.getChallenges().reloadChallengeConfig(); if (Settings.useEconomy && VaultHelper.setupEconomy()) { ControlPanel.loadShop(); } else { Settings.useEconomy = false; } ControlPanel.loadControlPanel(); if (Settings.updateCheck) { plugin.checkUpdates(); } else { plugin.setUpdateCheck(null); } plugin.getIslandCmd().loadSchematics(); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().reloadconfigReloaded); return true; } else if (split[0].equalsIgnoreCase("topten")) { sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminTopTengenerating); TopTen.topTenCreate(sender); return true; } else if (split[0].equalsIgnoreCase("purge")) { if (purgeFlag) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgealreadyRunning); return true; } sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgeusage.replace("[label]", label)); return true; } else if (split[0].equalsIgnoreCase("confirm")) { if (!confirmReq) { sender.sendMessage(ChatColor.RED + plugin.myLocale().confirmerrorTimeLimitExpired); return true; } else { // Tell purge routine to go confirmOK = true; confirmReq = false; } return true; } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return false; } case 2: // Resetsign <player> - makes a warp sign for player if (split[0].equalsIgnoreCase("resetsign")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } Player p = (Player) sender; if (!VaultHelper.checkPerm(p, Settings.PERMPREFIX + "mod.signadmin") && !p.isOp()) { p.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).errorNoPermission); return true; } // Convert target name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID) && !plugin.getPlayers().inTeam(playerUUID)) { // No island sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Has an island // Find out whether the player is looking at a warp sign // Look at what the player was looking at BlockIterator iter = new BlockIterator(p, 10); Block lastBlock = iter.next(); while (iter.hasNext()) { lastBlock = iter.next(); if (lastBlock.getType() == Material.AIR) continue; break; } // Check if it is a sign if (!lastBlock.getType().equals(Material.SIGN_POST)) { sender.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).adminResetSignNoSign); return true; } Sign sign = (Sign) lastBlock.getState(); // Check if the sign is within the right island boundary Location islandLoc = plugin.getPlayers().getIslandLocation(playerUUID); if (!plugin.getGrid().getIslandAt(islandLoc).inIslandSpace(sign.getLocation())) { p.sendMessage( ChatColor.RED + plugin.myLocale(p.getUniqueId()).adminSetHomeNotOnPlayersIsland); } else { sender.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminResetSignFound); // Find out if this player is allowed to have a sign on this island if (plugin.getWarpSignsListener().addWarp(playerUUID, lastBlock.getLocation())) { // Change sign color to green sign.setLine(0, ChatColor.GREEN + plugin.myLocale().warpswelcomeLine); sign.update(); p.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminResetSignRescued .replace("[name]", plugin.getPlayers().getName(playerUUID))); return true; } // Warp already exists sender.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).adminResetSignErrorExists.replace("[name]", plugin.getWarpSignsListener().getWarpOwner(lastBlock.getLocation()))); } } return true; } // Delete the island you are on else if (split[0].equalsIgnoreCase("deleteisland")) { if (!split[1].equalsIgnoreCase("confirm")) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminDeleteIslandError); return true; } // Get the island I am on Island island = plugin.getGrid().getIslandAt(((Player) sender).getLocation()); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminDeleteIslandnoid); return true; } // Try to get the owner of this island UUID owner = island.getOwner(); String name = "unknown"; if (owner != null) { name = plugin.getPlayers().getName(owner); sender.sendMessage( ChatColor.RED + plugin.myLocale().adminSetSpawnownedBy.replace("[name]", name)); sender.sendMessage( ChatColor.RED + plugin.myLocale().adminDeleteIslanduse.replace("[name]", name)); return true; } else { sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().deleteremoving.replace("[name]", name)); deleteIslands(island, sender); return true; } } else if (split[0].equalsIgnoreCase("resethome")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID) && !plugin.getPlayers().inTeam(playerUUID)) { // No island sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Has an island Location safeHome = plugin.getGrid().getSafeHomeLocation(playerUUID, 1); if (safeHome == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetHomeNoneFound); } else { plugin.getPlayers().setHomeLocation(playerUUID, safeHome); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetHomeHomeSet.replace( "[location]", safeHome.getBlockX() + ", " + safeHome.getBlockY() + "," + safeHome.getBlockZ())); } } return true; } else if (split[0].equalsIgnoreCase("sethome")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID) && !plugin.getPlayers().inTeam(playerUUID)) { // No island player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoIslandOther); return true; } // Has an island Location islandLoc = plugin.getPlayers().getIslandLocation(playerUUID); // Check the player is within the island boundaries if (!plugin.getGrid().getIslandAt(islandLoc).inIslandSpace(player.getLocation())) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminSetHomeNotOnPlayersIsland); } else { // Check that the location is safe if (!GridManager.isSafeLocation(player.getLocation())) { // Not safe player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminSetHomeNoneFound); } else { // Success plugin.getPlayers().setHomeLocation(playerUUID, player.getLocation()); player.sendMessage( ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).adminSetHomeHomeSet .replace("[location]", player.getLocation().getBlockX() + ", " + player.getLocation().getBlockY() + "," + player.getLocation().getBlockZ())); } } } return true; } else // Set protection for the island the player is on if (split[0].equalsIgnoreCase("setrange")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; UUID playerUUID = player.getUniqueId(); Island island = plugin.getGrid().getIslandAt(player.getLocation()); // Check if island exists if (island == null) { player.sendMessage(ChatColor.RED + plugin.myLocale().errorNotOnIsland); return true; } else { int newRange = 10; int maxRange = Settings.islandDistance; // If spawn do something different if (island.isSpawn()) { try { newRange = Integer.valueOf(split[1]); } catch (Exception e) { player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeInvalid); return true; } player.sendMessage(ChatColor.GREEN + plugin.myLocale(playerUUID).adminSetRangeSet .replace("[number]", String.valueOf(newRange))); if (newRange > maxRange) { player.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + plugin.myLocale(playerUUID).adminSetRangeWarning.replace("[max]", String.valueOf(maxRange))); player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeWarning2); } island.setProtectionSize(newRange); player.sendMessage( ChatColor.YELLOW + plugin.myLocale().adminSetSpawncenter.replace("[location]", island.getCenter().getBlockX() + "," + island.getCenter().getBlockZ())); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnlimits .replace("[min]", island.getMinX() + "," + island.getMinZ()) .replace("[max]", (island.getMinX() + island.getIslandDistance() - 1) + "," + (island.getMinZ() + island.getIslandDistance() - 1))); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnrange .replace("[number]", String.valueOf(island.getProtectionSize()))); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawncoords .replace("[min]", island.getMinProtectedX() + ", " + island.getMinProtectedZ()) .replace("[max]", +(island.getMinProtectedX() + island.getProtectionSize() - 1) + ", " + (island.getMinProtectedZ() + island.getProtectionSize() - 1))); if (island.isLocked()) { player.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnlocked); } } else { if (!plugin.getConfig().getBoolean("island.overridelimit")) { maxRange -= 16; } try { newRange = Integer.valueOf(split[1]); } catch (Exception e) { player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeInvalid + " " + plugin.myLocale(playerUUID).adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } if (newRange < 10 || newRange > maxRange) { player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeInvalid + " " + plugin.myLocale(playerUUID).adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } island.setProtectionSize(newRange); player.sendMessage(ChatColor.GREEN + plugin.myLocale(playerUUID).adminSetRangeSet .replace("[number]", String.valueOf(newRange))); showInfo(island.getOwner(), sender); } return true; } } if (split[0].equalsIgnoreCase("purge")) { // PURGE Command // Check for "allow" or "disallow" flags // Protect island from purging if (split[1].equalsIgnoreCase("allow") || split[1].equalsIgnoreCase("disallow")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } Player p = (Player) sender; // Island spawn must be in the island world if (!p.getLocation().getWorld().equals(ASkyBlock.getIslandWorld()) && !p.getLocation().getWorld().equals(ASkyBlock.getNetherWorld())) { p.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).errorWrongWorld); return true; } Island island = plugin.getGrid().getIslandAt(p.getLocation()); if (island == null) { p.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).errorNoIslandOther); return true; } if (split[1].equalsIgnoreCase("allow")) { island.setPurgeProtected(true); } else { island.setPurgeProtected(false); } if (island.isPurgeProtected()) { p.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminAllowPurge); } else { p.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminPreventPurge); } return true; } // Purge runs in the background so if one is already running // this flag stops a repeat if (purgeFlag) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgealreadyRunning); return true; } if (split[1].equalsIgnoreCase("unowned")) { countUnowned(sender); return true; } // Set the flag purgeFlag = true; // See if this purge unowned // Convert days to hours - no other limit checking? final int time; try { time = Integer.parseInt(split[1]) * 24; } catch (Exception e) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgeusage.replace("[label]", label)); purgeFlag = false; return true; } sender.sendMessage( ChatColor.YELLOW + plugin.myLocale().purgecalculating.replace("[time]", split[1])); // Check who has not been online since the time for (Entry<UUID, Island> entry : plugin.getGrid().getOwnershipMap().entrySet()) { //plugin.getLogger().info("UUID = " + entry.getKey()); // Only do this if it isn't protected if (entry.getKey() != null && !entry.getValue().isPurgeProtected()) { if (Bukkit.getOfflinePlayer(entry.getKey()).hasPlayedBefore()) { long offlineTime = Bukkit.getOfflinePlayer(entry.getKey()).getLastPlayed(); offlineTime = (System.currentTimeMillis() - offlineTime) / 3600000L; if (offlineTime > time) { //if (plugin.getPlayers().getIslandLevel(entry.getKey()) < Settings.abandonedIslandLevel) { // Check level later removeList.add(entry.getKey()); //} } } else { removeList.add(entry.getKey()); } } } if (removeList.isEmpty()) { sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgenoneFound); purgeFlag = false; return true; } sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgethisWillRemove .replace("[number]", String.valueOf(removeList.size())) .replace("[level]", String.valueOf(Settings.abandonedIslandLevel))); sender.sendMessage(ChatColor.RED + plugin.myLocale().purgewarning); sender.sendMessage(ChatColor.RED + plugin.myLocale().purgetypeConfirm.replace("[label]", label)); confirmReq = true; confirmOK = false; confirmTimer = 0; new BukkitRunnable() { @Override public void run() { // This waits for 10 seconds and if no // confirmation received, then it // cancels if (confirmTimer++ > 10) { // Ten seconds is up! confirmReq = false; confirmOK = false; purgeFlag = false; removeList.clear(); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgepurgeCancelled); this.cancel(); } else if (confirmOK) { // Set up a repeating task to run every 2 // seconds to remove // islands one by one and then cancel when // done final int total = removeList.size(); new BukkitRunnable() { @Override public void run() { if (removeList.isEmpty() && purgeFlag) { purgeFlag = false; sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgefinished); this.cancel(); } if (removeList.size() > 0 && purgeFlag) { // Check the level if (plugin.getPlayers().getIslandLevel( removeList.get(0)) < Settings.abandonedIslandLevel) { sender.sendMessage(ChatColor.YELLOW + "[" + (total - removeList.size() + 1) + "/" + total + "] " + plugin.myLocale().purgeremovingName.replace("[name]", plugin.getPlayers().getName(removeList.get(0)))); plugin.deletePlayerIsland(removeList.get(0), true); } removeList.remove(0); } //sender.sendMessage("Now waiting..."); } }.runTaskTimer(plugin, 0L, 20L); confirmReq = false; confirmOK = false; this.cancel(); } } }.runTaskTimer(plugin, 0L, 40L); return true; } else if (split[0].equalsIgnoreCase("lock")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { Island island = plugin.getGrid().getIsland(playerUUID); if (island != null) { Player owner = plugin.getServer().getPlayer(island.getOwner()); if (island.isLocked()) { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockUnlocking); island.setLocked(false); if (owner != null) { owner.sendMessage( plugin.myLocale(owner.getUniqueId()).adminLockadminUnlockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminUnlockedIsland); } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockLocking); island.setLocked(true); if (owner != null) { owner.sendMessage(plugin.myLocale(owner.getUniqueId()).adminLockadminLockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminLockedIsland); } } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); } return true; } } else if (split[0].equalsIgnoreCase("clearreset")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { plugin.getPlayers().setResetsLeft(playerUUID, Settings.resetLimit); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().clearedResetLimit + " [" + Settings.resetLimit + "]"); return true; } } else if (split[0].equalsIgnoreCase("tp")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return true; } player = (Player) sender; // Convert name to a UUID final UUID targetUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(targetUUID)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorUnknownPlayer); return true; } else { if (plugin.getPlayers().hasIsland(targetUUID) || plugin.getPlayers().inTeam(targetUUID)) { // Teleport to the over world Location warpSpot = plugin.getPlayers().getIslandLocation(targetUUID).toVector() .toLocation(ASkyBlock.getIslandWorld()); String failureMessage = ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminTpManualWarp.replace("[location]", warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " " + warpSpot.getBlockZ()); // Try the player's home first Location home = plugin.getPlayers().getHomeLocation(targetUUID); plugin.getGrid(); if (home.getWorld().equals(ASkyBlock.getIslandWorld()) && GridManager.isSafeLocation(home)) { player.teleport(home); return true; } // Other wise, go to a safe spot new SafeSpotTeleport(plugin, player, warpSpot, failureMessage); return true; } sender.sendMessage(plugin.myLocale().errorNoIslandOther); return true; } } else if (split[0].equalsIgnoreCase("tpnether")) { if (!Settings.createNether || !Settings.newNether) { return false; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return true; } player = (Player) sender; // Convert name to a UUID final UUID targetUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(targetUUID)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorUnknownPlayer); return true; } else { if (plugin.getPlayers().hasIsland(targetUUID) || plugin.getPlayers().inTeam(targetUUID)) { // Teleport to the nether Location warpSpot = plugin.getPlayers().getIslandLocation(targetUUID).toVector() .toLocation(ASkyBlock.getNetherWorld()); String failureMessage = ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminTpManualWarp.replace("[location]", warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " " + warpSpot.getBlockZ()); // Try the player's home first Location home = plugin.getPlayers().getHomeLocation(targetUUID); plugin.getGrid(); if (home.getWorld().equals(ASkyBlock.getNetherWorld()) && GridManager.isSafeLocation(home)) { player.teleport(home); return true; } new SafeSpotTeleport(plugin, player, warpSpot, failureMessage); return true; } sender.sendMessage(plugin.myLocale().errorNoIslandOther); return true; } } else if (split[0].equalsIgnoreCase("delete")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { // This now deletes the player and cleans them up even if // they don't have an island sender.sendMessage( ChatColor.YELLOW + plugin.myLocale().deleteremoving.replace("[name]", split[1])); // If they are online and in ASkyBlock then delete their // stuff too Player target = plugin.getServer().getPlayer(playerUUID); if (target != null) { // Clear any coop inventories // CoopPlay.getInstance().returnAllInventories(target); // Remove any of the target's coop invitees and grab // their stuff CoopPlay.getInstance().clearMyInvitedCoops(target); CoopPlay.getInstance().clearMyCoops(target); plugin.resetPlayer(target); } // plugin.getLogger().info("DEBUG: deleting player"); plugin.deletePlayerIsland(playerUUID, true); return true; } } else if (split[0].equalsIgnoreCase("register")) { if (sender instanceof Player) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { if (adminSetPlayerIsland(sender, ((Player) sender).getLocation(), playerUUID)) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().registersettingIsland.replace("[name]", split[1])); plugin.getGrid().saveGrid(); } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().registererrorBedrockNotFound); } return true; } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); } return true; } else if (split[0].equalsIgnoreCase("unregister")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { if (plugin.getPlayers().inTeam(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminUnregisterOnTeam); return true; } Location island = plugin.getPlayers().getIslandLocation(playerUUID); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Delete player, but keep blocks sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminUnregisterKeepBlocks .replace("[location]", +plugin.getPlayers().getIslandLocation(playerUUID).getBlockX() + "," + plugin.getPlayers().getIslandLocation(playerUUID).getBlockZ())); plugin.deletePlayerIsland(playerUUID, false); plugin.getGrid().saveGrid(); return true; } } else if (split[0].equalsIgnoreCase("info")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); // plugin.getLogger().info("DEBUG: console player info UUID = " // + playerUUID); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { showInfo(playerUUID, sender); return true; } } else if (split[0].equalsIgnoreCase("resetallchallenges")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } plugin.getPlayers().resetAllChallenges(playerUUID); sender.sendMessage( ChatColor.YELLOW + plugin.myLocale().resetChallengessuccess.replace("[name]", split[1])); return true; } else { return false; } case 3: // Confirm purge unowned if (split[0].equalsIgnoreCase("purge")) { if (purgeFlag) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgealreadyRunning); return true; } // Check if this is purge unowned if (split[1].equalsIgnoreCase("unowned") && split[2].equalsIgnoreCase("confirm")) { if (!purgeUnownedConfirm) { sender.sendMessage(ChatColor.RED + plugin.myLocale().confirmerrorTimeLimitExpired); return true; } else { purgeUnownedConfirm = false; // Purge the unowned islands purgeUnownedIslands(sender); return true; } } } // Set protection if (split[0].equalsIgnoreCase("setrange")) { // Convert name to a UUID UUID playerUUID = plugin.getPlayers().getUUID(split[1]); // Check if player exists if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } // Check if the target is in a team and if so, the leader needs to be adjusted if (plugin.getPlayers().inTeam(playerUUID)) { playerUUID = plugin.getPlayers().getTeamLeader(playerUUID); } // Get the range that this player has now Island island = plugin.getGrid().getIsland(playerUUID); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } else { int newRange = 0; int maxRange = Settings.islandDistance; if (!plugin.getConfig().getBoolean("island.overridelimit")) { maxRange -= 16; } try { newRange = Integer.valueOf(split[2]); } catch (Exception e) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetRangeInvalid + " " + plugin.myLocale().adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } if (newRange < 10 || newRange > maxRange) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetRangeInvalid + " " + plugin.myLocale().adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } island.setProtectionSize(newRange); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetRangeSet.replace("[number]", String.valueOf(newRange))); showInfo(playerUUID, sender); plugin.getGrid().saveGrid(); return true; } } // Change biomes if (split[0].equalsIgnoreCase("setbiome")) { // Convert name to a UUID UUID playerUUID = plugin.getPlayers().getUUID(split[1]); // Check if player exists if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } // Check if the target is in a team and if so, the leader if (plugin.getPlayers().inTeam(playerUUID)) { playerUUID = plugin.getPlayers().getTeamLeader(playerUUID); } // Check if biome is valid Biome biome = null; String biomeName = split[2].toUpperCase(); try { biome = Biome.valueOf(biomeName); biomeName = biome.name(); if (!plugin.getConfig().contains("biomes." + biomeName)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().biomeUnknown); // Doing it this way ensures that only valid biomes are // shown for (Biome b : Biome.values()) { if (plugin.getConfig().contains("biomes." + b.name())) { sender.sendMessage(b.name()); } } return true; } // Get friendly name biomeName = plugin.getConfig().getString("biomes." + biomeName + ".friendlyname", Util.prettifyText(biomeName)); } catch (Exception e) { sender.sendMessage(ChatColor.RED + plugin.myLocale().biomeUnknown); for (Biome b : Biome.values()) { if (plugin.getConfig().contains("biomes." + b.name())) { sender.sendMessage(b.name()); } } return true; } // Okay clear to set biome // Actually set the biome if (plugin.getPlayers().inTeam(playerUUID) && plugin.getPlayers().getTeamIslandLocation(playerUUID) != null) { plugin.getBiomes().setIslandBiome(plugin.getPlayers().getTeamIslandLocation(playerUUID), biome); } else { plugin.getBiomes().setIslandBiome(plugin.getPlayers().getIslandLocation(playerUUID), biome); } sender.sendMessage(ChatColor.GREEN + plugin.myLocale().biomeSet.replace("[biome]", biomeName)); Player targetPlayer = plugin.getServer().getPlayer(playerUUID); if (targetPlayer != null) { // Online targetPlayer.sendMessage("[Admin] " + ChatColor.GREEN + plugin.myLocale(playerUUID).biomeSet.replace("[biome]", biomeName)); } else { plugin.getMessages().setMessage(playerUUID, "[Admin] " + ChatColor.GREEN + plugin.myLocale(playerUUID).biomeSet.replace("[biome]", biomeName)); } return true; } else // team kick <player> and team delete <leader> if (split[0].equalsIgnoreCase("team")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[2]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (split[1].equalsIgnoreCase("kick")) { // Remove player from team if (!plugin.getPlayers().inTeam(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoTeam); return true; } UUID teamLeader = plugin.getPlayers().getTeamLeader(playerUUID); if (teamLeader == null) { // Player is apparently in a team, but there is no team leader // Remove their team status // Clear the player of all team-related items plugin.getPlayers().setLeaveTeam(playerUUID); plugin.getPlayers().setHomeLocation(playerUUID, null); plugin.getPlayers().setIslandLocation(playerUUID, null); // Remove any warps plugin.getWarpSignsListener().removeWarp(playerUUID); sender.sendMessage( ChatColor.RED + plugin.myLocale().kicknameRemoved.replace("[name]", split[2])); return true; } // Payer is not a team leader if (!teamLeader.equals(playerUUID)) { // Clear the player of all team-related items plugin.getPlayers().setLeaveTeam(playerUUID); plugin.getPlayers().setHomeLocation(playerUUID, null); plugin.getPlayers().setIslandLocation(playerUUID, null); // Clear the leader of this player and if they now have // no team, remove the team plugin.getPlayers().removeMember(teamLeader, playerUUID); if (plugin.getPlayers().getMembers(teamLeader).size() < 2) { plugin.getPlayers().setLeaveTeam(teamLeader); } // Remove any warps plugin.getWarpSignsListener().removeWarp(playerUUID); sender.sendMessage( ChatColor.RED + plugin.myLocale().kicknameRemoved.replace("[name]", split[2])); return true; } else { sender.sendMessage( ChatColor.RED + (plugin.myLocale().adminTeamKickLeader.replace("[label]", label)) .replace("[name]", split[2])); return true; } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return false; } } else if (split[0].equalsIgnoreCase("completechallenge")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[2]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (plugin.getPlayers().checkChallenge(playerUUID, split[1].toLowerCase()) || !plugin.getPlayers().get(playerUUID).challengeExists(split[1].toLowerCase())) { sender.sendMessage( ChatColor.RED + plugin.myLocale().completeChallengeerrorChallengeDoesNotExist); return true; } plugin.getPlayers().get(playerUUID).completeChallenge(split[1].toLowerCase()); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().completeChallengechallangeCompleted .replace("[challengename]", split[1].toLowerCase()).replace("[name]", split[2])); return true; } else if (split[0].equalsIgnoreCase("resetchallenge")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[2]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (!plugin.getPlayers().checkChallenge(playerUUID, split[1].toLowerCase()) || !plugin.getPlayers().get(playerUUID).challengeExists(split[1].toLowerCase())) { sender.sendMessage(ChatColor.RED + plugin.myLocale().resetChallengeerrorChallengeDoesNotExist); return true; } plugin.getPlayers().resetChallenge(playerUUID, split[1].toLowerCase()); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().resetChallengechallengeReset .replace("[challengename]", split[1].toLowerCase()).replace("[name]", split[2])); return true; } else if (split[0].equalsIgnoreCase("info") && split[1].equalsIgnoreCase("challenges")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[2]); // plugin.getLogger().info("DEBUG: console player info UUID = " // + playerUUID); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { showInfoChallenges(playerUUID, sender); return true; } } return false; case 4: // Team add <player> <leader> if (split[0].equalsIgnoreCase("team") && split[1].equalsIgnoreCase("add")) { // Convert names to UUIDs final UUID playerUUID = plugin.getPlayers().getUUID(split[2]); final Player targetPlayer = plugin.getServer().getPlayer(playerUUID); final UUID teamLeader = plugin.getPlayers().getUUID(split[3]); if (!plugin.getPlayers().isAKnownPlayer(playerUUID) || !plugin.getPlayers().isAKnownPlayer(teamLeader)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (playerUUID.equals(teamLeader)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminTeamAddLeaderToOwn); return true; } // See if leader has an island if (!plugin.getPlayers().hasIsland(teamLeader)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminTeamAddLeaderNoIsland); return true; } // Check to see if this player is already in a team if (plugin.getPlayers().inTeam(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().inviteerrorThatPlayerIsAlreadyInATeam); return true; } // If the leader's member list does not contain their own name // then // add it if (!plugin.getPlayers().getMembers(teamLeader).contains(teamLeader)) { // Set up the team leader plugin.getPlayers().setJoinTeam(teamLeader, teamLeader, plugin.getPlayers().getIslandLocation(teamLeader)); plugin.getPlayers().addTeamMember(teamLeader, teamLeader); sender.sendMessage(ChatColor.GOLD + plugin.myLocale().adminTeamAddedLeader); } // This is a hack to clear any pending invitations if (targetPlayer != null) { targetPlayer.performCommand(Settings.ISLANDCOMMAND + " decline"); } // If the invitee has an island of their own if (plugin.getPlayers().hasIsland(playerUUID)) { Location islandLoc = plugin.getPlayers().getIslandLocation(playerUUID); if (islandLoc != null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminTeamNowUnowned .replace("[name]", plugin.getPlayers().getName(playerUUID)) .replace("[location]", islandLoc.getBlockX() + " " + islandLoc.getBlockZ())); } } // Remove their old island affiliation - do not delete the // island just in case plugin.deletePlayerIsland(playerUUID, false); // Join the team and set the team island location and leader plugin.getPlayers().setJoinTeam(playerUUID, teamLeader, plugin.getPlayers().getIslandLocation(teamLeader)); // Configure the best home location for this player if (plugin.getPlayers().getHomeLocation(teamLeader) != null) { plugin.getPlayers().setHomeLocation(playerUUID, plugin.getPlayers().getHomeLocation(teamLeader)); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminTeamSettingHome); } else { plugin.getPlayers().setHomeLocation(playerUUID, plugin.getPlayers().getIslandLocation(teamLeader)); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminTeamSettingHome); } // If the leader's member list does not contain player then add // it if (!plugin.getPlayers().getMembers(teamLeader).contains(playerUUID)) { plugin.getPlayers().addTeamMember(teamLeader, playerUUID); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminTeamAddingPlayer); } else { sender.sendMessage(ChatColor.GOLD + plugin.myLocale().adminTeamAlreadyOnTeam); } // Teleport the player if they are online if (targetPlayer != null) { plugin.getGrid().homeTeleport(targetPlayer); } plugin.getGrid().saveGrid(); return true; } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return false; } default: return false; } }
From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.MotionModelImpl.java
@Override public Multiset<Particle> move(Multiset<Particle> particles, double timestamp, double timeElapsed, Observation obs, boolean previouslyResampled) throws ParticleFilterException { final Multiset<Particle> results = HashMultiset.create(); boolean anySnapped = false; /*// www .ja v a 2s .c o m * TODO FIXME could keep a particle-set-info record... */ for (final Multiset.Entry<Particle> parent : particles.entrySet()) { final VehicleState state = parent.getElement().getData(); if (state.getBlockStateObservation() != null && state.getBlockStateObservation().isSnapped()) { anySnapped = true; break; } } final double ess = ParticleFilter.getEffectiveSampleSize(particles); final boolean generalBlockTransition = allowGeneralBlockTransition(obs, ess, previouslyResampled, anySnapped); double normOffset = Double.NEGATIVE_INFINITY; for (final Multiset.Entry<Particle> parent : particles.entrySet()) { final VehicleState parentState = parent.getElement().getData(); final BlockStateObservation parentBlockStateObs = parentState.getBlockStateObservation(); final Set<BlockStateObservation> transitions = Sets.newHashSet(); if (generalBlockTransition || allowParentBlockTransition(parentState, obs)) { /* * These are all the snapped and DSC/run blocks */ transitions.addAll(_blocksFromObservationService.determinePotentialBlockStatesForObservation(obs)); } else if (parentBlockStateObs != null) { /* * Only the snapped blocks. * We are also allowing changes to snapped in-progress states when * they were sampled well outside of allowed backward search distance. */ final double backwardDistance = Double.NEGATIVE_INFINITY; transitions.addAll(_blocksFromObservationService.advanceState(obs, parentState.getBlockState(), backwardDistance, Double.POSITIVE_INFINITY)); } BlockStateObservation newParentBlockStateObs; if (parentBlockStateObs != null) { newParentBlockStateObs = _blocksFromObservationService.getBlockStateObservationFromDist(obs, parentBlockStateObs.getBlockState().getBlockInstance(), parentBlockStateObs.getBlockState().getBlockLocation().getDistanceAlongBlock()); } else { newParentBlockStateObs = null; } transitions.add(newParentBlockStateObs); /* * We make a subtle distinction here, by allowing the previous state to * remain as a transition but unaltered. This helps in cases of * deadhead->in-progress transitions, since, later on, the block state we * create in the following will be treated differently, signaled by way of * pointer equality. */ final double vehicleHasNotMovedProb = MovedLikelihood.computeVehicleHasNotMovedProbability(obs); for (int i = 0; i < parent.getCount(); ++i) { final Particle sampledParticle = sampleTransitionParticle(parent, newParentBlockStateObs, obs, vehicleHasNotMovedProb, transitions); normOffset = LogMath.add(sampledParticle.getLogWeight(), normOffset); results.add(sampledParticle); } } /* * Normalize */ for (final Entry<Particle> p : results.entrySet()) { final double thisTotalWeight = p.getElement().getLogWeight() + FastMath.log(p.getCount()); double logNormed = thisTotalWeight - normOffset; if (logNormed > 0d) logNormed = 0d; p.getElement().setLogNormedWeight(logNormed); } return results; }
From source file:org.apache.hadoop.mapred.NetCDFInputFormatPrunerByFileIndexMultiFileTwoDimensions.java
@Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { FileStatus[] files = listStatus(job); LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher")); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher")); /* Analyzing Query here */ String hiveQuery = job.get(HIVE_QUERY, "Kossher"); QueryType queryType = QueryType.NOLIMIT; // default mode /*//from w w w.j a va 2 s . c o m if(hiveQuery.contains("where") || hiveQuery.contains("WHERE")) { if (hiveQuery.contains("time") || hiveQuery.contains("TIME")) { queryType = QueryType.TIME; } else if (hiveQuery.contains("lat") || hiveQuery.contains("LAT")) { queryType = QueryType.LAT; } else if (hiveQuery.contains("lon") || hiveQuery.contains("LON")) { queryType = QueryType.LON; } } */ float latTopLimit = -1; float latBottomLimit = -1; float lonTopLimit = -1; float lonBottomLimit = -1; String[] querySplitted = hiveQuery.split(" "); for (int i = 0; i < querySplitted.length; i++) { if (querySplitted[i].equals("lat") || querySplitted[i].equals("LAT")) { if (querySplitted[i + 1].equals(">")) { latBottomLimit = Float.valueOf(querySplitted[i + 2]); } else if (querySplitted[i + 1].equals("<")) { latTopLimit = Float.valueOf(querySplitted[i + 2]); } } if (querySplitted[i].equals("lon") || querySplitted[i].equals("LON")) { if (querySplitted[i + 1].equals(">")) { lonBottomLimit = Float.valueOf(querySplitted[i + 2]); } else if (querySplitted[i + 1].equals("<")) { lonTopLimit = Float.valueOf(querySplitted[i + 2]); } } } System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] " + "latTopLimit=" + latTopLimit + ",latBottomLimit=" + latBottomLimit + ",lonTopLimit=" + lonTopLimit + ",lonBottomLimit=" + lonBottomLimit); System.out.println("[SAMANPruner] beginning of getSplits"); job.setLong(NUM_INPUT_FILES, files.length); long totalSize = 0; // compute total size for (FileStatus file : files) { // check we have valid files if (file.isDir()) { throw new IOException("Not a file: " + file.getPath()); } totalSize += file.getLen(); } // generate splits ArrayList<NetCDFFileSplit> splits = new ArrayList<NetCDFFileSplit>(numSplits); ArrayList<NetCDFFileSplit> finalSplits = new ArrayList<NetCDFFileSplit>(); NetworkTopology clusterMap = new NetworkTopology(); for (FileStatus file : files) { Path path = file.getPath(); int fileIndex = 0; int dimIndex = 0; String[] parts = path.getName().split("-"); dimIndex = Integer.valueOf(parts[1]); //LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] File name is : " + path.getName()); System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] File name is : " + path.getName()); FileSystem fs = path.getFileSystem(job); long length = file.getLen(); BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0, length); if ((length != 0) && isSplitable(fs, path)) { long blockSize = file.getBlockSize(); netInfo = getNetCDFInfo(path, fs, job); // First decide which which files should be considered as the base to be read int latTopTemp = -1; if (latTopLimit == -1) { latTopTemp = result.latLength; } else { latTopTemp = Math.min(result.latLength, (int) latTopLimit); } int latBottomTemp = -1; if (latBottomLimit == -1) { latBottomTemp = 0; } else { latBottomTemp = Math.max(0, (int) latBottomLimit); } int lonTopTemp = -1; if (lonTopLimit == -1) { lonTopTemp = result.lonLength; } else { lonTopTemp = Math.min(result.lonLength, (int) lonTopLimit); } int lonBottomTemp = -1; if (lonBottomLimit == -1) { lonBottomTemp = 0; } else { lonBottomTemp = Math.min(0, (int) lonBottomLimit); } if ((latTopTemp - latBottomTemp) * 4 * result.lonLength * result.timeLength < (lonTopTemp - lonBottomTemp) * 4 * result.latLength * result.timeLength) { chooseLat = true; } else { chooseLat = false; } System.out.println("[SAMAN][NetCDFInputFormat][getSplits] chooseLat = " + chooseLat); if (chooseLat) { if (!path.getName().contains("lat")) continue; } else { if (!path.getName().contains("lon")) continue; } long recStart = netInfo.recStart; long[] chunkStarts = netInfo.chunkStarts; long smallSize = netInfo.smallRecSize; long recSize = netInfo.recSize; long splitSize = 0; int chunkIndex = 0; long bytesRemaining = chunkStarts[chunkStarts.length - 1] + recSize - recStart - 2 * smallSize; long thisStart = recStart; // file position long thisChunk = 0; long blockNo = 1; while (bytesRemaining > 0) { while (chunkIndex < chunkStarts.length && chunkStarts[chunkIndex] < blockNo * blockSize) { chunkIndex++; } long tempStart = thisStart; long endChunk; if (chunkIndex >= chunkStarts.length) { splitSize = chunkStarts[chunkStarts.length - 1] + recSize - thisStart - smallSize; } else { splitSize = chunkStarts[chunkIndex] - thisStart - smallSize; thisStart = chunkStarts[chunkIndex]; } endChunk = chunkIndex; blockNo++; //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize="+splitSize+", thisStart="+thisStart+ // ", endChunk="+endChunk+", blockNo="+blockNo); System.out.println("[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize=" + splitSize + ", thisStart=" + thisStart + ", endChunk=" + endChunk + ", blockNo=" + blockNo); String[] splitHosts = getSplitHosts(blkLocations, tempStart, splitSize, clusterMap); NetCDFFileSplit split = new NetCDFFileSplit(path, tempStart, splitSize, splitHosts); if (chooseLat) { if (latTopTemp < thisChunk) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if (latBottomTemp > endChunk) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } blockToNodes.put(split, splitHosts); // Put the nodes with the specified split into the node to block set for (int i = 0; i < splitHosts.length; i++) { Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if (splitList == null) { splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put(splitHosts[i], splitList); } splitList.add(split); } // For the test, we would assign everything statically. if (latBottomLimit > thisChunk) { System.out .println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] startChunk = " + latBottomLimit); split.getFileSplit().startChunk.add((long) latBottomLimit); } else { split.getFileSplit().startChunk.add(thisChunk); } if (latTopLimit < endChunk) { System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] endChunk = " + latTopLimit); split.getFileSplit().endChunk.add((long) latTopLimit); } else { split.getFileSplit().endChunk.add(endChunk); } split.getFileSplit().secondDimStartChunk.add((long) lonBottomTemp); split.getFileSplit().secondDimEndChunk.add((long) lonTopTemp); } if (!chooseLat) { if (lonTopTemp < thisChunk) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if (lonBottomTemp > endChunk) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } blockToNodes.put(split, splitHosts); // Put the nodes with the specified split into the node to block set for (int i = 0; i < splitHosts.length; i++) { Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if (splitList == null) { splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put(splitHosts[i], splitList); } splitList.add(split); } if (lonBottomLimit > thisChunk) { System.out .println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] startChunk = " + latBottomLimit); split.getFileSplit().startChunk.add((long) lonBottomLimit); } else { split.getFileSplit().startChunk.add(thisChunk); } if (lonTopLimit < endChunk) { System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] endChunk = " + latTopLimit); split.getFileSplit().endChunk.add((long) lonTopLimit); } else { split.getFileSplit().endChunk.add(endChunk); } split.getFileSplit().secondDimStartChunk.add((long) latBottomTemp); split.getFileSplit().secondDimEndChunk.add((long) latTopTemp); } splits.add(split); bytesRemaining -= splitSize; thisChunk = endChunk; //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk ); //System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk ); } } else if (length != 0) { String[] splitHosts = getSplitHosts(blkLocations, 0, length, clusterMap); //splits.add(new FileSplit(path, 0, length, splitHosts)); } else { //Create empty hosts array for zero length files //splits.add(new FileSplit(path, 0, length, new String[0])); } } // Now it's time to merge non-complete splits. // Check if each split has enough space to include another split too Set<String> completedNodes = new HashSet<String>(); ArrayList<NetCDFFileSplit> validBlocks = new ArrayList<NetCDFFileSplit>(); long curSplitSize = 0; Multiset<String> splitsPerNode = HashMultiset.create(); for (Iterator<Map.Entry<String, Set<NetCDFFileSplit>>> iter = nodeToBlocks.entrySet().iterator(); iter .hasNext();) { Map.Entry<String, Set<NetCDFFileSplit>> one = iter.next(); String node = one.getKey(); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] node is = " + node); // Skip the node if it has previously been marked as completed. if (completedNodes.contains(node)) { continue; } Set<NetCDFFileSplit> blocksInCurrentNode = one.getValue(); // for each block, copy it into validBlocks. Delete it from // blockToNodes so that the same block does not appear in // two different splits. Iterator<NetCDFFileSplit> oneBlockIter = blocksInCurrentNode.iterator(); while (oneBlockIter.hasNext()) { NetCDFFileSplit oneblock = oneBlockIter.next(); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "split is: " + oneblock.getFileSplit().getPath()); // Remove all blocks which may already have been assigned to other // splits. if (!blockToNodes.containsKey(oneblock)) { oneBlockIter.remove(); continue; } validBlocks.add(oneblock); if (chooseLat) { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.lonLength * netInfo.timeLength; } else { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.latLength * netInfo.timeLength; } blockToNodes.remove(oneblock); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] curSplitSize = " + curSplitSize); //curSplitSize += singleSplitSize; System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "Added to valid blocks!"); // if the accumulated split size exceeds the maximum, then // create this split. if (blockSize != 0 && curSplitSize >= blockSize) { // create an input split and add it to the splits array addCreatedSplit(finalSplits, Collections.singleton(node), validBlocks); //totalLength -= curSplitSize; System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "addCreatedSplit called!"); curSplitSize = 0; splitsPerNode.add(node); // Remove entries from blocksInNode so that we don't walk these // again. //blocksInCurrentNode.removeAll(validBlocks); validBlocks.clear(); // Done creating a single split for this node. Move on to the next // node so that splits are distributed across nodes. //break; } } if (!validBlocks.isEmpty()) { System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] validBlocks not empty!"); addCreatedSplit(finalSplits, Collections.singleton(node), validBlocks); curSplitSize = 0; splitsPerNode.add(node); blocksInCurrentNode.removeAll(validBlocks); validBlocks.clear(); } } Set<NetCDFFileSplit> singleSplitsSet = blockToNodes.keySet(); Iterator itrSingle = singleSplitsSet.iterator(); while (itrSingle.hasNext()) { NetCDFFileSplit temp = (NetCDFFileSplit) itrSingle.next(); addCreatedSingleSplit(finalSplits, temp.getLocations(), temp); } Iterator itr = finalSplits.iterator(); while (itr.hasNext()) { NetCDFFileSplit temp = (NetCDFFileSplit) itr.next(); String[] locations = temp.getFileSplit().getLocations(); String locationsString = ""; for (int i = 0; i < locations.length; i++) locationsString += locations[i]; String pathsString = ""; List<Path> paths = temp.getFileSplit().getPaths(); for (Path path : paths) pathsString += path.getName() + ","; String startsString = ""; List<Long> starts = temp.getFileSplit().startChunk; for (Long start : starts) startsString += (start + ","); String endsString = ""; List<Long> ends = temp.getFileSplit().endChunk; for (Long end : ends) endsString += (end + ","); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "locations=" + locationsString + "," + "paths=" + pathsString + "," + "starts=" + startsString + "," + "ends=" + endsString + ","); } return finalSplits.toArray(new NetCDFFileSplit[finalSplits.size()]); }
From source file:com.wasteofplastic.askyblock.commands.AdminCmd.java
@Override public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] split) { // Console commands Player player;/* w ww . jav a 2 s. c om*/ if (sender instanceof Player) { player = (Player) sender; if (split.length > 0) { // Admin-only commands : reload, register, delete and purge if (split[0].equalsIgnoreCase("reload") || split[0].equalsIgnoreCase("register") || split[0].equalsIgnoreCase("delete") || split[0].equalsIgnoreCase("purge") || split[0].equalsIgnoreCase("confirm") || split[0].equalsIgnoreCase("setspawn") || split[0].equalsIgnoreCase("deleteisland") || split[0].equalsIgnoreCase("setrange") || split[0].equalsIgnoreCase("reserve") || split[0].equalsIgnoreCase("unregister") || split[0].equalsIgnoreCase("clearresetall") || split[0].equalsIgnoreCase("settingsreset")) { if (!checkAdminPerms(player, split)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission); return true; } } else { // Mod commands if (!checkModPerms(player, split)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission); return true; } } } } // Island name (can have spaces) if (split.length > 1 && split[0].equalsIgnoreCase("name")) { final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); // plugin.getLogger().info("DEBUG: console player info UUID = " // + playerUUID); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { if (split.length == 2) { // Say the island name sender.sendMessage(plugin.getGrid().getIslandName(playerUUID)); } else { String name = split[2]; for (int i = 3; i < split.length; i++) { name = name + " " + split[i]; } if (name.length() < Settings.minNameLength) { sender.sendMessage(ChatColor.RED + (plugin.myLocale().errorTooShort).replace("[length]", String.valueOf(Settings.minNameLength))); return true; } if (name.length() > Settings.maxNameLength) { sender.sendMessage(ChatColor.RED + (plugin.myLocale().errorTooLong).replace("[length]", String.valueOf(Settings.maxNameLength))); return true; } plugin.getGrid().setIslandName(playerUUID, ChatColor.translateAlternateColorCodes('&', name)); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().generalSuccess); } return true; } } // Check for zero parameters e.g., /asadmin switch (split.length) { case 0: help(sender, label); return true; case 1: if (split[0].equalsIgnoreCase("setdeaths")) { sender.sendMessage(ChatColor.YELLOW + label + " setdeaths <player> <number>:" + ChatColor.WHITE + " " + plugin.myLocale().adminHelpsetDeaths); return true; } else if (split[0].equalsIgnoreCase("settingsreset")) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminHelpSettingsReset); return true; } else if (Settings.teamChat && split[0].equalsIgnoreCase("spy")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; if (VaultHelper.checkPerm(player, Settings.PERMPREFIX + "mod.spy") || player.isOp()) { if (plugin.getChatListener().toggleSpy(player.getUniqueId())) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().teamChatStatusOn); } else { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().teamChatStatusOff); } return true; } } else if (split[0].equalsIgnoreCase("lock")) { // Just /asadmin lock if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; Island island = plugin.getGrid().getIslandAt(player.getLocation()); // Check if island exists if (island == null) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNotOnIsland); return true; } else { Player owner = plugin.getServer().getPlayer(island.getOwner()); if (island.isLocked()) { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockUnlocking); island.setLocked(false); if (owner != null) { owner.sendMessage(plugin.myLocale(owner.getUniqueId()).adminLockadminUnlockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminUnlockedIsland); } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockLocking); island.setLocked(true); if (owner != null) { owner.sendMessage(plugin.myLocale(owner.getUniqueId()).adminLockadminLockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminLockedIsland); } } return true; } } else // Find farms if (split[0].equalsIgnoreCase("topbreeders")) { // Go through each island and find how many farms there are sender.sendMessage(plugin.myLocale().adminTopBreedersFinding); //TreeMap<Integer, List<UUID>> topEntityIslands = new TreeMap<Integer, List<UUID>>(); // Generate the stats sender.sendMessage(plugin.myLocale().adminTopBreedersChecking.replace("[number]", String.valueOf(plugin.getGrid().getOwnershipMap().size()))); // Try just finding every entity final List<Entity> allEntities = ASkyBlock.getIslandWorld().getEntities(); final World islandWorld = ASkyBlock.getIslandWorld(); final World netherWorld = ASkyBlock.getNetherWorld(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { Map<UUID, Multiset<EntityType>> result = new HashMap<UUID, Multiset<EntityType>>(); // Find out where the entities are for (Entity entity : allEntities) { //System.out.println("DEBUG " + entity.getType().toString()); if (entity.getLocation().getWorld().equals(islandWorld) || entity.getLocation().getWorld().equals(netherWorld)) { //System.out.println("DEBUG in world"); if (entity instanceof Creature && !(entity instanceof Player)) { //System.out.println("DEBUG creature"); // Find out where it is Island island = plugin.getGrid().getIslandAt(entity.getLocation()); if (island != null && !island.isSpawn()) { //System.out.println("DEBUG on island"); // Add to result UUID owner = island.getOwner(); Multiset<EntityType> count = result.get(owner); if (count == null) { // New entry for owner //System.out.println("DEBUG new entry for owner"); count = HashMultiset.create(); } count.add(entity.getType()); result.put(owner, count); } } } } // Sort by the number of entities on each island TreeMap<Integer, List<UUID>> topEntityIslands = new TreeMap<Integer, List<UUID>>(); for (Entry<UUID, Multiset<EntityType>> entry : result.entrySet()) { int numOfEntities = entry.getValue().size(); List<UUID> players = topEntityIslands.get(numOfEntities); if (players == null) { players = new ArrayList<UUID>(); } players.add(entry.getKey()); topEntityIslands.put(numOfEntities, players); } final TreeMap<Integer, List<UUID>> topBreeders = topEntityIslands; final Map<UUID, Multiset<EntityType>> finalResult = result; // Now display results in sync thread plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { if (topBreeders.isEmpty()) { sender.sendMessage(plugin.myLocale().adminTopBreedersNothing); return; } int rank = 1; // Display, largest first for (int numOfEntities : topBreeders.descendingKeySet()) { // Only bother if there's more that 5 animals if (numOfEntities > 5) { // There can be multiple owners in the same position List<UUID> owners = topBreeders.get(numOfEntities); // Go through the owners one by one for (UUID owner : owners) { sender.sendMessage("#" + rank + " " + plugin.getPlayers().getName(owner) + " = " + numOfEntities); String content = ""; Multiset<EntityType> entityCount = finalResult.get(owner); for (EntityType entity : entityCount.elementSet()) { int num = entityCount.count(entity); String color = ChatColor.GREEN.toString(); if (num > 10 && num <= 20) { color = ChatColor.YELLOW.toString(); } else if (num > 20 && num <= 40) { color = ChatColor.GOLD.toString(); } else if (num > 40) { color = ChatColor.RED.toString(); } content += Util.prettifyText(entity.toString()) + " x " + color + num + ChatColor.WHITE + ", "; } int lastComma = content.lastIndexOf(","); // plugin.getLogger().info("DEBUG: last comma " + // lastComma); if (lastComma > 0) { content = content.substring(0, lastComma); } sender.sendMessage(" " + content); } rank++; if (rank > 10) { break; } } } // If we didn't show anything say so if (rank == 1) { sender.sendMessage(plugin.myLocale().adminTopBreedersNothing); } } }); } }); return true; } // Delete island if (split[0].equalsIgnoreCase("deleteisland")) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminDeleteIslandError); return true; } // Set spawn if (split[0].equalsIgnoreCase("setspawn")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } player = (Player) sender; // Island spawn must be in the island world if (!player.getLocation().getWorld().getName().equals(Settings.worldName)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorWrongWorld); return true; } // The island location is calculated based on the grid Location closestIsland = getClosestIsland(player.getLocation()); Island oldSpawn = plugin.getGrid().getSpawn(); Island newSpawn = plugin.getGrid().getIslandAt(closestIsland); if (newSpawn != null && newSpawn.isSpawn()) { // Already spawn, so just set the world spawn coords plugin.getGrid().setSpawnPoint(player.getLocation()); //ASkyBlock.getIslandWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetSpawnset); return true; } // Space otherwise occupied - find if anyone owns it if (newSpawn != null && newSpawn.getOwner() != null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnownedBy.replace("[name]", plugin.getPlayers().getName(newSpawn.getOwner()))); sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnmove); return true; } if (oldSpawn != null) { sender.sendMessage(ChatColor.GOLD + "Changing spawn island location. Warning: old spawn island location at " + oldSpawn.getCenter().getBlockX() + "," + oldSpawn.getCenter().getBlockZ() + " will be at risk of being overwritten with new islands. Recommend to clear that old area."); plugin.getGrid().deleteSpawn(); } // New spawn site is free, so make it official if (newSpawn == null) { // Make the new spawn newSpawn = plugin.getGrid().addIsland(closestIsland.getBlockX(), closestIsland.getBlockZ(), Environment.NORMAL); } plugin.getGrid().setSpawn(newSpawn); plugin.getGrid().setSpawnPoint(player.getLocation()); //ASkyBlock.getIslandWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); player.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetSpawnsetting.replace("[location]", player.getLocation().getBlockX() + "," + player.getLocation().getBlockZ())); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawncenter.replace("[location]", newSpawn.getCenter().getBlockX() + "," + newSpawn.getCenter().getBlockZ())); player.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawnlimits.replace("[min]", newSpawn.getMinX() + "," + newSpawn.getMinZ())).replace("[max]", (newSpawn.getMinX() + newSpawn.getIslandDistance() - 1) + "," + (newSpawn.getMinZ() + newSpawn.getIslandDistance() - 1))); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnrange.replace("[number]", String.valueOf(newSpawn.getProtectionSize()))); player.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawncoords.replace("[min]", newSpawn.getMinProtectedX() + ", " + newSpawn.getMinProtectedZ())).replace("[max]", +(newSpawn.getMinProtectedX() + newSpawn.getProtectionSize() - 1) + ", " + (newSpawn.getMinProtectedZ() + newSpawn.getProtectionSize() - 1))); if (newSpawn.isLocked()) { player.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnlocked); } return true; } else if (split[0].equalsIgnoreCase("info") || split[0].equalsIgnoreCase("setrange")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } Location closestIsland = getClosestIsland(((Player) sender).getLocation()); if (closestIsland == null) { sender.sendMessage(ChatColor.RED + "Sorry, could not find an island. Move closer?"); return true; } Island island = plugin.getGrid().getIslandAt(closestIsland); if (island != null && island.isSpawn()) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminInfotitle); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawncenter.replace( "[location]", island.getCenter().getBlockX() + "," + island.getCenter().getBlockZ())); sender.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawnlimits.replace("[min]", island.getMinX() + "," + island.getMinZ())).replace("[max]", (island.getMinX() + island.getIslandDistance() - 1) + "," + (island.getMinZ() + island.getIslandDistance() - 1))); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnrange.replace("[number]", String.valueOf(island.getProtectionSize()))); sender.sendMessage(ChatColor.YELLOW + (plugin.myLocale().adminSetSpawncoords.replace("[min]", island.getMinProtectedX() + ", " + island.getMinProtectedZ())).replace("[max]", +(island.getMinProtectedX() + island.getProtectionSize() - 1) + ", " + (island.getMinProtectedZ() + island.getProtectionSize() - 1))); if (island.isLocked()) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnlocked); } return true; } if (island == null) { plugin.getLogger().info("Get island at was null" + closestIsland); } UUID target = plugin.getPlayers().getPlayerFromIslandLocation(closestIsland); if (target == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminInfounowned); return true; } showInfo(target, sender); return true; } else if (split[0].equalsIgnoreCase("resetsign")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } player = (Player) sender; if (!VaultHelper.checkPerm(player, Settings.PERMPREFIX + "mod.signadmin") && !player.isOp()) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoPermission); return true; } // Find out whether the player is looking at a warp sign // Look at what the player was looking at BlockIterator iter = new BlockIterator(player, 10); Block lastBlock = iter.next(); while (iter.hasNext()) { lastBlock = iter.next(); if (lastBlock.getType() == Material.AIR) continue; break; } if (!lastBlock.getType().equals(Material.SIGN_POST)) { sender.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminResetSignNoSign); return true; } // Check if it is a warp sign Sign sign = (Sign) lastBlock.getState(); sender.sendMessage(ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).adminResetSignFound); // Find out whose island this is // plugin.getLogger().info("DEBUG: closest bedrock: " + // closestBedRock.toString()); UUID target = plugin.getPlayers().getPlayerFromIslandLocation(player.getLocation()); if (target == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminInfounowned); return true; } if (plugin.getWarpSignsListener().addWarp(target, lastBlock.getLocation())) { // Change sign color to green sign.setLine(0, ChatColor.GREEN + plugin.myLocale().warpswelcomeLine); sign.update(); sender.sendMessage(ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).adminResetSignRescued .replace("[name]", plugin.getPlayers().getName(target))); return true; } // Warp already exists sender.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminResetSignErrorExists .replace("[name]", plugin.getWarpSignsListener().getWarpOwner(lastBlock.getLocation()))); return true; } else if (split[0].equalsIgnoreCase("reload")) { plugin.reloadConfig(); plugin.loadPluginConfig(); plugin.getChallenges().reloadChallengeConfig(); if (Settings.useEconomy && VaultHelper.setupEconomy()) { ControlPanel.loadShop(); } else { Settings.useEconomy = false; } ControlPanel.loadControlPanel(); if (Settings.updateCheck) { plugin.checkUpdates(); } else { plugin.setUpdateCheck(null); } plugin.getIslandCmd().loadSchematics(); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().reloadconfigReloaded); return true; } else if (split[0].equalsIgnoreCase("topten")) { sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminTopTengenerating); TopTen.topTenCreate(sender); return true; } else if (split[0].equalsIgnoreCase("purge")) { if (purgeFlag) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgealreadyRunning); return true; } sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgeusage.replace("[label]", label)); return true; } else if (split[0].equalsIgnoreCase("confirm")) { if (!confirmReq) { sender.sendMessage(ChatColor.RED + plugin.myLocale().confirmerrorTimeLimitExpired); return true; } else { // Tell purge routine to go confirmOK = true; confirmReq = false; } return true; } else // clearesetall - clears all player resets if (split[0].equalsIgnoreCase("clearresetall")) { if (asyncPending) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorCommandNotReady); return true; } // Do online players first plugin.getPlayers().clearResets(Settings.resetLimit); // Do offline players final File playerFolder = plugin.getPlayersFolder(); // Set the pending flag asyncPending = true; // Check against player files plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { //System.out.println("DEBUG: Running async task"); int done = 0; // Check files against potentialUnowned FilenameFilter ymlFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".yml")) { return true; } else { return false; } } }; for (File file : playerFolder.listFiles(ymlFilter)) { List<String> playerFileContents = new ArrayList<String>(); done++; try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { final String lineFromFile = scanner.nextLine(); if (lineFromFile.contains("resetsLeft:")) { playerFileContents.add("resetsLeft: " + Settings.resetLimit); } else { playerFileContents.add(lineFromFile); } } scanner.close(); // Write file FileWriter writer = new FileWriter(file); for (String str : playerFileContents) { writer.write(str + "\n"); } writer.close(); if (done % 500 == 0) { final int update = done; plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { // Tell player sender.sendMessage(ChatColor.GREEN + plugin.myLocale().clearedResetLimit + " [" + update + " players]..."); } }); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //System.out.println("DEBUG: scanning done"); asyncPending = false; sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().clearedResetLimit + " [" + done + " players] completed."); } }); return true; } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return false; } case 2: if (!plugin.getServer().getVersion().contains("(MC: 1.7")) { if (split[0].equalsIgnoreCase("level")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); // plugin.getLogger().info("DEBUG: console player info UUID = " // + playerUUID); if (playerUUID == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { if (sender instanceof Player) { plugin.getIslandCmd().calculateIslandLevel(sender, playerUUID, false); } else { plugin.getIslandCmd().calculateIslandLevel(sender, playerUUID, true); } return true; } } } if (split[0].equalsIgnoreCase("settingsreset")) { if (split[1].equalsIgnoreCase("confirm")) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().settingsResetInProgress); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { for (Collection<Island> islands : plugin.getGrid().getOwnedIslands().values()) { for (Island island : islands) { island.setDefaults(); } } for (Island island : plugin.getGrid().getUnownedIslands().values()) { island.setDefaults(); } sender.sendMessage(ChatColor.GREEN + plugin.myLocale().settingsResetDone); plugin.getGrid().saveGrid(); } }); return true; } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminHelpSettingsReset); return true; } } // Resetsign <player> - makes a warp sign for player if (split[0].equalsIgnoreCase("resetsign")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUseInGame); return true; } Player p = (Player) sender; if (!VaultHelper.checkPerm(p, Settings.PERMPREFIX + "mod.signadmin") && !p.isOp()) { p.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).errorNoPermission); return true; } // Convert target name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID, ((Player) sender).getWorld().getEnvironment()) && !plugin.getPlayers().inTeam(playerUUID)) { // No island sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Has an island // Find out whether the player is looking at a warp sign // Look at what the player was looking at BlockIterator iter = new BlockIterator(p, 10); Block lastBlock = iter.next(); while (iter.hasNext()) { lastBlock = iter.next(); if (lastBlock.getType() == Material.AIR) continue; break; } // Check if it is a sign if (!lastBlock.getType().equals(Material.SIGN_POST)) { sender.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).adminResetSignNoSign); return true; } Sign sign = (Sign) lastBlock.getState(); // Check if the sign is within the right island boundary Location islandLoc = plugin.getPlayers().getIslandLocation(playerUUID); if (!plugin.getGrid().getIslandAt(islandLoc).inIslandSpace(sign.getLocation())) { p.sendMessage( ChatColor.RED + plugin.myLocale(p.getUniqueId()).adminSetHomeNotOnPlayersIsland); } else { sender.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminResetSignFound); // Find out if this player is allowed to have a sign on this island if (plugin.getWarpSignsListener().addWarp(playerUUID, lastBlock.getLocation())) { // Change sign color to green sign.setLine(0, ChatColor.GREEN + plugin.myLocale().warpswelcomeLine); sign.update(); p.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminResetSignRescued .replace("[name]", plugin.getPlayers().getName(playerUUID))); return true; } // Warp already exists sender.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).adminResetSignErrorExists.replace("[name]", plugin.getWarpSignsListener().getWarpOwner(lastBlock.getLocation()))); } } return true; } // Delete the island you are on else if (split[0].equalsIgnoreCase("deleteisland")) { if (!split[1].equalsIgnoreCase("confirm")) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminDeleteIslandError); return true; } // Get the island I am on Island island = plugin.getGrid().getIslandAt(((Player) sender).getLocation()); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminDeleteIslandnoid); return true; } // Try to get the owner of this island UUID owner = island.getOwner(); String name = "unknown"; if (owner != null) { name = plugin.getPlayers().getName(owner); sender.sendMessage( ChatColor.RED + plugin.myLocale().adminSetSpawnownedBy.replace("[name]", name)); sender.sendMessage( ChatColor.RED + plugin.myLocale().adminDeleteIslanduse.replace("[name]", name)); return true; } else { sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().deleteremoving.replace("[name]", name)); deleteIslands(island, sender); return true; } } else if (split[0].equalsIgnoreCase("resetname")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID, ((Player) sender).getWorld().getEnvironment()) && !plugin.getPlayers().inTeam(playerUUID)) { // No island sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Has an island plugin.getGrid().setIslandName(playerUUID, null); sender.sendMessage(plugin.myLocale().generalSuccess); } return true; } else if (split[0].equalsIgnoreCase("resethome")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID, ((Player) sender).getWorld().getEnvironment()) && !plugin.getPlayers().inTeam(playerUUID)) { // No island sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Has an island Location safeHome = plugin.getGrid().getSafeHomeLocation(playerUUID, 1); if (safeHome == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetHomeNoneFound); } else { plugin.getPlayers().setHomeLocation(playerUUID, safeHome); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetHomeHomeSet.replace( "[location]", safeHome.getBlockX() + ", " + safeHome.getBlockY() + "," + safeHome.getBlockZ())); } } return true; } else if (split[0].equalsIgnoreCase("sethome")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); } else { // Check if this player has an island if (!plugin.getPlayers().hasIsland(playerUUID, player.getWorld().getEnvironment()) && !plugin.getPlayers().inTeam(playerUUID)) { // No island player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorNoIslandOther); return true; } // Has an island Location islandLoc = plugin.getPlayers().getIslandLocation(playerUUID); // Check the player is within the island boundaries if (!plugin.getGrid().getIslandAt(islandLoc).inIslandSpace(player.getLocation())) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminSetHomeNotOnPlayersIsland); } else { // Check that the location is safe if (!GridManager.isSafeLocation(player.getLocation())) { // Not safe player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminSetHomeNoneFound); } else { // Success plugin.getPlayers().setHomeLocation(playerUUID, player.getLocation()); player.sendMessage( ChatColor.GREEN + plugin.myLocale(player.getUniqueId()).adminSetHomeHomeSet .replace("[location]", player.getLocation().getBlockX() + ", " + player.getLocation().getBlockY() + "," + player.getLocation().getBlockZ())); } } } return true; } else // Set protection for the island the player is on if (split[0].equalsIgnoreCase("setrange")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } player = (Player) sender; UUID playerUUID = player.getUniqueId(); Island island = plugin.getGrid().getIslandAt(player.getLocation()); // Check if island exists if (island == null) { player.sendMessage(ChatColor.RED + plugin.myLocale().errorNotOnIsland); return true; } else { int newRange = 10; int maxRange = Settings.islandDistance; // If spawn do something different if (island.isSpawn()) { try { newRange = Integer.valueOf(split[1]); } catch (Exception e) { player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeInvalid); return true; } player.sendMessage(ChatColor.GREEN + plugin.myLocale(playerUUID).adminSetRangeSet .replace("[number]", String.valueOf(newRange))); if (newRange > maxRange) { player.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + plugin.myLocale(playerUUID).adminSetRangeWarning.replace("[max]", String.valueOf(maxRange))); player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeWarning2); } island.setProtectionSize(newRange); player.sendMessage( ChatColor.YELLOW + plugin.myLocale().adminSetSpawncenter.replace("[location]", island.getCenter().getBlockX() + "," + island.getCenter().getBlockZ())); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnlimits .replace("[min]", island.getMinX() + "," + island.getMinZ()) .replace("[max]", (island.getMinX() + island.getIslandDistance() - 1) + "," + (island.getMinZ() + island.getIslandDistance() - 1))); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawnrange .replace("[number]", String.valueOf(island.getProtectionSize()))); player.sendMessage(ChatColor.YELLOW + plugin.myLocale().adminSetSpawncoords .replace("[min]", island.getMinProtectedX() + ", " + island.getMinProtectedZ()) .replace("[max]", +(island.getMinProtectedX() + island.getProtectionSize() - 1) + ", " + (island.getMinProtectedZ() + island.getProtectionSize() - 1))); if (island.isLocked()) { player.sendMessage(ChatColor.RED + plugin.myLocale().adminSetSpawnlocked); } } else { if (!plugin.getConfig().getBoolean("island.overridelimit")) { maxRange -= 16; } try { newRange = Integer.valueOf(split[1]); } catch (Exception e) { player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeInvalid + " " + plugin.myLocale(playerUUID).adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } if (newRange < 10 || newRange > maxRange) { player.sendMessage(ChatColor.RED + plugin.myLocale(playerUUID).adminSetRangeInvalid + " " + plugin.myLocale(playerUUID).adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } island.setProtectionSize(newRange); player.sendMessage(ChatColor.GREEN + plugin.myLocale(playerUUID).adminSetRangeSet .replace("[number]", String.valueOf(newRange))); showInfo(island.getOwner(), sender); } return true; } } if (split[0].equalsIgnoreCase("purge")) { // PURGE Command // Check for "allow" or "disallow" flags // Protect island from purging if (split[1].equalsIgnoreCase("allow") || split[1].equalsIgnoreCase("disallow")) { // Find the closest island if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminLockerrorInGame); return true; } Player p = (Player) sender; // Island spawn must be in the island world if (!p.getLocation().getWorld().equals(ASkyBlock.getIslandWorld()) && !p.getLocation().getWorld().equals(ASkyBlock.getNetherWorld())) { p.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).errorWrongWorld); return true; } Island island = plugin.getGrid().getIslandAt(p.getLocation()); if (island == null) { p.sendMessage(ChatColor.RED + plugin.myLocale(p.getUniqueId()).errorNoIslandOther); return true; } if (split[1].equalsIgnoreCase("allow")) { island.setPurgeProtected(true); } else { island.setPurgeProtected(false); } if (island.isPurgeProtected()) { p.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminAllowPurge); } else { p.sendMessage(ChatColor.GREEN + plugin.myLocale(p.getUniqueId()).adminPreventPurge); } return true; } // Purge runs in the background so if one is already running // this flag stops a repeat if (purgeFlag) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgealreadyRunning); return true; } if (split[1].equalsIgnoreCase("unowned")) { countUnowned(sender); return true; } // Set the flag purgeFlag = true; // See if this purge unowned // Convert days to hours - no other limit checking? final int time; try { time = Integer.parseInt(split[1]) * 24; } catch (Exception e) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgeusage.replace("[label]", label)); purgeFlag = false; return true; } sender.sendMessage( ChatColor.YELLOW + plugin.myLocale().purgecalculating.replace("[time]", split[1])); // Check who has not been online since the time for (Entry<UUID, Collection<Island>> entry : plugin.getGrid().getOwnershipMap().asMap() .entrySet()) { for (Island island : entry.getValue()) { if (entry.getKey() != null && !island.isPurgeProtected()) { if (Bukkit.getOfflinePlayer(entry.getKey()).hasPlayedBefore()) { long offlineTime = Bukkit.getOfflinePlayer(entry.getKey()).getLastPlayed(); offlineTime = (System.currentTimeMillis() - offlineTime) / 3600000L; if (offlineTime > time) { //if (plugin.getPlayers().getIslandLevel(entry.getKey()) < Settings.abandonedIslandLevel) { // Check level later removeList.add(entry.getKey()); //} } } else { removeList.add(entry.getKey()); } } } //plugin.getLogger().info("UUID = " + entry.getKey()); // Only do this if it isn't protected } if (removeList.isEmpty()) { sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgenoneFound); purgeFlag = false; return true; } sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgethisWillRemove .replace("[number]", String.valueOf(removeList.size())) .replace("[level]", String.valueOf(Settings.abandonedIslandLevel))); sender.sendMessage(ChatColor.RED + plugin.myLocale().purgewarning); sender.sendMessage(ChatColor.RED + plugin.myLocale().purgetypeConfirm.replace("[label]", label)); confirmReq = true; confirmOK = false; confirmTimer = 0; new BukkitRunnable() { @Override public void run() { // This waits for 10 seconds and if no // confirmation received, then it // cancels if (confirmTimer++ > 10) { // Ten seconds is up! confirmReq = false; confirmOK = false; purgeFlag = false; removeList.clear(); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgepurgeCancelled); this.cancel(); } else if (confirmOK) { // Set up a repeating task to run every 2 // seconds to remove // islands one by one and then cancel when // done final int total = removeList.size(); new BukkitRunnable() { @Override public void run() { if (removeList.isEmpty() && purgeFlag) { purgeFlag = false; sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().purgefinished); this.cancel(); } if (removeList.size() > 0 && purgeFlag) { // Check if the player is online if (plugin.getServer().getPlayer(removeList.get(0)) == null) { //plugin.getLogger().info("DEBUG: player is offline"); // Check the level if (plugin.getPlayers().getIslandLevel( removeList.get(0)) < Settings.abandonedIslandLevel) { sender.sendMessage(ChatColor.YELLOW + "[" + (total - removeList.size() + 1) + "/" + total + "] " + plugin.myLocale().purgeremovingName.replace("[name]", plugin.getPlayers().getName(removeList.get(0)))); plugin.deletePlayerIsland(removeList.get(0), true, plugin.getServer().getPlayer(removeList.get(0)).getWorld() .getEnvironment()); } } else { sender.sendMessage( ChatColor.YELLOW + "[" + (total - removeList.size() + 1) + "/" + total + "] " + "Skipping online player..."); } removeList.remove(0); } //sender.sendMessage("Now waiting..."); } }.runTaskTimer(plugin, 0L, 20L); confirmReq = false; confirmOK = false; this.cancel(); } } }.runTaskTimer(plugin, 0L, 40L); return true; } else if (split[0].equalsIgnoreCase("lock")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { Island island = plugin.getGrid().getIsland(playerUUID, plugin.getServer().getPlayer(playerUUID).getWorld().getEnvironment()); if (island != null) { Player owner = plugin.getServer().getPlayer(island.getOwner()); if (island.isLocked()) { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockUnlocking); island.setLocked(false); if (owner != null) { owner.sendMessage( plugin.myLocale(owner.getUniqueId()).adminLockadminUnlockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminUnlockedIsland); } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().lockLocking); island.setLocked(true); if (owner != null) { owner.sendMessage(plugin.myLocale(owner.getUniqueId()).adminLockadminLockedIsland); } else { plugin.getMessages().setMessage(island.getOwner(), plugin.myLocale(island.getOwner()).adminLockadminLockedIsland); } } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); } return true; } } else if (split[0].equalsIgnoreCase("setdeaths")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { sender.sendMessage(ChatColor.GREEN + plugin.getPlayers().getName(playerUUID) + " " + plugin.getPlayers().getDeaths(playerUUID) + " " + plugin.myLocale().deaths); sender.sendMessage(ChatColor.YELLOW + label + " setdeaths <player> <number>:" + ChatColor.WHITE + " " + plugin.myLocale().adminHelpsetDeaths); return true; } } else if (split[0].equalsIgnoreCase("clearreset")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { plugin.getPlayers().setResetsLeft(playerUUID, Settings.resetLimit); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().clearedResetLimit + " [" + Settings.resetLimit + "]"); return true; } } else if (split[0].equalsIgnoreCase("tp")) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return true; } player = (Player) sender; // Convert name to a UUID final UUID targetUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(targetUUID)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorUnknownPlayer); return true; } else { if (plugin.getPlayers().hasIsland(targetUUID, player.getWorld().getEnvironment()) || plugin.getPlayers().inTeam(targetUUID)) { // Teleport to the over world Location warpSpot = plugin.getPlayers().getIslandLocation(targetUUID).toVector() .toLocation(ASkyBlock.getIslandWorld()); String failureMessage = ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminTpManualWarp.replace("[location]", warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " " + warpSpot.getBlockZ()); // Try the player's home first Location home = plugin.getPlayers().getHomeLocation(targetUUID); plugin.getGrid(); if (home != null && home.getWorld().equals(ASkyBlock.getIslandWorld()) && GridManager.isSafeLocation(home)) { player.teleport(home); return true; } // Other wise, go to a safe spot new SafeSpotTeleport(plugin, player, warpSpot, failureMessage); return true; } sender.sendMessage(plugin.myLocale().errorNoIslandOther); return true; } } else if (split[0].equalsIgnoreCase("tpnether")) { if (!Settings.createNether || !Settings.newNether || ASkyBlock.getNetherWorld() == null) { return false; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return true; } player = (Player) sender; // Convert name to a UUID final UUID targetUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(targetUUID)) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorUnknownPlayer); return true; } else { if (plugin.getPlayers().hasIsland(targetUUID, player.getWorld().getEnvironment()) || plugin.getPlayers().inTeam(targetUUID)) { // Teleport to the nether Location warpSpot = plugin.getPlayers().getIslandLocation(targetUUID).toVector() .toLocation(ASkyBlock.getNetherWorld()); String failureMessage = ChatColor.RED + plugin.myLocale(player.getUniqueId()).adminTpManualWarp.replace("[location]", warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " " + warpSpot.getBlockZ()); // Try the player's home first Location home = plugin.getPlayers().getHomeLocation(targetUUID); plugin.getGrid(); if (home != null && home.getWorld().equals(ASkyBlock.getNetherWorld()) && GridManager.isSafeLocation(home)) { player.teleport(home); return true; } new SafeSpotTeleport(plugin, player, warpSpot, failureMessage); return true; } sender.sendMessage(plugin.myLocale().errorNoIslandOther); return true; } } else if (split[0].equalsIgnoreCase("delete")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { // This now deletes the player and cleans them up even if // they don't have an island sender.sendMessage( ChatColor.YELLOW + plugin.myLocale().deleteremoving.replace("[name]", split[1])); // If they are online and in ASkyBlock then delete their // stuff too Player target = plugin.getServer().getPlayer(playerUUID); if (target != null) { // Clear any coop inventories // CoopPlay.getInstance().returnAllInventories(target); // Remove any of the target's coop invitees and grab // their stuff CoopPlay.getInstance().clearMyInvitedCoops(target); CoopPlay.getInstance().clearMyCoops(target); plugin.resetPlayer(target); } // plugin.getLogger().info("DEBUG: deleting player"); plugin.deletePlayerIsland(playerUUID, true, Environment.NETHER); plugin.deletePlayerIsland(playerUUID, true, Environment.NORMAL); return true; } } else if (split[0].equalsIgnoreCase("reserve")) { // Reserves a spot for the player's next island if (sender instanceof Player) { player = (Player) sender; // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { // Check the spot Location islandLoc = plugin.getGrid().getClosestIsland(player.getLocation()); Island island = plugin.getGrid().getIslandAt(islandLoc); if (island == null) { // Empty spot, reserve it! plugin.getIslandCmd().reserveLocation(playerUUID, islandLoc); sender.sendMessage(ChatColor.GREEN + " [" + islandLoc.getBlockX() + ", " + islandLoc.getBlockZ() + "] " + plugin.myLocale().generalSuccess); } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminReserveIslandExists); } return true; } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); } return true; } else if (split[0].equalsIgnoreCase("register")) { if (sender instanceof Player) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { if (adminSetPlayerIsland(sender, ((Player) sender).getLocation(), playerUUID)) { sender.sendMessage(ChatColor.GREEN + plugin.myLocale().registersettingIsland.replace("[name]", split[1])); plugin.getGrid().saveGrid(); } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().registererrorBedrockNotFound); } return true; } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); } return true; } else if (split[0].equalsIgnoreCase("unregister")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { if (plugin.getPlayers().inTeam(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminUnregisterOnTeam); return true; } Location island = plugin.getPlayers().getIslandLocation(playerUUID); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } // Delete player, but keep blocks sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminUnregisterKeepBlocks .replace("[location]", +plugin.getPlayers().getIslandLocation(playerUUID).getBlockX() + "," + plugin.getPlayers().getIslandLocation(playerUUID).getBlockZ())); plugin.deletePlayerIsland(playerUUID, false, Environment.NORMAL); plugin.deletePlayerIsland(playerUUID, false, Environment.NETHER); plugin.getGrid().saveGrid(); return true; } } else if (split[0].equalsIgnoreCase("info")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); // plugin.getLogger().info("DEBUG: console player info UUID = " // + playerUUID); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { showInfo(playerUUID, sender); return true; } } else if (split[0].equalsIgnoreCase("resetallchallenges")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } plugin.getPlayers().resetAllChallenges(playerUUID, true); sender.sendMessage( ChatColor.YELLOW + plugin.myLocale().resetChallengessuccess.replace("[name]", split[1])); return true; } else { return false; } case 3: // Confirm purge unowned if (split[0].equalsIgnoreCase("purge")) { if (purgeFlag) { sender.sendMessage(ChatColor.RED + plugin.myLocale().purgealreadyRunning); return true; } // Check if this is purge unowned if (split[1].equalsIgnoreCase("unowned") && split[2].equalsIgnoreCase("confirm")) { if (!purgeUnownedConfirm) { sender.sendMessage(ChatColor.RED + plugin.myLocale().confirmerrorTimeLimitExpired); return true; } else { purgeUnownedConfirm = false; // Purge the unowned islands purgeUnownedIslands(sender); return true; } } } // Set protection if (split[0].equalsIgnoreCase("setrange")) { // Convert name to a UUID UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); // Check if player exists if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } // Check if the target is in a team and if so, the leader needs to be adjusted if (plugin.getPlayers().inTeam(playerUUID)) { playerUUID = plugin.getPlayers().getTeamLeader(playerUUID); } // Get the range that this player has now Island island = plugin.getGrid().getIsland(playerUUID, ((Player) sender).getWorld().getEnvironment()); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIslandOther); return true; } else { int newRange = 0; int maxRange = Settings.islandDistance; if (!plugin.getConfig().getBoolean("island.overridelimit")) { maxRange -= 16; } try { newRange = Integer.valueOf(split[2]); } catch (Exception e) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetRangeInvalid + " " + plugin.myLocale().adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } if (newRange < 10 || newRange > maxRange) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminSetRangeInvalid + " " + plugin.myLocale().adminSetRangeTip.replace("[max]", String.valueOf(maxRange))); return true; } island.setProtectionSize(newRange); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminSetRangeSet.replace("[number]", String.valueOf(newRange))); showInfo(playerUUID, sender); plugin.getGrid().saveGrid(); return true; } } else if (split[0].equalsIgnoreCase("setdeaths")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { try { int newDeaths = Integer.valueOf(split[2]); int oldDeaths = plugin.getPlayers().getDeaths(playerUUID); plugin.getPlayers().setDeaths(playerUUID, newDeaths); sender.sendMessage(ChatColor.GREEN + plugin.getPlayers().getName(playerUUID) + " " + oldDeaths + " >>> " + newDeaths + " " + plugin.myLocale().deaths); } catch (Exception e) { sender.sendMessage(ChatColor.GREEN + plugin.getPlayers().getName(playerUUID) + " " + plugin.getPlayers().getDeaths(playerUUID) + " " + plugin.myLocale().deaths); sender.sendMessage(ChatColor.YELLOW + label + " setdeaths <player> <number>:" + ChatColor.WHITE + " " + plugin.myLocale().adminHelpsetDeaths); return true; } return true; } } // Change biomes if (split[0].equalsIgnoreCase("setbiome")) { // Convert name to a UUID UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); // Check if player exists if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } // Check if the target is in a team and if so, the leader if (plugin.getPlayers().inTeam(playerUUID)) { playerUUID = plugin.getPlayers().getTeamLeader(playerUUID); } Island island = plugin.getGrid().getIsland(playerUUID, ((Player) sender).getLocation().getWorld().getEnvironment()); if (island == null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoIsland); return true; } // Check if biome is valid Biome biome = null; String biomeName = split[2].toUpperCase(); try { biome = Biome.valueOf(biomeName); biomeName = biome.name(); if (!plugin.getConfig().contains("biomes." + biomeName)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().biomeUnknown); // Doing it this way ensures that only valid biomes are // shown for (Biome b : Biome.values()) { if (plugin.getConfig().contains("biomes." + b.name())) { sender.sendMessage(b.name()); } } return true; } // Get friendly name biomeName = plugin.getConfig().getString("biomes." + biomeName + ".friendlyname", Util.prettifyText(biomeName)); } catch (Exception e) { sender.sendMessage(ChatColor.RED + plugin.myLocale().biomeUnknown); for (Biome b : Biome.values()) { if (plugin.getConfig().contains("biomes." + b.name())) { sender.sendMessage(b.name()); } } return true; } // Okay clear to set biome // Actually set the biome plugin.getBiomes().setIslandBiome(island, biome); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().biomeSet.replace("[biome]", biomeName)); Player targetPlayer = plugin.getServer().getPlayer(playerUUID); if (targetPlayer != null) { // Online targetPlayer.sendMessage("[Admin] " + ChatColor.GREEN + plugin.myLocale(playerUUID).biomeSet.replace("[biome]", biomeName)); } else { plugin.getMessages().setMessage(playerUUID, "[Admin] " + ChatColor.GREEN + plugin.myLocale(playerUUID).biomeSet.replace("[biome]", biomeName)); } return true; } else // team kick <player> and team delete <leader> if (split[0].equalsIgnoreCase("team")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[2], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (split[1].equalsIgnoreCase("kick")) { // Remove player from team if (!plugin.getPlayers().inTeam(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorNoTeam); return true; } UUID teamLeader = plugin.getPlayers().getTeamLeader(playerUUID); if (teamLeader == null) { // Player is apparently in a team, but there is no team leader // Remove their team status // Clear the player of all team-related items plugin.getPlayers().setLeaveTeam(playerUUID); plugin.getPlayers().setHomeLocation(playerUUID, null); plugin.getPlayers().setIslandLocation(playerUUID, null); // Remove any warps plugin.getWarpSignsListener().removeWarp(playerUUID); sender.sendMessage( ChatColor.RED + plugin.myLocale().kicknameRemoved.replace("[name]", split[2])); return true; } // Payer is not a team leader if (!teamLeader.equals(playerUUID)) { // Clear the player of all team-related items plugin.getPlayers().setLeaveTeam(playerUUID); plugin.getPlayers().setHomeLocation(playerUUID, null); plugin.getPlayers().setIslandLocation(playerUUID, null); // Clear the leader of this player and if they now have // no team, remove the team plugin.getPlayers().removeMember(teamLeader, playerUUID); if (plugin.getPlayers().getMembers(teamLeader).size() < 2) { plugin.getPlayers().setLeaveTeam(teamLeader); } // Remove any warps plugin.getWarpSignsListener().removeWarp(playerUUID); sender.sendMessage( ChatColor.RED + plugin.myLocale().kicknameRemoved.replace("[name]", split[2])); return true; } else { sender.sendMessage( ChatColor.RED + (plugin.myLocale().adminTeamKickLeader.replace("[label]", label)) .replace("[name]", split[2])); return true; } } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return false; } } else if (split[0].equalsIgnoreCase("completechallenge")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (plugin.getPlayers().checkChallenge(playerUUID, split[2].toLowerCase()) || !plugin.getPlayers().get(playerUUID).challengeExists(split[2].toLowerCase())) { sender.sendMessage( ChatColor.RED + plugin.myLocale().completeChallengeerrorChallengeDoesNotExist); return true; } plugin.getPlayers().get(playerUUID).completeChallenge(split[2].toLowerCase()); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().completeChallengechallangeCompleted .replace("[challengename]", split[2].toLowerCase()).replace("[name]", split[1])); return true; } else if (split[0].equalsIgnoreCase("resetchallenge")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[1], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (!plugin.getPlayers().checkChallenge(playerUUID, split[2].toLowerCase()) || !plugin.getPlayers().get(playerUUID).challengeExists(split[2].toLowerCase())) { sender.sendMessage(ChatColor.RED + plugin.myLocale().resetChallengeerrorChallengeDoesNotExist); return true; } plugin.getPlayers().resetChallenge(playerUUID, split[2].toLowerCase()); sender.sendMessage(ChatColor.YELLOW + plugin.myLocale().resetChallengechallengeReset .replace("[challengename]", split[2].toLowerCase()).replace("[name]", split[1])); return true; } else if (split[0].equalsIgnoreCase("info") && split[1].equalsIgnoreCase("challenges")) { // Convert name to a UUID final UUID playerUUID = plugin.getPlayers().getUUID(split[2], true); // plugin.getLogger().info("DEBUG: console player info UUID = " // + playerUUID); if (!plugin.getPlayers().isAKnownPlayer(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } else { showInfoChallenges(playerUUID, sender); return true; } } return false; case 4: // Team add <player> <leader> if (split[0].equalsIgnoreCase("team") && split[1].equalsIgnoreCase("add")) { // Convert names to UUIDs final UUID playerUUID = plugin.getPlayers().getUUID(split[2], true); final Player targetPlayer = plugin.getServer().getPlayer(playerUUID); final UUID teamLeader = plugin.getPlayers().getUUID(split[3], true); if (!plugin.getPlayers().isAKnownPlayer(playerUUID) || !plugin.getPlayers().isAKnownPlayer(teamLeader)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownPlayer); return true; } if (playerUUID.equals(teamLeader)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminTeamAddLeaderToOwn); return true; } // See if leader has an island if (!plugin.getPlayers().hasIsland(teamLeader, ((Player) sender).getWorld().getEnvironment())) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminTeamAddLeaderNoIsland); return true; } // Check to see if this player is already in a team if (plugin.getPlayers().inTeam(playerUUID)) { sender.sendMessage(ChatColor.RED + plugin.myLocale().inviteerrorThatPlayerIsAlreadyInATeam); return true; } // If the leader's member list does not contain their own name // then // add it if (!plugin.getPlayers().getMembers(teamLeader).contains(teamLeader)) { // Set up the team leader plugin.getPlayers().setJoinTeam(teamLeader, teamLeader, plugin.getPlayers().getIslandLocation(teamLeader)); plugin.getPlayers().addTeamMember(teamLeader, teamLeader); sender.sendMessage(ChatColor.GOLD + plugin.myLocale().adminTeamAddedLeader); } // This is a hack to clear any pending invitations if (targetPlayer != null) { targetPlayer.performCommand(Settings.ISLANDCOMMAND + " decline"); } // If the invitee has an island of their own if (plugin.getPlayers().hasIsland(playerUUID, ((Player) sender).getWorld().getEnvironment())) { Location islandLoc = plugin.getPlayers().getIslandLocation(playerUUID); if (islandLoc != null) { sender.sendMessage(ChatColor.RED + plugin.myLocale().adminTeamNowUnowned .replace("[name]", plugin.getPlayers().getName(playerUUID)) .replace("[location]", islandLoc.getBlockX() + " " + islandLoc.getBlockZ())); } } // Remove their old island affiliation - do not delete the // island just in case plugin.deletePlayerIsland(playerUUID, false, Environment.NETHER); plugin.deletePlayerIsland(playerUUID, false, Environment.NORMAL); // Join the team and set the team island location and leader plugin.getPlayers().setJoinTeam(playerUUID, teamLeader, plugin.getPlayers().getIslandLocation(teamLeader)); // Configure the best home location for this player if (plugin.getPlayers().getHomeLocation(teamLeader) != null) { plugin.getPlayers().setHomeLocation(playerUUID, plugin.getPlayers().getHomeLocation(teamLeader)); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminTeamSettingHome); } else { plugin.getPlayers().setHomeLocation(playerUUID, plugin.getPlayers().getIslandLocation(teamLeader)); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminTeamSettingHome); } // If the leader's member list does not contain player then add // it if (!plugin.getPlayers().getMembers(teamLeader).contains(playerUUID)) { plugin.getPlayers().addTeamMember(teamLeader, playerUUID); sender.sendMessage(ChatColor.GREEN + plugin.myLocale().adminTeamAddingPlayer); } else { sender.sendMessage(ChatColor.GOLD + plugin.myLocale().adminTeamAlreadyOnTeam); } // Teleport the player if they are online if (targetPlayer != null) { plugin.getGrid().homeTeleport(targetPlayer, targetPlayer.getWorld().getEnvironment()); } plugin.getGrid().saveGrid(); return true; } else { sender.sendMessage(ChatColor.RED + plugin.myLocale().errorUnknownCommand); return false; } default: return false; } }
From source file:org.apache.hadoop.mapred.NetCDFInputFormatPrunerByFileIndexMultiFile.java
@Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { FileStatus[] files = listStatus(job); LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher")); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher")); /* Analyzing Query here */ String hiveQuery = job.get(HIVE_QUERY, "Kossher"); QueryType queryType = QueryType.NOLIMIT; // default mode if (hiveQuery.contains("where") || hiveQuery.contains("WHERE")) { if (hiveQuery.contains("time") || hiveQuery.contains("TIME")) { queryType = QueryType.TIME;/*from www.j av a2 s . c om*/ } else if (hiveQuery.contains("lat") || hiveQuery.contains("LAT")) { queryType = QueryType.LAT; } else if (hiveQuery.contains("lon") || hiveQuery.contains("LON")) { queryType = QueryType.LON; } } float topLimit = -1; float bottomLimit = -1; if (queryType != QueryType.NOLIMIT) { if (hiveQuery.contains("<")) { String[] querySplitted = hiveQuery.split(" "); int i = Arrays.asList(querySplitted).indexOf("<"); topLimit = Float.valueOf(querySplitted[i + 1]); } if (hiveQuery.contains(">")) { String[] querySplitted = hiveQuery.split(" "); int i = Arrays.asList(querySplitted).indexOf(">"); bottomLimit = Float.valueOf(querySplitted[i + 1]); } } //System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndex] QueryType = " + queryType.toString() // +", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit ); //LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex] QueryType = " + queryType.toString() // + ", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit); /* End Analyzing Query here */ System.out.println("[SAMANPruner] beginning of getSplits"); LOG.info("[SAMANPruner] beginning of getSplits"); //System.out.println( "[SAMAN] " + files.length ); //LOG.info( "[SAMAN] " + files.length ); // Save the number of input files in the job-conf job.setLong(NUM_INPUT_FILES, files.length); long totalSize = 0; // compute total size for (FileStatus file : files) { // check we have valid files if (file.isDir()) { throw new IOException("Not a file: " + file.getPath()); } totalSize += file.getLen(); } //long minSize = Math.max(job.getLong("mapred.min.split.size", 1), // minSplitSize); // generate splits ArrayList<NetCDFFileSplit> splits = new ArrayList<NetCDFFileSplit>(numSplits); ArrayList<NetCDFFileSplit> finalSplits = new ArrayList<NetCDFFileSplit>(); NetworkTopology clusterMap = new NetworkTopology(); for (FileStatus file : files) { Path path = file.getPath(); int fileIndex = 0; int dimIndex = 0; if (queryType == QueryType.TIME || queryType == QueryType.NOLIMIT) { if (path.getName().contains("lat") || path.getName().contains("lon")) continue; } else if (queryType == QueryType.LAT) { if (!path.getName().contains("lat")) continue; } else if (queryType == QueryType.LON) { if (!path.getName().contains("lon")) continue; } if (queryType == QueryType.TIME) { String[] parts = path.getName().split("-"); fileIndex = Integer.valueOf(parts[1]); } else if (queryType == QueryType.LAT || queryType == QueryType.LON) { if (path.getName().contains("_")) { String[] parts = path.getName().split("_"); fileIndex = Integer.valueOf(parts[2]); dimIndex = Integer.valueOf(parts[0].substring(7)); } else { //dimIndex = Integer.valueOf(path.getName().substring(7)); String[] parts = path.getName().split("-"); dimIndex = Integer.valueOf(parts[1]); } } //LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] File name is : " + path.getName()); System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] File name is : " + path.getName()); FileSystem fs = path.getFileSystem(job); long length = file.getLen(); BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0, length); if ((length != 0) && isSplitable(fs, path)) { long blockSize = file.getBlockSize(); netInfo = getNetCDFInfo(path, fs, job); long recStart = netInfo.recStart; long[] chunkStarts = netInfo.chunkStarts; long smallSize = netInfo.smallRecSize; long recSize = netInfo.recSize; long splitSize = 0; int chunkIndex = 0; long bytesRemaining = chunkStarts[chunkStarts.length - 1] + recSize - recStart - 2 * smallSize; long thisStart = recStart; // file position long thisChunk = 0; long blockNo = 1; long numChunksPerKey = 0; if (queryType == QueryType.LAT) { long chunkSize = netInfo.timeLength * netInfo.lonLength * 4; numChunksPerKey = blockSize / chunkSize; } else if (queryType == QueryType.LON) { long chunkSize = netInfo.timeLength * netInfo.latLength * 4; numChunksPerKey = blockSize / chunkSize; } System.out.println("[SAMAN][NetCDFInputFormat][getSplits] numChunksPerKey = " + numChunksPerKey); //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => recStart = " + recStart + ", chunkStarts = " + chunkStarts + // ", smallSize = " + smallSize + ", recSize = " + recSize + ", bytesRemaining = " + bytesRemaining + // ", thisStart = " + thisStart); //System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => recStart = " + recStart + ", chunkStarts = " + chunkStarts + // ", smallSize = " + smallSize + ", recSize = " + recSize + ", bytesRemaining = " + bytesRemaining + // ", thisStart = " + thisStart); while (bytesRemaining > 0) { while (chunkIndex < chunkStarts.length && chunkStarts[chunkIndex] < blockNo * blockSize) { chunkIndex++; } long tempStart = thisStart; long endChunk; if (chunkIndex >= chunkStarts.length) { splitSize = chunkStarts[chunkStarts.length - 1] + recSize - thisStart - smallSize; //bytesRemaining should be 0 after this round } else { splitSize = chunkStarts[chunkIndex] - thisStart - smallSize; thisStart = chunkStarts[chunkIndex]; } endChunk = chunkIndex; blockNo++; //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize="+splitSize+", thisStart="+thisStart+ // ", endChunk="+endChunk+", blockNo="+blockNo); System.out.println("[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize=" + splitSize + ", thisStart=" + thisStart + ", endChunk=" + endChunk + ", blockNo=" + blockNo); String[] splitHosts = getSplitHosts(blkLocations, tempStart, splitSize, clusterMap); NetCDFFileSplit split = new NetCDFFileSplit(path, tempStart, splitSize, splitHosts); if (queryType == QueryType.TIME) { if ((topLimit < thisChunk + (fileIndex * netInfo.timeLength)) && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if ((bottomLimit > endChunk + (fileIndex * netInfo.timeLength)) && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } blockToNodes.put(split, splitHosts); // Put the nodes with the specified split into the node to block set System.out.println( "[SAMAN][NetCDFInputFormat][getSplits] Put the nodes with the specified split into the node to block set"); for (int i = 0; i < splitHosts.length; i++) { Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if (splitList == null) { splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put(splitHosts[i], splitList); } splitList.add(split); } System.out.println("[SAMAN][NetCDFInputFormat][getSplits] set start and end!"); split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); } else if (queryType == QueryType.LAT || queryType == QueryType.LON) { //System.out.println( "[SAMAN][NetCDFInputFormat][getSplits] file = " // + path.getName() + ", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit + ", dimIndex = " + dimIndex ); /* if( topLimit < dimIndex*numChunksPerKey && (topLimit != -1) ){ bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if( bottomLimit > dimIndex*numChunksPerKey && (bottomLimit != -1) ){ bytesRemaining -= splitSize; thisChunk = endChunk; continue; }*/ if (topLimit < thisChunk && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if (bottomLimit > endChunk && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } /* if ((topLimit < thisChunk) && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if ((bottomLimit > endChunk) && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } */ //split.getNetCDFFileSplit().endChunk = (long)topLimit; /* split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); */ // Put the block into the block to node set blockToNodes.put(split, splitHosts); // Put the nodes with the specified split into the node to block set for (int i = 0; i < splitHosts.length; i++) { Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if (splitList == null) { splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put(splitHosts[i], splitList); } splitList.add(split); } // For the test, we would assign everything statically. if (bottomLimit > thisChunk && (bottomLimit != -1)) { System.out .println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] startChunk = " + bottomLimit); split.getFileSplit().startChunk.add((long) bottomLimit); } else { split.getFileSplit().startChunk.add(thisChunk); } if (topLimit < endChunk && (topLimit != -1)) { System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] endChunk = " + endChunk); split.getFileSplit().endChunk.add((long) topLimit); } else { split.getFileSplit().endChunk.add(endChunk); } } else { if ((topLimit < thisChunk) && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if ((bottomLimit > endChunk) && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } blockToNodes.put(split, splitHosts); // Put the nodes with the specified split into the node to block set for (int i = 0; i < splitHosts.length; i++) { Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if (splitList == null) { splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put(splitHosts[i], splitList); } splitList.add(split); } split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); } splits.add(split); bytesRemaining -= splitSize; thisChunk = endChunk; //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk ); //System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk ); } } else if (length != 0) { String[] splitHosts = getSplitHosts(blkLocations, 0, length, clusterMap); //splits.add(new FileSplit(path, 0, length, splitHosts)); } else { //Create empty hosts array for zero length files //splits.add(new FileSplit(path, 0, length, new String[0])); } } // Now it's time to merge non-complete splits. // Check if each split has enough space to include another split too Set<String> completedNodes = new HashSet<String>(); ArrayList<NetCDFFileSplit> validBlocks = new ArrayList<NetCDFFileSplit>(); long curSplitSize = 0; Multiset<String> splitsPerNode = HashMultiset.create(); for (Iterator<Map.Entry<String, Set<NetCDFFileSplit>>> iter = nodeToBlocks.entrySet().iterator(); iter .hasNext();) { Map.Entry<String, Set<NetCDFFileSplit>> one = iter.next(); String node = one.getKey(); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] node is = " + node); // Skip the node if it has previously been marked as completed. if (completedNodes.contains(node)) { continue; } Set<NetCDFFileSplit> blocksInCurrentNode = one.getValue(); // for each block, copy it into validBlocks. Delete it from // blockToNodes so that the same block does not appear in // two different splits. Iterator<NetCDFFileSplit> oneBlockIter = blocksInCurrentNode.iterator(); while (oneBlockIter.hasNext()) { NetCDFFileSplit oneblock = oneBlockIter.next(); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "split is: " + oneblock.getFileSplit().getPath()); // Remove all blocks which may already have been assigned to other // splits. if (!blockToNodes.containsKey(oneblock)) { oneBlockIter.remove(); continue; } validBlocks.add(oneblock); if (queryType == QueryType.LAT) { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.lonLength * netInfo.timeLength; } else if (queryType == QueryType.LON) { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.latLength * netInfo.timeLength; } else if (queryType == QueryType.TIME) { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.latLength * netInfo.lonLength; } else { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.latLength * netInfo.lonLength; } blockToNodes.remove(oneblock); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] curSplitSize = " + curSplitSize); //curSplitSize += singleSplitSize; System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "Added to valid blocks!"); // if the accumulated split size exceeds the maximum, then // create this split. if (blockSize != 0 && curSplitSize >= blockSize) { // create an input split and add it to the splits array addCreatedSplit(finalSplits, Collections.singleton(node), validBlocks); //totalLength -= curSplitSize; System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "addCreatedSplit called!"); curSplitSize = 0; splitsPerNode.add(node); // Remove entries from blocksInNode so that we don't walk these // again. //blocksInCurrentNode.removeAll(validBlocks); validBlocks.clear(); // Done creating a single split for this node. Move on to the next // node so that splits are distributed across nodes. //break; } } if (!validBlocks.isEmpty()) { System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] validBlocks not empty!"); addCreatedSplit(finalSplits, Collections.singleton(node), validBlocks); curSplitSize = 0; splitsPerNode.add(node); blocksInCurrentNode.removeAll(validBlocks); validBlocks.clear(); } } Set<NetCDFFileSplit> singleSplitsSet = blockToNodes.keySet(); Iterator itrSingle = singleSplitsSet.iterator(); while (itrSingle.hasNext()) { NetCDFFileSplit temp = (NetCDFFileSplit) itrSingle.next(); addCreatedSingleSplit(finalSplits, temp.getLocations(), temp); } Iterator itr = finalSplits.iterator(); while (itr.hasNext()) { NetCDFFileSplit temp = (NetCDFFileSplit) itr.next(); String[] locations = temp.getFileSplit().getLocations(); String locationsString = ""; for (int i = 0; i < locations.length; i++) locationsString += locations[i]; String pathsString = ""; List<Path> paths = temp.getFileSplit().getPaths(); for (Path path : paths) pathsString += path.getName() + ","; String startsString = ""; List<Long> starts = temp.getFileSplit().startChunk; for (Long start : starts) startsString += (start + ","); String endsString = ""; List<Long> ends = temp.getFileSplit().endChunk; for (Long end : ends) endsString += (end + ","); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "locations=" + locationsString + "," + "paths=" + pathsString + "," + "starts=" + startsString + "," + "ends=" + endsString + ","); } return finalSplits.toArray(new NetCDFFileSplit[finalSplits.size()]); }
From source file:org.apache.hadoop.mapred.NetCDFInputFormatPartToMemoryMultiSplit.java
@Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { FileStatus[] files = listStatus(job); LOG.info("[SAMAN][NetCDFInputFormatPartToMemoryMultiSplit][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher")); System.out.println("[SAMAN][NetCDFInputFormatPartToMemoryMultiSplit][getSplits] hive query is: " + job.get(HIVE_QUERY, "Kossher")); /* Analyzing Query here */ String hiveQuery = job.get(HIVE_QUERY, "Kossher"); QueryType queryType = QueryType.NOLIMIT; // default mode if (hiveQuery.contains("where") || hiveQuery.contains("WHERE")) { if (hiveQuery.contains("time") || hiveQuery.contains("TIME")) { queryType = QueryType.TIME;/*from ww w . j ava2s .c om*/ } else if (hiveQuery.contains("lat") || hiveQuery.contains("LAT")) { queryType = QueryType.LAT; } else if (hiveQuery.contains("lon") || hiveQuery.contains("LON")) { queryType = QueryType.LON; } } float topLimit = -1; float bottomLimit = -1; if (queryType != QueryType.NOLIMIT) { if (hiveQuery.contains("<")) { String[] querySplitted = hiveQuery.split(" "); int i = Arrays.asList(querySplitted).indexOf("<"); topLimit = Float.valueOf(querySplitted[i + 1]); } if (hiveQuery.contains(">")) { String[] querySplitted = hiveQuery.split(" "); int i = Arrays.asList(querySplitted).indexOf(">"); bottomLimit = Float.valueOf(querySplitted[i + 1]); } } //System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndex] QueryType = " + queryType.toString() // +", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit ); //LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex] QueryType = " + queryType.toString() // + ", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit); /* End Analyzing Query here */ System.out.println("[SAMANPruner] beginning of getSplits"); LOG.info("[SAMANPruner] beginning of getSplits"); //System.out.println( "[SAMAN] " + files.length ); //LOG.info( "[SAMAN] " + files.length ); // Save the number of input files in the job-conf job.setLong(NUM_INPUT_FILES, files.length); long totalSize = 0; // compute total size for (FileStatus file : files) { // check we have valid files if (file.isDir()) { throw new IOException("Not a file: " + file.getPath()); } totalSize += file.getLen(); } //long minSize = Math.max(job.getLong("mapred.min.split.size", 1), // minSplitSize); // generate splits ArrayList<NetCDFFileSplit> splits = new ArrayList<NetCDFFileSplit>(numSplits); ArrayList<NetCDFFileSplit> finalSplits = new ArrayList<NetCDFFileSplit>(); NetworkTopology clusterMap = new NetworkTopology(); for (FileStatus file : files) { Path path = file.getPath(); int fileIndex = 0; int dimIndex = 0; //LOG.info("[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] File name is : " + path.getName()); System.out.println( "[SAMAN][NetCDFInputFormatPartToMemoryMultiSplit][getSplits] File name is : " + path.getName()); FileSystem fs = path.getFileSystem(job); long length = file.getLen(); BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0, length); if ((length != 0) && isSplitable(fs, path)) { long blockSize = file.getBlockSize(); netInfo = getNetCDFInfo(path, fs, job); long recStart = netInfo.recStart; long[] chunkStarts = netInfo.chunkStarts; long smallSize = netInfo.smallRecSize; long recSize = netInfo.recSize; long splitSize = 0; int chunkIndex = 0; long bytesRemaining = chunkStarts[chunkStarts.length - 1] + recSize - recStart - 2 * smallSize; long thisStart = recStart; // file position long thisChunk = 0; long blockNo = 1; long numChunksPerKey = 0; if (queryType == QueryType.LAT) { long chunkSize = netInfo.timeLength * netInfo.lonLength * 4; numChunksPerKey = blockSize / chunkSize; } else if (queryType == QueryType.LON) { long chunkSize = netInfo.timeLength * netInfo.latLength * 4; numChunksPerKey = blockSize / chunkSize; } System.out.println("[SAMAN][NetCDFInputFormat][getSplits] numChunksPerKey = " + numChunksPerKey); //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => recStart = " + recStart + ", chunkStarts = " + chunkStarts + // ", smallSize = " + smallSize + ", recSize = " + recSize + ", bytesRemaining = " + bytesRemaining + // ", thisStart = " + thisStart); //System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => recStart = " + recStart + ", chunkStarts = " + chunkStarts + // ", smallSize = " + smallSize + ", recSize = " + recSize + ", bytesRemaining = " + bytesRemaining + // ", thisStart = " + thisStart); while (bytesRemaining > 0) { while (chunkIndex < chunkStarts.length && chunkStarts[chunkIndex] < blockNo * blockSize) { chunkIndex++; } long tempStart = thisStart; long endChunk; if (chunkIndex >= chunkStarts.length) { splitSize = chunkStarts[chunkStarts.length - 1] + recSize - thisStart - smallSize; //bytesRemaining should be 0 after this round } else { splitSize = chunkStarts[chunkIndex] - thisStart - smallSize; thisStart = chunkStarts[chunkIndex]; } endChunk = chunkIndex; blockNo++; //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize="+splitSize+", thisStart="+thisStart+ // ", endChunk="+endChunk+", blockNo="+blockNo); System.out.println("[SAMAN] NetCDFInputFormatPruner.getSplits => splitSize=" + splitSize + ", thisStart=" + thisStart + ", endChunk=" + endChunk + ", blockNo=" + blockNo); String[] splitHosts = getSplitHosts(blkLocations, tempStart, splitSize, clusterMap); NetCDFFileSplit split = new NetCDFFileSplit(path, tempStart, splitSize, splitHosts); split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); if (queryType == QueryType.TIME) { split.getFileSplit().timeStartLimit.add((long) bottomLimit); split.getFileSplit().timeEndLimit.add((long) topLimit); split.getFileSplit().latStartLimit.add((long) -1); split.getFileSplit().latEndLimit.add((long) -1); split.getFileSplit().lonStartLimit.add((long) -1); split.getFileSplit().lonEndLimit.add((long) -1); } else if (queryType == QueryType.LAT) { split.getFileSplit().timeStartLimit.add((long) -1); split.getFileSplit().timeEndLimit.add((long) -1); split.getFileSplit().latStartLimit.add((long) bottomLimit); split.getFileSplit().latEndLimit.add((long) topLimit); split.getFileSplit().lonStartLimit.add((long) -1); split.getFileSplit().lonEndLimit.add((long) -1); } else if (queryType == QueryType.LON) { split.getFileSplit().timeStartLimit.add((long) -1); split.getFileSplit().timeEndLimit.add((long) -1); split.getFileSplit().latStartLimit.add((long) -1); split.getFileSplit().latEndLimit.add((long) -1); split.getFileSplit().lonStartLimit.add((long) bottomLimit); split.getFileSplit().lonEndLimit.add((long) topLimit); } blockToNodes.put(split, splitHosts); System.out.println( "[SAMAN][NetCDFInputFormat][getSplits] Put the nodes with the specified split into the node to block set"); for (int i = 0; i < splitHosts.length; i++) { Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if (splitList == null) { splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put(splitHosts[i], splitList); } splitList.add(split); } /* if( queryType == QueryType.TIME ) { if ((topLimit < thisChunk + (fileIndex*netInfo.timeLength)) && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if ((bottomLimit > endChunk + (fileIndex*netInfo.timeLength)) && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } blockToNodes.put( split, splitHosts ); // Put the nodes with the specified split into the node to block set System.out.println( "[SAMAN][NetCDFInputFormat][getSplits] Put the nodes with the specified split into the node to block set" ); for( int i = 0; i < splitHosts.length; i++ ){ Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if( splitList == null ){ splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put( splitHosts[i], splitList ); } splitList.add( split ); } System.out.println("[SAMAN][NetCDFInputFormat][getSplits] set start and end!" ); split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); } else if( queryType == QueryType.LAT || queryType == QueryType.LON ){ //System.out.println( "[SAMAN][NetCDFInputFormat][getSplits] file = " // + path.getName() + ", topLimit = " + topLimit + ", bottomLimit = " + bottomLimit + ", dimIndex = " + dimIndex ); */ /* if( topLimit < dimIndex*numChunksPerKey && (topLimit != -1) ){ bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if( bottomLimit > dimIndex*numChunksPerKey && (bottomLimit != -1) ){ bytesRemaining -= splitSize; thisChunk = endChunk; continue; }*/ /* if (topLimit < thisChunk && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if (bottomLimit > endChunk && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } */ /* if ((topLimit < thisChunk) && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if ((bottomLimit > endChunk) && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } */ //split.getNetCDFFileSplit().endChunk = (long)topLimit; /* split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); */ // Put the block into the block to node set /* blockToNodes.put( split, splitHosts ); // Put the nodes with the specified split into the node to block set for( int i = 0; i < splitHosts.length; i++ ){ Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if( splitList == null ){ splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put( splitHosts[i], splitList ); } splitList.add( split ); } // For the test, we would assign everything statically. if( bottomLimit > thisChunk && (bottomLimit != -1) ){ System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] startChunk = " + bottomLimit ); split.getFileSplit().startChunk.add((long)bottomLimit); }else{ split.getFileSplit().startChunk.add(thisChunk); } if( topLimit < endChunk && (topLimit != -1) ){ System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndex][getSplits] endChunk = " + endChunk ); split.getFileSplit().endChunk.add((long)topLimit); }else{ split.getFileSplit().endChunk.add(endChunk); } } else { if ((topLimit < thisChunk) && (topLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } if ((bottomLimit > endChunk) && (bottomLimit != -1)) { bytesRemaining -= splitSize; thisChunk = endChunk; continue; } blockToNodes.put( split, splitHosts ); // Put the nodes with the specified split into the node to block set for( int i = 0; i < splitHosts.length; i++ ){ Set<NetCDFFileSplit> splitList = nodeToBlocks.get(splitHosts[i]); if( splitList == null ){ splitList = new LinkedHashSet<NetCDFFileSplit>(); nodeToBlocks.put( splitHosts[i], splitList ); } splitList.add( split ); } split.getFileSplit().startChunk.add(thisChunk); split.getFileSplit().endChunk.add(endChunk); } */ splits.add(split); bytesRemaining -= splitSize; thisChunk = endChunk; //LOG.info( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk ); //System.out.println( "[SAMAN] NetCDFInputFormatPruner.getSplits => bytesRemaining="+bytesRemaining+", thisChunk="+thisChunk ); } } else if (length != 0) { String[] splitHosts = getSplitHosts(blkLocations, 0, length, clusterMap); //splits.add(new FileSplit(path, 0, length, splitHosts)); } else { //Create empty hosts array for zero length files //splits.add(new FileSplit(path, 0, length, new String[0])); } } // Now it's time to merge non-complete splits. // Check if each split has enough space to include another split too Set<String> completedNodes = new HashSet<String>(); ArrayList<NetCDFFileSplit> validBlocks = new ArrayList<NetCDFFileSplit>(); long curSplitSize = 0; Multiset<String> splitsPerNode = HashMultiset.create(); for (Iterator<Map.Entry<String, Set<NetCDFFileSplit>>> iter = nodeToBlocks.entrySet().iterator(); iter .hasNext();) { Map.Entry<String, Set<NetCDFFileSplit>> one = iter.next(); String node = one.getKey(); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] node is = " + node); // Skip the node if it has previously been marked as completed. if (completedNodes.contains(node)) { continue; } Set<NetCDFFileSplit> blocksInCurrentNode = one.getValue(); // for each block, copy it into validBlocks. Delete it from // blockToNodes so that the same block does not appear in // two different splits. Iterator<NetCDFFileSplit> oneBlockIter = blocksInCurrentNode.iterator(); while (oneBlockIter.hasNext()) { NetCDFFileSplit oneblock = oneBlockIter.next(); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "split is: " + oneblock.getFileSplit().getPath()); // Remove all blocks which may already have been assigned to other // splits. if (!blockToNodes.containsKey(oneblock)) { oneBlockIter.remove(); continue; } validBlocks.add(oneblock); if (queryType == QueryType.LAT) { curSplitSize += (oneblock.getFileSplit().latEndLimit.get(0) - oneblock.getFileSplit().latStartLimit.get(0)) * 4 * netInfo.lonLength * netInfo.timeLength; } else if (queryType == QueryType.LON) { curSplitSize += (oneblock.getFileSplit().lonEndLimit.get(0) - oneblock.getFileSplit().lonStartLimit.get(0)) * 4 * netInfo.latLength * netInfo.timeLength; } else if (queryType == QueryType.TIME) { curSplitSize += (oneblock.getFileSplit().timeEndLimit.get(0) - oneblock.getFileSplit().timeStartLimit.get(0)) * 4 * netInfo.latLength * netInfo.lonLength; } else { curSplitSize += (oneblock.getFileSplit().endChunk.get(0) - oneblock.getFileSplit().startChunk.get(0)) * 4 * netInfo.latLength * netInfo.lonLength; } blockToNodes.remove(oneblock); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] curSplitSize = " + curSplitSize); //curSplitSize += singleSplitSize; //System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + // "Added to valid blocks!" ); // if the accumulated split size exceeds the maximum, then // create this split. if (blockSize != 0 && curSplitSize >= blockSize) { // create an input split and add it to the splits array addCreatedSplit(finalSplits, Collections.singleton(node), validBlocks); //totalLength -= curSplitSize; //System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + // "addCreatedSplit called!" ); curSplitSize = 0; splitsPerNode.add(node); // Remove entries from blocksInNode so that we don't walk these // again. //blocksInCurrentNode.removeAll(validBlocks); validBlocks.clear(); // Done creating a single split for this node. Move on to the next // node so that splits are distributed across nodes. //break; } } if (!validBlocks.isEmpty()) { //System.out.println( "[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] validBlocks not empty!" ); addCreatedSplit(finalSplits, Collections.singleton(node), validBlocks); curSplitSize = 0; splitsPerNode.add(node); blocksInCurrentNode.removeAll(validBlocks); validBlocks.clear(); } } Set<NetCDFFileSplit> singleSplitsSet = blockToNodes.keySet(); Iterator itrSingle = singleSplitsSet.iterator(); while (itrSingle.hasNext()) { NetCDFFileSplit temp = (NetCDFFileSplit) itrSingle.next(); addCreatedSingleSplit(finalSplits, temp.getLocations(), temp); } Iterator itr = finalSplits.iterator(); while (itr.hasNext()) { NetCDFFileSplit temp = (NetCDFFileSplit) itr.next(); String[] locations = temp.getFileSplit().getLocations(); String locationsString = ""; for (int i = 0; i < locations.length; i++) locationsString += locations[i]; String pathsString = ""; List<Path> paths = temp.getFileSplit().getPaths(); for (Path path : paths) pathsString += path.getName() + ","; String startsString = ""; List<Long> starts = temp.getFileSplit().startChunk; for (Long start : starts) startsString += (start + ","); String endsString = ""; List<Long> ends = temp.getFileSplit().endChunk; for (Long end : ends) endsString += (end + ","); System.out.println("[SAMAN][NetCDFInputFormatPrunerByFileIndexMultiFile][getSplits] " + "locations=" + locationsString + "," + "paths=" + pathsString + "," + "starts=" + startsString + "," + "ends=" + endsString + ","); } return finalSplits.toArray(new NetCDFFileSplit[finalSplits.size()]); }
From source file:com.zimbra.cs.account.ProvUtil.java
/** * Convert an array of the form:/*from w w w .j av a 2 s. c o m*/ * * a1 v1 a2 v2 a2 v3 * * to a map of the form: * * a1 -> v1 a2 -> [v2, v3] * * For binary attribute, the argument following an attribute name will be treated as a file path and value for the * attribute will be the base64 encoded string of the content of the file. */ private Map<String, Object> keyValueArrayToMultiMap(String[] args, int offset, boolean isCreateCmd) throws IOException, ServiceException { AttributeManager attrMgr = AttributeManager.getInstance(); Map<String, Object> attrs = new HashMap<String, Object>(); String safeguarded_attrs_prop = LC.get("zmprov_safeguarded_attrs"); Set<String> safeguarded_attrs = safeguarded_attrs_prop == null ? Sets.<String>newHashSet() : Sets.newHashSet(safeguarded_attrs_prop.toLowerCase().split(",")); Multiset<String> multiValAttrsToCheck = HashMultiset.create(); for (int i = offset; i < args.length; i += 2) { String n = args[i]; if (i + 1 >= args.length) { throw new IllegalArgumentException("not enough arguments"); } String v = args[i + 1]; String attrName = n; if (n.charAt(0) == '+' || n.charAt(0) == '-') { attrName = attrName.substring(1); } else if (safeguarded_attrs.contains(attrName.toLowerCase()) && attrMgr.isMultiValued(attrName)) { multiValAttrsToCheck.add(attrName.toLowerCase()); } if (needsBinaryIO(attrMgr, attrName) && v.length() > 0) { File file = new File(v); byte[] bytes = ByteUtil.getContent(file); v = ByteUtil.encodeLDAPBase64(bytes); } StringUtil.addToMultiMap(attrs, n, v); } if (!allowMultiValuedAttrReplacement && !isCreateCmd) { for (Multiset.Entry<String> entry : multiValAttrsToCheck.entrySet()) { if (entry.getCount() == 1) { // If multiple values are being assigned to an attr as part of the same command // then we don't consider it an unsafe replacement printError("error: cannot replace multi-valued attr value unless -r is specified"); System.exit(2); } } } return attrs; }
From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java
/** * Two steps insertion:// w w w. ja v a 2 s . c o m * First check that the variant and study exists making an update. * For those who doesn't exist, pushes a study with the file and genotype information * <p> * The documents that throw a "dup key" exception are those variants that exist and have the study. * Then, only for those variants, make a second update. * <p> * *An interesting idea would be to invert this actions depending on the number of already inserted variants. * * @param data Variants to insert * @param fileId File ID * @param variantConverter Variant converter to be used * @param variantSourceEntryConverter Variant source converter to be used * @param studyConfiguration Configuration for the study * @param loadedSampleIds Other loaded sampleIds EXCEPT those that are going to be loaded * @return QueryResult object */ QueryResult<MongoDBVariantWriteResult> insert(List<Variant> data, int fileId, DocumentToVariantConverter variantConverter, DocumentToStudyVariantEntryConverter variantSourceEntryConverter, StudyConfiguration studyConfiguration, List<Integer> loadedSampleIds) { MongoDBVariantWriteResult writeResult = new MongoDBVariantWriteResult(); long startTime = System.currentTimeMillis(); if (data.isEmpty()) { return new QueryResult<>("insertVariants", 0, 1, 1, "", "", Collections.singletonList(writeResult)); } List<Bson> queries = new ArrayList<>(data.size()); List<Bson> updates = new ArrayList<>(data.size()); // Use a multiset instead of a normal set, to keep tracking of duplicated variants Multiset<String> nonInsertedVariants = HashMultiset.create(); String fileIdStr = Integer.toString(fileId); // List<String> extraFields = studyConfiguration.getAttributes().getAsStringList(VariantStorageManager.Options.EXTRA_GENOTYPE_FIELDS // .key()); boolean excludeGenotypes = studyConfiguration.getAttributes().getBoolean( VariantStorageManager.Options.EXCLUDE_GENOTYPES.key(), VariantStorageManager.Options.EXCLUDE_GENOTYPES.defaultValue()); long nanoTime = System.nanoTime(); Map missingSamples = Collections.emptyMap(); String defaultGenotype = studyConfiguration.getAttributes().getString(DEFAULT_GENOTYPE.key(), ""); if (defaultGenotype.equals(DocumentToSamplesConverter.UNKNOWN_GENOTYPE)) { logger.debug("Do not need fill gaps. DefaultGenotype is UNKNOWN_GENOTYPE({}).", DocumentToSamplesConverter.UNKNOWN_GENOTYPE); } else if (excludeGenotypes) { logger.debug("Do not need fill gaps. Excluding genotypes."); } else if (!loadedSampleIds.isEmpty()) { missingSamples = new Document(DocumentToSamplesConverter.UNKNOWN_GENOTYPE, loadedSampleIds); // ?/? } // List<Object> missingOtherValues = new ArrayList<>(loadedSampleIds.size()); // for (int i = 0; i < loadedSampleIds.size(); i++) { // missingOtherValues.add(DBObjectToSamplesConverter.UNKNOWN_FIELD); // } for (Variant variant : data) { if (variant.getType().equals(VariantType.NO_VARIATION)) { //Storage-MongoDB is not able to store NON VARIANTS writeResult.setSkippedVariants(writeResult.getSkippedVariants() + 1); continue; } else if (variant.getType().equals(VariantType.SYMBOLIC)) { logger.warn("Skip symbolic variant " + variant.toString()); writeResult.setSkippedVariants(writeResult.getSkippedVariants() + 1); continue; } String id = variantConverter.buildStorageId(variant); for (StudyEntry studyEntry : variant.getStudies()) { if (studyEntry.getFiles().size() == 0 || !studyEntry.getFiles().get(0).getFileId().equals(fileIdStr)) { continue; } int studyId = studyConfiguration.getStudyId(); Document study = variantSourceEntryConverter.convertToStorageType(studyEntry); Document genotypes = study.get(DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, Document.class); if (genotypes != null) { //If genotypes is null, genotypes are not suppose to be loaded genotypes.putAll(missingSamples); //Add missing samples // for (String extraField : extraFields) { // List<Object> otherFieldValues = (List<Object>) study.get(extraField.toLowerCase()); // otherFieldValues.addAll(0, missingOtherValues); // } } Document push = new Document(DocumentToVariantConverter.STUDIES_FIELD, study); Document update = new Document().append("$push", push).append("$setOnInsert", variantConverter.convertToStorageType(variant)); if (variant.getIds() != null && !variant.getIds().isEmpty() && !variant.getIds().iterator().next().isEmpty()) { update.put("$addToSet", new Document(DocumentToVariantConverter.IDS_FIELD, new Document("$each", variant.getIds()))); } // { _id: <variant_id>, "studies.sid": {$ne: <studyId> } } //If the variant exists and contains the study, this find will fail, will try to do the upsert, and throw a // duplicated key exception. queries.add(new Document("_id", id).append( DocumentToVariantConverter.STUDIES_FIELD + "." + DocumentToStudyVariantEntryConverter.STUDYID_FIELD, new Document("$ne", studyId))); updates.add(update); } } // if (!queries.isEmpty()) { QueryOptions options = new QueryOptions(UPSERT, true); options.put(MULTI, false); int newDocuments; int updatedObjects; try { BulkWriteResult bulkWriteResult; bulkWriteResult = variantsCollection.update(queries, updates, options).first(); newDocuments = bulkWriteResult.getUpserts().size(); updatedObjects = bulkWriteResult.getModifiedCount(); } catch (MongoBulkWriteException e) { BulkWriteResult bulkWriteResult; bulkWriteResult = e.getWriteResult(); newDocuments = bulkWriteResult.getUpserts().size(); updatedObjects = bulkWriteResult.getModifiedCount(); for (BulkWriteError writeError : e.getWriteErrors()) { if (writeError.getCode() == 11000) { //Dup Key error code Matcher matcher = writeResultErrorPattern.matcher(writeError.getMessage()); if (matcher.find()) { String id = matcher.group(1); nonInsertedVariants.add(id); } else { throw e; } } else { throw e; } } } writeResult.setNewVariants(newDocuments); writeResult.setUpdatedVariants(updatedObjects); // writeResult.setNewDocuments(data.size() - nonInsertedVariants.size() - writeResult.getSkippedVariants()); queries.clear(); updates.clear(); } writeResult.setNewVariantsNanoTime(System.nanoTime() - nanoTime); nanoTime = System.nanoTime(); for (Variant variant : data) { variant.setAnnotation(null); String id = variantConverter.buildStorageId(variant); if (nonInsertedVariants != null && !nonInsertedVariants.contains(id)) { continue; //Already inserted variant } for (StudyEntry studyEntry : variant.getStudies()) { if (studyEntry.getFiles().size() == 0 || !studyEntry.getFiles().get(0).getFileId().equals(fileIdStr)) { continue; } Document studyObject = variantSourceEntryConverter.convertToStorageType(studyEntry); Document genotypes = studyObject.get(DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, Document.class); Document push = new Document(); if (!excludeGenotypes) { if (genotypes != null) { //If genotypes is null, genotypes are not suppose to be loaded for (String genotype : genotypes.keySet()) { push.put( DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD + "." + genotype, new Document("$each", genotypes.get(genotype))); } // for (String extraField : extraFields) { // List values = (List) studyObject.get(extraField.toLowerCase()); // push.put(DBObjectToVariantConverter.STUDIES_FIELD + ".$." + extraField.toLowerCase(), // new Document("$each", values).append("$position", loadedSampleIds.size())); // } } else { push.put( DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, Collections.emptyMap()); } } push.put( DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.FILES_FIELD, ((List) studyObject.get(DocumentToStudyVariantEntryConverter.FILES_FIELD)).get(0)); Document update = new Document(new Document("$push", push)); queries.add(new Document("_id", id) .append(DocumentToVariantConverter.STUDIES_FIELD + '.' + DocumentToStudyVariantEntryConverter.STUDYID_FIELD, studyConfiguration.getStudyId()) .append(DocumentToVariantConverter.STUDIES_FIELD + '.' + DocumentToStudyVariantEntryConverter.FILES_FIELD + '.' + DocumentToStudyVariantEntryConverter.FILEID_FIELD, new Document("$ne", fileId))); updates.add(update); } } writeResult.setExistingVariantsNanoTime(System.nanoTime() - nanoTime); if (!queries.isEmpty()) { QueryOptions options = new QueryOptions(UPSERT, false); options.put(MULTI, false); QueryResult<BulkWriteResult> update = variantsCollection.update(queries, updates, options); // Can happen that nonInsertedVariantsNum != queries.size() != nonInsertedVariants.size() if there was // a duplicated variant. writeResult.setNonInsertedVariants(nonInsertedVariants.size() - update.first().getMatchedCount()); writeResult.setUpdatedVariants(writeResult.getUpdatedVariants() + update.first().getModifiedCount()); } return new QueryResult<>("insertVariants", ((int) (System.currentTimeMillis() - startTime)), 1, 1, "", "", Collections.singletonList(writeResult)); }
From source file:org.opencb.opencga.storage.mongodb.variant.adaptors.VariantMongoDBAdaptor.java
/** * Two steps insertion:// w ww.j a va 2 s .c o m * First check that the variant and study exists making an update. * For those who doesn't exist, pushes a study with the file and genotype information * <p> * The documents that throw a "dup key" exception are those variants that exist and have the study. * Then, only for those variants, make a second update. * <p> * *An interesting idea would be to invert this actions depending on the number of already inserted variants. * * @param data Variants to insert * @param fileId File ID * @param variantConverter Variant converter to be used * @param variantSourceEntryConverter Variant source converter to be used * @param studyConfiguration Configuration for the study * @param loadedSampleIds Other loaded sampleIds EXCEPT those that are going to be loaded * @return QueryResult object */ QueryResult<MongoDBVariantWriteResult> insert(List<Variant> data, int fileId, DocumentToVariantConverter variantConverter, DocumentToStudyVariantEntryConverter variantSourceEntryConverter, StudyConfiguration studyConfiguration, List<Integer> loadedSampleIds) { MongoDBVariantWriteResult writeResult = new MongoDBVariantWriteResult(); long startTime = System.currentTimeMillis(); if (data.isEmpty()) { return new QueryResult<>("insertVariants", 0, 1, 1, "", "", Collections.singletonList(writeResult)); } List<Bson> queries = new ArrayList<>(data.size()); List<Bson> updates = new ArrayList<>(data.size()); // Use a multiset instead of a normal set, to keep tracking of duplicated variants Multiset<String> nonInsertedVariants = HashMultiset.create(); String fileIdStr = Integer.toString(fileId); // List<String> extraFields = studyConfiguration.getAttributes().getAsStringList(VariantStorageEngine.Options.EXTRA_GENOTYPE_FIELDS // .key()); boolean excludeGenotypes = studyConfiguration.getAttributes().getBoolean( VariantStorageEngine.Options.EXCLUDE_GENOTYPES.key(), VariantStorageEngine.Options.EXCLUDE_GENOTYPES.defaultValue()); long nanoTime = System.nanoTime(); Map missingSamples = Collections.emptyMap(); String defaultGenotype = studyConfiguration.getAttributes().getString(DEFAULT_GENOTYPE.key(), ""); if (defaultGenotype.equals(DocumentToSamplesConverter.UNKNOWN_GENOTYPE)) { logger.debug("Do not need fill gaps. DefaultGenotype is UNKNOWN_GENOTYPE({}).", DocumentToSamplesConverter.UNKNOWN_GENOTYPE); } else if (excludeGenotypes) { logger.debug("Do not need fill gaps. Excluding genotypes."); } else if (!loadedSampleIds.isEmpty()) { missingSamples = new Document(DocumentToSamplesConverter.UNKNOWN_GENOTYPE, loadedSampleIds); // ?/? } // List<Object> missingOtherValues = new ArrayList<>(loadedSampleIds.size()); // for (int i = 0; i < loadedSampleIds.size(); i++) { // missingOtherValues.add(DBObjectToSamplesConverter.UNKNOWN_FIELD); // } for (Variant variant : data) { if (variant.getType().equals(VariantType.NO_VARIATION)) { //Storage-MongoDB is not able to store NON VARIANTS writeResult.setSkippedVariants(writeResult.getSkippedVariants() + 1); continue; } else if (variant.getType().equals(VariantType.SYMBOLIC)) { logger.warn("Skip symbolic variant " + variant.toString()); writeResult.setSkippedVariants(writeResult.getSkippedVariants() + 1); continue; } String id = variantConverter.buildStorageId(variant); for (StudyEntry studyEntry : variant.getStudies()) { if (studyEntry.getFiles().size() == 0 || !studyEntry.getFiles().get(0).getFileId().equals(fileIdStr)) { continue; } int studyId = studyConfiguration.getStudyId(); Document study = variantSourceEntryConverter.convertToStorageType(variant, studyEntry); Document genotypes = study.get(DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, Document.class); if (genotypes != null) { //If genotypes is null, genotypes are not suppose to be loaded genotypes.putAll(missingSamples); //Add missing samples // for (String extraField : extraFields) { // List<Object> otherFieldValues = (List<Object>) study.get(extraField.toLowerCase()); // otherFieldValues.addAll(0, missingOtherValues); // } } Document push = new Document(DocumentToVariantConverter.STUDIES_FIELD, study); Document update = new Document().append("$push", push).append("$setOnInsert", variantConverter.convertToStorageType(variant)); if (variant.getIds() != null && !variant.getIds().isEmpty() && !variant.getIds().iterator().next().isEmpty()) { update.put("$addToSet", new Document(DocumentToVariantConverter.IDS_FIELD, new Document("$each", variant.getIds()))); } // { _id: <variant_id>, "studies.sid": {$ne: <studyId> } } //If the variant exists and contains the study, this find will fail, will try to do the upsert, and throw a // duplicated key exception. queries.add(new Document("_id", id).append( DocumentToVariantConverter.STUDIES_FIELD + "." + DocumentToStudyVariantEntryConverter.STUDYID_FIELD, new Document("$ne", studyId))); updates.add(update); } } // if (!queries.isEmpty()) { QueryOptions options = new QueryOptions(UPSERT, true); options.put(MULTI, false); int newDocuments; int updatedObjects; try { BulkWriteResult bulkWriteResult; bulkWriteResult = variantsCollection.update(queries, updates, options).first(); newDocuments = bulkWriteResult.getUpserts().size(); updatedObjects = bulkWriteResult.getModifiedCount(); } catch (MongoBulkWriteException e) { BulkWriteResult bulkWriteResult; bulkWriteResult = e.getWriteResult(); newDocuments = bulkWriteResult.getUpserts().size(); updatedObjects = bulkWriteResult.getModifiedCount(); for (BulkWriteError writeError : e.getWriteErrors()) { if (writeError.getCode() == 11000) { //Dup Key error code Matcher matcher = writeResultErrorPattern.matcher(writeError.getMessage()); if (matcher.find()) { String id = matcher.group(1); nonInsertedVariants.add(id); } else { throw e; } } else { throw e; } } } writeResult.setNewVariants(newDocuments); writeResult.setUpdatedVariants(updatedObjects); // writeResult.setNewDocuments(data.size() - nonInsertedVariants.size() - writeResult.getSkippedVariants()); queries.clear(); updates.clear(); } writeResult.setNewVariantsNanoTime(System.nanoTime() - nanoTime); nanoTime = System.nanoTime(); for (Variant variant : data) { variant.setAnnotation(null); String id = variantConverter.buildStorageId(variant); if (nonInsertedVariants != null && !nonInsertedVariants.contains(id)) { continue; //Already inserted variant } for (StudyEntry studyEntry : variant.getStudies()) { if (studyEntry.getFiles().size() == 0 || !studyEntry.getFiles().get(0).getFileId().equals(fileIdStr)) { continue; } Document studyObject = variantSourceEntryConverter.convertToStorageType(variant, studyEntry); Document genotypes = studyObject.get(DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, Document.class); Document push = new Document(); if (!excludeGenotypes) { if (genotypes != null) { //If genotypes is null, genotypes are not suppose to be loaded for (String genotype : genotypes.keySet()) { push.put( DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD + "." + genotype, new Document("$each", genotypes.get(genotype))); } // for (String extraField : extraFields) { // List values = (List) studyObject.get(extraField.toLowerCase()); // push.put(DBObjectToVariantConverter.STUDIES_FIELD + ".$." + extraField.toLowerCase(), // new Document("$each", values).append("$position", loadedSampleIds.size())); // } } else { push.put( DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, Collections.emptyMap()); } } push.put( DocumentToVariantConverter.STUDIES_FIELD + ".$." + DocumentToStudyVariantEntryConverter.FILES_FIELD, ((List) studyObject.get(DocumentToStudyVariantEntryConverter.FILES_FIELD)).get(0)); Document update = new Document(new Document("$push", push)); queries.add(new Document("_id", id) .append(DocumentToVariantConverter.STUDIES_FIELD + '.' + DocumentToStudyVariantEntryConverter.STUDYID_FIELD, studyConfiguration.getStudyId()) .append(DocumentToVariantConverter.STUDIES_FIELD + '.' + DocumentToStudyVariantEntryConverter.FILES_FIELD + '.' + DocumentToStudyVariantEntryConverter.FILEID_FIELD, new Document("$ne", fileId))); updates.add(update); } } writeResult.setExistingVariantsNanoTime(System.nanoTime() - nanoTime); if (!queries.isEmpty()) { QueryOptions options = new QueryOptions(UPSERT, false); options.put(MULTI, false); QueryResult<BulkWriteResult> update = variantsCollection.update(queries, updates, options); // Can happen that nonInsertedVariantsNum != queries.size() != nonInsertedVariants.size() if there was // a duplicated variant. writeResult.setNonInsertedVariants(nonInsertedVariants.size() - update.first().getMatchedCount()); writeResult.setUpdatedVariants(writeResult.getUpdatedVariants() + update.first().getModifiedCount()); } return new QueryResult<>("insertVariants", ((int) (System.currentTimeMillis() - startTime)), 1, 1, "", "", Collections.singletonList(writeResult)); }