public static void callPlayerItemBreakEvent(EntityPlayerMP human, ItemStack brokenItem) {
   BukkitItemStack item = new BukkitItemStack(brokenItem);
   PlayerItemBreakEvent event =
       new PlayerItemBreakEvent(
           (Player) BukkitEntity.getEntity((BukkitServer) Bukkit.getServer(), human), item);
   Bukkit.getPluginManager().callEvent(event);
 }
  private boolean disableWorld(CommandSender sender, String worldName) {
    if (worldName == null) return false;

    for (World world : Bukkit.getWorlds()) {
      if (!world.getName().equalsIgnoreCase(worldName)) continue;

      if (settings == null) settings = new Settings();

      settings.worldsToUnload.remove(worldName);
      settings.worldsToDisable.add(worldName);

      Bukkit.getServer().unloadWorld(world, true);

      String msg = "NoPreload";
      msg = String.format("%s[%s]", ChatColor.DARK_AQUA, msg);
      msg = String.format("%s%s ", msg, ChatColor.WHITE);
      msg += worldName + " has been disabled.";
      sender.sendMessage(msg);

      return true;
    }

    String msg = "NoPreload";
    msg = String.format("%s[%s]", ChatColor.DARK_AQUA, msg);
    msg = String.format("%s%s ", msg, ChatColor.WHITE);
    msg += worldName + " does not appear to exist.";
    sender.sendMessage(msg);
    return true;
  }
Exemple #3
0
 public static ItemStack addGlow(ItemStack item) {
   switch (Version.getVersion()) {
     case TOO_NEW:
       Bukkit.getLogger()
           .log(
               Level.SEVERE,
               "[Crazy Crates]>> Your server is too new for this plugin. "
                   + "Please update or remove this plugin to stop further Errors.");
       break;
     case v1_10_R1:
       return NMS_v1_10_R1.addGlow(item);
     case v1_9_R2:
       return NMS_v1_9_R2.addGlow(item);
     case v1_9_R1:
       return NMS_v1_9_R1.addGlow(item);
     case v1_8_R3:
       return NMS_v1_8_R3.addGlow(item);
     case v1_8_R2:
       return NMS_v1_8_R2.addGlow(item);
     case v1_8_R1:
       return NMS_v1_8_R1.addGlow(item);
     case TOO_OLD:
       Bukkit.getLogger()
           .log(
               Level.SEVERE,
               "[Crazy Crates]>> Your server is too far out of date. "
                   + "Please update or remove this plugin to stop further Errors.");
       break;
   }
   return item;
 }
Exemple #4
0
  public static Machine fromString(String input) {
    JSONObject machine = null;
    try {
      machine = (JSONObject) new JSONParser().parse(input);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    JSONObject cutObj = (JSONObject) machine.get("cuttingface");
    Block cutFace =
        Bukkit.getWorld((String) cutObj.get("world"))
            .getBlockAt(
                (Integer) getNumber((String) cutObj.get("x")),
                (Integer) getNumber((String) cutObj.get("y")),
                (Integer) getNumber((String) cutObj.get("z")));

    OfflinePlayer owner = Bukkit.getOfflinePlayer(UUID.fromString((String) machine.get("owner")));

    JSONObject dis = (JSONObject) machine.get("dispenser");
    Block dispenser =
        Bukkit.getWorld((String) dis.get("world"))
            .getBlockAt(
                (Integer) getNumber((String) dis.get("x")),
                (Integer) getNumber((String) dis.get("y")),
                (Integer) getNumber((String) dis.get("z")));
    return new Machine(cutFace, dispenser, owner);
  }
Exemple #5
0
  /** Generic method that posts a plugin to the metrics website */
  private void postPlugin(boolean isPing) throws IOException {
    // The plugin's description file containg all of the plugin data such as name, version, author,
    // etc
    final PluginDescriptionFile description = this.plugin.getDescription();

    // Construct the post data
    String data =
        Metrics.encode("guid")
            + '='
            + Metrics.encode(this.guid)
            + Metrics.encodeDataPair("version", description.getVersion())
            + Metrics.encodeDataPair("server", Bukkit.getVersion())
            + Metrics.encodeDataPair(
                "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length))
            + Metrics.encodeDataPair("revision", String.valueOf(Metrics.REVISION));

    // If we're pinging, append it
    if (isPing) {
      data += Metrics.encodeDataPair("ping", "true");
    }

    // Create the url
    final URL url =
        new URL(
            Metrics.BASE_URL
                + String.format(Metrics.REPORT_URL, this.plugin.getDescription().getName()));

    // Connect to the website
    URLConnection connection;

    // Mineshafter creates a socks proxy, so we can safely bypass it
    // It does not reroute POST requests so we need to go around it
    if (this.isMineshafterPresent()) {
      connection = url.openConnection(Proxy.NO_PROXY);
    } else {
      connection = url.openConnection();
    }

    connection.setDoOutput(true);

    // Write the data
    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(data);
    writer.flush();

    // Now read the response
    final BufferedReader reader =
        new BufferedReader(new InputStreamReader(connection.getInputStream()));
    final String response = reader.readLine();

    // close resources
    writer.close();
    reader.close();

    if (response.startsWith("ERR")) {
      throw new IOException(response); // Throw the exception
    }
    // if (response.startsWith("OK")) - We should get "OK" followed by an optional description if
    // everything goes right
  }
  public void open() {
    if (this.args.length == 2) {
      String worldName = this.args[1];
      World world = Bukkit.getWorld(worldName);
      if (world == null) {
        message("World <" + worldName + "> was not loaded. Loading world...");
        world = Bukkit.createWorld(WorldCreator.name(worldName));
        message("World <" + worldName + "> loaded");
      }
      if (this.editor.getWorlds().keySet().contains(world)) {
        message("World <" + worldName + "> is already openned in editor");
        return;
      }

      try {
        this.editor.addWorld(world);

      } catch (IOException e) {
        message("Error loading script map for world <" + worldName + ">...");
        e.printStackTrace();
        return;
      }

      this.editor.buildSigns(world);

      message("World <" + worldName + "> openned in editor");
      NSCore.log("World <" + worldName + "> openned in editor by " + this.sender.getName());
    }
  }
Exemple #7
0
  @Override
  public void onEnable() {
    PluginManager pm = Bukkit.getPluginManager();

    AccountsConfig config;
    try {
      config = getLoader().loadOrCreate("config.json", AccountsConfig.class);
    } catch (GsonLoadException exc) {
      getLogger().log(Level.SEVERE, "Unable to load config.json", exc);
      config = new AccountsConfig();
    }

    Accounts accounts = new EVAccounts(this, config);
    EthilVan.registerAccounts(accounts);

    Listener accountsListener = new AccountsListener(this);
    pm.registerEvents(accountsListener, this);

    ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
    protocolManager.addPacketListener(new NamePlatePacketListener(this));

    CommandsRegistration registration = new CommandsRegistration(this, Locale.FRANCE);
    registration.register(new AccountsCommands());

    Bukkit.getScheduler().runTaskTimer(this, this, 6000, 6000);
  }
  @Override
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

    if (!sender.hasPermission(GoldRushPerms.SCHEDULE)) {
      deny(sender);
      return true;
    }

    int taskID = Departure.getTaskID();
    BukkitScheduler s = Bukkit.getScheduler();

    if (args[0].equalsIgnoreCase("Start") && taskID == -1) {
      sender.sendMessage("Starting Train Cycle...");
      Departure.setTaskID(
          Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Departure(plugin), 100, 400));
      return true;
    } else if (taskID != 0) {
      sender.sendMessage("Train Cycle already started!");
      return true;
    } else if (args[0].equalsIgnoreCase("Stop")
        && (s.isCurrentlyRunning(taskID) || s.isQueued(taskID))) {
      sender.sendMessage("Stopping Train Cycle...");
      Bukkit.getScheduler().cancelTask(taskID);
      Departure.resetTaskID();
      return true;
    } else if (taskID == -1) {
      sender.sendMessage("Train Cycle is not running.");
      return true;
    }
    return false;
  }
Exemple #9
0
 public PlantTimer(EodArena arena) {
   this.plugin = (BombPlugin) Bukkit.getPluginManager().getPlugin("BombArena");
   this.duration = this.plugin.getPlantTime() + 1;
   this.arena = arena;
   this.player = Bukkit.getPlayer(arena.getBombCarrier());
   this.BOMB_LOCATION = plugin.getExactLocation(player.getLocation());
 }
Exemple #10
0
 private void changePlayerRank(UUID toChange, PlayerType newRank) {
   if (gm.hasAccess(g, p.getUniqueId(), getAccordingPermission(g.getCurrentRank(toChange)))) {
     if (!g.isMember(toChange)) {
       p.sendMessage(
           ChatColor.RED
               + "This player is no longer on the group and can't be "
               + demoteOrPromote(g.getCurrentRank(toChange), newRank, false)
               + "d");
       return;
     }
     if (g.isOwner(toChange)) {
       p.sendMessage(ChatColor.RED + "This player owns the group and can't be demoted");
     }
     OfflinePlayer prom = Bukkit.getOfflinePlayer(toChange);
     NameLayerPlugin.log(
         Level.INFO,
         p.getName()
             + " changed player rank for "
             + NameAPI.getCurrentName(toChange)
             + " from "
             + g.getCurrentRank(toChange).toString()
             + " to "
             + newRank.toString()
             + " for group "
             + g.getName()
             + "via gui");
     if (prom.isOnline()) {
       Player oProm = (Player) prom;
       PromotePlayerEvent event =
           new PromotePlayerEvent(oProm, g, g.getCurrentRank(toChange), newRank);
       Bukkit.getPluginManager().callEvent(event);
       if (event.isCancelled()) {
         p.sendMessage(
             ChatColor.RED + "Could not change player rank, you should complain about this");
         return;
       }
       g.removeMember(toChange);
       g.addMember(toChange, newRank);
       oProm.sendMessage(
           ChatColor.GREEN
               + "You have been promoted to "
               + getRankName(toChange)
               + " in (Group) "
               + g.getName());
     } else {
       // player is offline change their perms
       g.removeMember(toChange);
       g.addMember(toChange, newRank);
     }
     p.sendMessage(
         ChatColor.GREEN
             + NameAPI.getCurrentName(toChange)
             + " has been "
             + demoteOrPromote(g.getCurrentRank(toChange), newRank, false)
             + "d to "
             + getRankName(toChange));
   } else {
     p.sendMessage(ChatColor.RED + "You have lost permission to remove this player");
   }
 }
 @Override
 public void undo(Undo undo) {
   World w = Bukkit.getWorld(worldName);
   Location loc = new Location(Bukkit.getWorld(worldName), blockX, blockY, blockZ);
   w.getBlockAt(loc).setType(Material.AIR);
   undo.chunks.add(loc.getChunk());
 }
  public void deleteWorld(String dimension) {
    World world = Bukkit.getWorld(dimension);
    File worldFolder = world.getWorldFolder();
    Bukkit.unloadWorld(dimension, true);

    scheduleWorldDeletion(worldFolder, dimension);
  }
  private void removePlayer(PlayerInfo player, PlayerInfo owner, CommandSender sender) {
    Player onlinePlayer = player.getPlayer();

    if (onlinePlayer != null) {
      onlinePlayer.sendMessage(
          ChatColor.RED + "You have been kicked from " + owner.getPlayerName() + "'s skyblock.");
      if (uSkyBlock.isSkyBlockWorld(onlinePlayer.getWorld())) {

        if (Settings.extras_sendToSpawn)
          Misc.safeTeleport(onlinePlayer, Bukkit.getWorlds().get(0).getSpawnLocation());
        else Misc.safeTeleport(onlinePlayer, uSkyBlock.getSkyBlockWorld().getSpawnLocation());
      }
    }

    sender.sendMessage(
        ChatColor.GREEN + player.getPlayerName() + " has been removed from the island.");

    player.setLeaveParty();
    player.setHomeLocation(null);

    owner.getMembers().remove(player.getPlayerName());

    if (Settings.island_protectWithWorldGuard
        && Bukkit.getPluginManager().isPluginEnabled("WorldGuard"))
      WorldGuardHandler.removePlayerFromRegion(owner.getPlayerName(), player.getPlayerName());

    player.save();
  }
Exemple #14
0
  public void execute(User user, List<String> actions, CheckType type) {
    final String name = user.getName();
    for (String event : actions) {
      event =
          event
              .replaceAll("&player", name)
              .replaceAll("&world", user.getPlayer().getWorld().getName())
              .replaceAll("&check", type.name());

      if (event.startsWith("COMMAND[")) {
        for (String cmd : Utilities.getCommands(event)) {
          Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
        }
      } else if (event.equalsIgnoreCase("KICK")) {
        user.getPlayer().kickPlayer(RED + lang.getKickReason());
        String msg = RED + lang.getKickBroadcast().replaceAll("&player", name);
        if (!msg.equals("")) {
          Bukkit.broadcastMessage(msg);
        }
      } else if (event.equalsIgnoreCase("WARN")) {
        List<String> message = lang.getWarning();
        for (String string : message) {
          user.getPlayer().sendMessage(RED + string);
        }
      } else if (event.equalsIgnoreCase("BAN")) {
        user.getPlayer().setBanned(true);
        user.getPlayer().kickPlayer(RED + lang.getBanReason());
        String msg = RED + lang.getBanBroadcast().replaceAll("&player", name);
        if (!msg.equals("")) {
          Bukkit.broadcastMessage(msg);
        }
      }
    }
  }
Exemple #15
0
  @Override
  public boolean execute(CommandSender sender, String currentAlias, String[] args) {
    if (!testPermission(sender)) return true;

    StringBuilder online = new StringBuilder();

    Player[] players = Bukkit.getOnlinePlayers();

    for (Player player : players) {
      // If a player is hidden from the sender don't show them in the list
      if (sender instanceof Player && !((Player) sender).canSee(player)) continue;

      if (online.length() > 0) {
        online.append(", ");
      }

      online.append(player.getDisplayName());
    }

    sender.sendMessage(
        "There are "
            + players.length
            + "/"
            + Bukkit.getMaxPlayers()
            + " players online:\n"
            + online.toString());

    return true;
  }
 public String getWhoDestroyed(String locale) {
   String whoDestroyed = "";
   List<String> toCombine = new ArrayList<>();
   for (UUID player : MiscUtils.getSortedHashMapKeyset(playersCompleted)) {
     if (getPercentFromAmount(playersCompleted.get(player)) > (100 / 3)) {
       toCombine.add(
           TeamUtils.getTeamColorByPlayer(Bukkit.getPlayer(player))
               + Bukkit.getPlayer(player).getName()
               + ChatColor.GRAY
               + " ("
               + getPercentFromAmount(playersCompleted.get(player))
               + "%)");
     }
   }
   if (toCombine.size() == 0) {
     toCombine.add(
         ChatColor.DARK_AQUA
             + new LocalizedChatMessage(ChatConstant.MISC_ENEMY).getMessage(locale));
   }
   if (toCombine.size() < playersCompleted.keySet().size()) {
     toCombine.add(
         ChatColor.DARK_AQUA
             + new LocalizedChatMessage(ChatConstant.MISC_OTHERS).getMessage(locale));
   }
   whoDestroyed = toCombine.get(0);
   for (int i = 1; i < toCombine.size(); i++) {
     whoDestroyed +=
         ChatColor.GRAY
             + (i == toCombine.size() - 1
                 ? " " + new LocalizedChatMessage(ChatConstant.MISC_AND).getMessage(locale) + " "
                 : ", ")
             + toCombine.get(i);
   }
   return whoDestroyed;
 }
Exemple #17
0
 public void remove(UUID uuid) {
   Cardinal.getCardinalDatabase().remove(this, uuid);
   Bukkit.getPluginManager()
       .callEvent(
           new RankChangeEvent(
               Bukkit.getPlayer(uuid), this, false, Bukkit.getOfflinePlayer(uuid).isOnline()));
 }
  public ZoneUserManager(Plugin plugin, ZoneConfig usersConfig) {
    this.usersConfigReference = usersConfig;
    this.usersConfigFilePath = usersConfig.getFile().getPath();
    this.plugin = plugin;
    if (plugin instanceof ZonePlugin) {
      this.isZonePlugin = true;
    } else {
      this.isZonePlugin = false;
    }

    loadUsers(usersConfig);

    if (preventOnlineUserGC) {
      for (Player player : Bukkit.getOnlinePlayers()) {
        holdUserFromGC(getUser(player));
      }
    }

    Bukkit.getPluginManager().registerEvents(this, plugin);

    Bukkit.getScheduler()
        .runTaskTimerAsynchronously(
            plugin,
            new Runnable() {
              @Override
              public void run() {
                getUsersConfig().schedualSave();
              }
            },
            saveInterval,
            saveInterval);
  }
 @Override
 public boolean isValid(ConversationContext context, String input) {
   if (input.contains(" ")) {
     String[] split = input.split("\\s");
     if (split.length == 4) {
       if (Bukkit.getWorld(split[0]) != null) {
         for (int i = 1; i <= 3; i++) {
           if (!GeneralUtil.isInt(split[i])) {
             context.setSessionData("fail_int", true);
             return false;
           }
         }
         this.location =
             new Location(
                 Bukkit.getWorld(split[0]),
                 Integer.parseInt(split[1]),
                 Integer.parseInt(split[2]),
                 Integer.parseInt(split[3]));
       } else {
         context.setSessionData("fail_world", true);
         return false;
       }
     } else {
       context.setSessionData("fail_format", true);
       return false;
     }
   } else {
     context.setSessionData("fail_format", true);
     return false;
   }
   return true;
 }
  public void createDuel(Player p1, Player p2, String mode) {
    Duel duel = new Duel(this.plugin, p1.getName(), p2.getName(), mode);

    this.invites.removeAll(p1.getName());
    this.invites.removeAll(p2.getName());

    p1.getInventory().clear();
    p2.getInventory().clear();

    p1.updateInventory();
    p2.updateInventory();

    p1.setHealth(20.0D);
    p2.setHealth(20.0D);

    this.duels.add(duel);
    duel.setTaskID(Bukkit.getScheduler().scheduleSyncRepeatingTask(this.plugin, duel, 0L, 10L));
    for (String s : ovo) {
      Player p = Bukkit.getPlayerExact(s);
      if ((!p.getName().equals(p1.getName())) && (!p.getName().equals(p2.getName()))) {
        p1.hidePlayer(p);
        p2.hidePlayer(p);
      }
    }
  }
 @Override
 protected void execute(CommandSender cs, String... args) {
   PlotBuild plotbuild = checkPlotBuild((Player) cs, 1, args);
   if (plotbuild == null) {
     return;
   }
   if (!hasPermissionsForPlotBuild((Player) cs, plotbuild)) {
     return;
   }
   OfflinePlayer removedStaff = BukkitUtil.matchPlayer(args[0]);
   if (removedStaff == null) {
     removedStaff = Bukkit.getOfflinePlayer(args[0]);
   }
   if (removedStaff.getLastPlayed() == 0) {
     sendPlayerNotFoundMessage(cs);
     return;
   }
   if (!plotbuild.isStaff(removedStaff)) {
     sendNotStaffMessage(cs, removedStaff, plotbuild.getName());
     return;
   }
   plotbuild.removeStaff(removedStaff);
   sendRemoveStaffMessage(cs, removedStaff.getName(), plotbuild.getName());
   if (removedStaff.getPlayer() != cs) {
     sendRemovedStaffPlayerMessage(cs, removedStaff, plotbuild.getName());
   }
   for (UUID staff : plotbuild.getOfflineStaffList()) {
     if (!staff.equals(((Player) cs).getUniqueId()) && !staff.equals(removedStaff.getUniqueId())) {
       sendOtherStaffMessage(
           cs, Bukkit.getOfflinePlayer(staff), removedStaff, plotbuild.getName());
     }
   }
   plotbuild.log(((Player) cs).getName() + " removed " + removedStaff.getName() + " from staff.");
   PluginData.saveData();
 }
Exemple #22
0
 @EventHandler
 public void onExpire(TimerExpireEvent e) {
   if ((e.getUserUUID().isPresent()) && (e.getTimer().equals(this))) {
     UUID userUUID = (UUID) e.getUserUUID().get();
     Player player = Bukkit.getPlayer(userUUID);
     if (player == null) {
       return;
     }
     Bukkit.getPlayer((UUID) ArcherClass.tagged.get(userUUID))
         .sendMessage(
             ChatColor.YELLOW
                 + "Your archer mark on "
                 + ChatColor.AQUA
                 + player.getName()
                 + ChatColor.YELLOW
                 + " has expired.");
     player.sendMessage(ChatColor.YELLOW + "You're no longer archer marked.");
     ArcherClass.tagged.remove(player.getUniqueId());
     for (Player players : Bukkit.getOnlinePlayers()) {
       this.plugin
           .getScoreboardHandler()
           .getPlayerBoard(players.getUniqueId())
           .addUpdates(Bukkit.getOnlinePlayers());
     }
   }
 }
 /**
  * @param types
  * @param type
  * @param worlds worlds or null for all
  * @return All entities of this type in the given worlds
  */
 @SuppressWarnings({"null", "unchecked"})
 public static final <E extends Entity> E[] getAll(
     final EntityData<?>[] types, final Class<E> type, @Nullable World[] worlds) {
   assert types.length > 0;
   if (type == Player.class) {
     if (worlds == null
         && types.length == 1
         && types[0] instanceof PlayerData
         && ((PlayerData) types[0]).op == 0) return (E[]) Bukkit.getOnlinePlayers();
     final List<Player> list = new ArrayList<Player>();
     for (final Player p : Bukkit.getOnlinePlayers()) {
       if (worlds != null && !CollectionUtils.contains(worlds, p.getWorld())) continue;
       for (final EntityData<?> t : types) {
         if (t.isInstance(p)) {
           list.add(p);
           break;
         }
       }
     }
     return (E[]) list.toArray(new Player[list.size()]);
   }
   final List<E> list = new ArrayList<E>();
   if (worlds == null) worlds = Bukkit.getWorlds().toArray(new World[0]);
   for (final World w : worlds) {
     for (final E e : w.getEntitiesByClass(type)) {
       for (final EntityData<?> t : types) {
         if (t.isInstance(e)) {
           list.add(e);
           break;
         }
       }
     }
   }
   return list.toArray((E[]) Array.newInstance(type, list.size()));
 }
Exemple #24
0
 public Scoreboard Initialize(Player p) throws IllegalStateException, IllegalArgumentException {
   ScoreboardManager manager = Bukkit.getScoreboardManager();
   Scoreboard board = manager.getNewScoreboard();
   Objective objective = board.registerNewObjective("test", "dummy");
   objective.setDisplaySlot(DisplaySlot.SIDEBAR);
   objective.setDisplayName(
       ChatColor.GOLD
           + ""
           + ChatColor.BOLD
           + "     _Esti"
           + ChatColor.DARK_AQUA
           + ""
           + ChatColor.BOLD
           + "Net_     ");
   Score score2 = objective.getScore(ChatColor.DARK_BLUE + "Online:"); // Get a fake offline player
   score2.setScore(4);
   Score score3 =
       objective.getScore(
           ChatColor.BOLD
               + ""
               + Integer.toString(
                   Bukkit.getServer().getOnlinePlayers().size())); // Get a fake offline player
   score3.setScore(3);
   Score score =
       objective.getScore(
           ChatColor.AQUA + "Time before game starts:"); // Get a fake offline player
   score.setScore(2);
   Score score5 =
       objective.getScore(
           ChatColor.BOLD + "" + Basic.countdown + " "); // Get a fake offline player
   score5.setScore(1);
   return board;
 }
Exemple #25
0
 public static void deployDefaultConfig(String name) {
   try {
     final File target = new File(VanishNoPacket.getPlugin().getDataFolder(), name);
     final InputStream source = VanishNoPacket.getPlugin().getResource(name);
     if (source == null) {
       Bukkit.getServer().getLogger().log(Level.SEVERE, "Could not find default config " + name);
       return;
     }
     if (!VanishNoPacket.getPlugin().getDataFolder().exists()) {
       VanishNoPacket.getPlugin().getDataFolder().mkdir();
     }
     if (!target.exists()) {
       final OutputStream output = new FileOutputStream(target);
       int len;
       final byte[] buffer = new byte[1024];
       while ((len = source.read(buffer)) > 0) {
         output.write(buffer, 0, len);
       }
       output.close();
     }
     source.close();
   } catch (final Exception ex) {
     Bukkit.getServer()
         .getLogger()
         .log(Level.SEVERE, "Could not save default config to " + name, ex);
   }
 }
  public void inject(Plugin plugin) {
    Bukkit.getLogger()
        .info(
            "["
                + PluginBungeePermsBukkitBridge.getInstance().getDescription().getName()
                + "] Injection of BungeepermsBukkit into Vault");
    try {
      Vault v = (Vault) plugin;

      // inject BungeePerms
      Method m =
          v.getClass()
              .getDeclaredMethod(
                  "hookPermission",
                  String.class,
                  Class.class,
                  ServicePriority.class,
                  String[].class);
      m.setAccessible(true);
      m.invoke(
          v,
          "BungeePermsBukkit",
          Permission_BungeePermsBukkit.class,
          ServicePriority.Normal,
          new String[] {"net.alpenblock.bungeeperms.bukkit.BungeePerms"});

      Field f = v.getClass().getDeclaredField("perms");
      f.setAccessible(true);
      f.set(v, Bukkit.getServicesManager().getRegistration(Permission.class).getProvider());

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Exemple #27
0
  public void onEnable() {
    loadSettings();

    if (settings == null) return;

    for (World world : Bukkit.getWorlds()) {
      boolean disabled = false;
      for (String worldName : settings.worldsToDisable) {
        if (!world.getName().equalsIgnoreCase(worldName)) continue;

        Bukkit.getServer().unloadWorld(world, true);
        disabled = true;
        break;
      }

      if (disabled) continue;

      for (String worldName : settings.worldsToUnload) {
        if (!world.getName().equalsIgnoreCase(worldName)) continue;

        world.setKeepSpawnInMemory(false);
        break;
      }
    }
    getServer().getPluginManager().registerEvents(this, this);
    getCommand("nopreload").setExecutor(this);
  }
  @Override
  public void onEnable() {
    Bukkit.getScheduler()
        .runTaskTimerAsynchronously(
            this,
            new Runnable() {
              @Override
              public void run() {
                if (isProcessing) return;

                isProcessing = true;
                Iterator<AtomicInteger> iterator = scores.values().iterator();
                int threshold = getConfig().getInt("threshold");

                while (iterator.hasNext()) {
                  AtomicInteger score = iterator.next();
                  int newScore = score.decrementAndGet();

                  if (newScore <= 0) {
                    iterator.remove();
                  } else if (newScore > threshold) {
                    score.compareAndSet(newScore, threshold);
                  }
                }

                isProcessing = false;
              }
            },
            60,
            60);

    saveDefaultConfig();
    Bukkit.getPluginManager().registerEvents(this, this);
  }
Exemple #29
0
  static Player getOfflinePlayer(String player, UUID uuid) {
    Player pplayer = null;
    try {
      File playerfolder = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "players");

      for (File playerfile : playerfolder.listFiles()) {
        String filename = playerfile.getName();
        String playername = filename.substring(0, filename.length() - 4);

        GameProfile profile = new GameProfile(uuid, playername);

        if (playername.trim().equalsIgnoreCase(player)) {
          MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
          EntityPlayer entity =
              new EntityPlayer(
                  server,
                  server.getWorldServer(0),
                  profile,
                  new PlayerInteractManager(server.getWorldServer(0)));
          Player target = entity == null ? null : (Player) entity.getBukkitEntity();
          if (target != null) {
            target.loadData();
            return target;
          }
        }
      }
    } catch (Exception e) {
      return null;
    }
    return pplayer;
  }
  /** Block place methods */
  public static BlockPlaceEvent callBlockPlaceEvent(
      World world,
      EntityPlayerMP who,
      BlockState replacedBlockState,
      int clickedX,
      int clickedY,
      int clickedZ) {
    BukkitWorld craftWorld =
        (BukkitWorld)
            Bukkit.getServer().getWorld(((WorldServer) world).getWorldInfo().getWorldName());
    BukkitServer craftServer = (BukkitServer) Bukkit.getServer();

    Player player = (who == null) ? null : (Player) BukkitEntity.getEntity(craftServer, who);

    Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ);
    Block placedBlock = replacedBlockState.getBlock();

    boolean canBuild = canBuild(craftWorld, player, placedBlock.getX(), placedBlock.getZ());

    BlockPlaceEvent event =
        new BlockPlaceEvent(
            placedBlock,
            replacedBlockState,
            blockClicked,
            player.getItemInHand(),
            player,
            canBuild);
    craftServer.getPluginManager().callEvent(event);

    return event;
  }