itemLore = meta.getLore();
+ lore = itemLore.toArray(new String[0]);
+ }
+ }
+ return new PlotItemStack(id.name(), amount, name, lore);
+ }
- @Override public PlotItemStack[] getItems(PlotPlayer player) {
- BukkitPlayer bp = (BukkitPlayer) player;
- PlayerInventory inv = bp.player.getInventory();
- PlotItemStack[] items = new PlotItemStack[36];
- for (int i = 0; i < 36; i++) {
- items[i] = getItem(inv.getItem(i));
- }
- return items;
- }
+ @Override public PlotItemStack[] getItems(PlotPlayer player) {
+ BukkitPlayer bp = (BukkitPlayer) player;
+ PlayerInventory inv = bp.player.getInventory();
+ return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i)))
+ .toArray(PlotItemStack[]::new);
+ }
- @Override public boolean isOpen(PlotInventory inv) {
- if (!inv.isOpen()) {
- return false;
- }
- BukkitPlayer bp = (BukkitPlayer) inv.player;
- InventoryView opened = bp.player.getOpenInventory();
- return inv.isOpen() && opened.getType() == InventoryType.CRAFTING
- && opened.getTitle() == null;
+ @Override public boolean isOpen(PlotInventory plotInventory) {
+ if (!plotInventory.isOpen()) {
+ return false;
}
+ BukkitPlayer bp = (BukkitPlayer) plotInventory.player;
+ InventoryView opened = bp.player.getOpenInventory();
+ if (plotInventory.isOpen()) {
+ if (opened.getType() == InventoryType.CRAFTING) {
+ opened.getTitle();
+ }
+ }
+ return false;
+ }
}
diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java
index e9ec7742f..44c262b10 100644
--- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java
+++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java
@@ -1,36 +1,47 @@
package com.github.intellectualsites.plotsquared.bukkit.util;
+import com.github.intellectualsites.plotsquared.bukkit.BukkitMain;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.LegacyPlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.LegacyMappings;
import com.github.intellectualsites.plotsquared.plot.util.StringComparison;
-import lombok.*;
-import org.bukkit.Material;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
import java.util.stream.Collectors;
+import lombok.AccessLevel;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.NonNull;
+import lombok.RequiredArgsConstructor;
+import lombok.ToString;
+import org.bukkit.Bukkit;
+import org.bukkit.Material;
+
/**
* Borrowed from https://github.com/Phoenix616/IDConverter/blob/master/mappings/src/main/java/de/themoep/idconverter/IdMappings.java
* Original License:
*
- * Minecraft ID mappings
- * Copyright (C) 2017 Max Lee (https://github.com/Phoenix616)
+ * Minecraft ID mappings Copyright (C) 2017 Max Lee (https://github.com/Phoenix616)
*
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
+ * This program is free software: you can redistribute it and/or modify it under the terms of the
+ * GNU General Public License as published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
*
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
+ * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
+ * You should have received a copy of the GNU General Public License along with this program. If
+ * not, see .
*/
public final class BukkitLegacyMappings extends LegacyMappings {
@@ -75,7 +86,7 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(19, 1, "sponge", "wet_sponge"), new LegacyBlock(20, "glass"),
new LegacyBlock(21, "lapis_ore"), new LegacyBlock(22, "lapis_block"),
new LegacyBlock(23, "dispenser"), new LegacyBlock(24, "sandstone"),
- new LegacyBlock(24, 1, "sandstone", "chisled_sandstone"),
+ new LegacyBlock(24, 1, "sandstone", "chiseled_sandstone"),
new LegacyBlock(24, 2, "sandstone", "cut_sandstone"), new LegacyBlock(25, "note_block"),
new LegacyBlock(26, "bed_block"), new LegacyBlock(27, "powered_rail"),
new LegacyBlock(28, "detector_rail"),
@@ -118,7 +129,7 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(43, 6, "double_step", "smooth_quartz"),
new LegacyBlock(43, 8, "double_step", "smooth_stone"),
new LegacyBlock(43, 9, "double_step", "smooth_sandstone"),
- new LegacyBlock(44, "step", "stone_slab"),
+ new LegacyBlock(44, "step", "stone_slab", "smooth_stone_slab"),
new LegacyBlock(44, 1, "step", "sandstone_slab"),
new LegacyBlock(44, 2, "step", "petrified_oak_slab"),
new LegacyBlock(44, 3, "step", "cobblestone_slab"),
@@ -139,10 +150,11 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(58, "workbench", "crafting_table"),
new LegacyBlock(59, "crops", "wheat"), new LegacyBlock(60, "soil", "farmland"),
new LegacyBlock(61, "furnace"), new LegacyBlock(62, "burning_furnace"),
- new LegacyBlock(63, "sign_post", "sign"),
+ new LegacyBlock(63, "sign_post", "sign", "oak_sign"),
new LegacyBlock(64, "wooden_door", "oak_door"), new LegacyBlock(65, "ladder"),
new LegacyBlock(66, "rails", "rail"), new LegacyBlock(67, "cobblestone_stairs"),
- new LegacyBlock(68, "wall_sign"), new LegacyBlock(69, "lever"),
+ new LegacyBlock(68, "wall_sign", "wall_sign", "oak_wall_sign"),
+ new LegacyBlock(69, "lever"),
new LegacyBlock(70, "stone_plate", "stone_pressure_plate"),
new LegacyBlock(71, "iron_door_block", "iron_door"),
new LegacyBlock(72, "wood_plate", "oak_pressure_plate"),
@@ -182,10 +194,10 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(95, 15, "stained_glass", "black_stained_glass"),
new LegacyBlock(96, "trap_door", "oak_trapdoor"),
new LegacyBlock(97, "monster_eggs", "infested_stone"),
- new LegacyBlock(97, 1, "monster_eggs", "infested_coblestone"),
+ new LegacyBlock(97, 1, "monster_eggs", "infested_cobblestone"),
new LegacyBlock(97, 2, "monster_eggs", "infested_stone_bricks"),
new LegacyBlock(97, 3, "monster_eggs", "infested_mossy_stone_bricks"),
- new LegacyBlock(97, 4, "monster_eggs", "infested_crcked_stone_bricks"),
+ new LegacyBlock(97, 4, "monster_eggs", "infested_cracked_stone_bricks"),
new LegacyBlock(97, 5, "monster_eggs", "infested_chiseled_stone_bricks"),
new LegacyBlock(98, "smooth_brick", "stone_bricks"),
new LegacyBlock(98, 1, "smooth_brick", "mossy_stone_bricks"),
@@ -208,7 +220,7 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(100, 10, "huge_mushroom_2", "mushroom_stem"),
new LegacyBlock(100, 14, "huge_mushroom_2"),
new LegacyBlock(100, 15, "huge_mushroom_2"),
- new LegacyBlock(101, "iron_fence", "ironbars"),
+ new LegacyBlock(101, "iron_fence", "iron_bars"),
new LegacyBlock(102, "thin_glass", "glass_pane"), new LegacyBlock(103, "melon_block"),
new LegacyBlock(104, "pumpkin_stem"), new LegacyBlock(105, "melon_stem"),
new LegacyBlock(106, "vine"), new LegacyBlock(107, "fence_gate", "oak_fence_gate"),
@@ -541,7 +553,7 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(383, 5, "monster_egg", "wither_skeleton_spawn_egg"),
new LegacyBlock(383, 6, "monster_egg", "stray_spawn_egg"),
new LegacyBlock(383, 23, "monster_egg", "husk_spawn_egg"),
- new LegacyBlock(383, 27, "monster_egg", "zombe_villager_spawn_egg"),
+ new LegacyBlock(383, 27, "monster_egg", "zombie_villager_spawn_egg"),
new LegacyBlock(383, 28, "monster_egg", "skeleton_horse_spawn_egg"),
new LegacyBlock(383, 29, "monster_egg", "zombie_horse_spawn_egg"),
new LegacyBlock(383, 31, "monster_egg", "donkey_spawn_egg"),
@@ -664,22 +676,24 @@ public final class BukkitLegacyMappings extends LegacyMappings {
new LegacyBlock(2266, "record_11", "music_disc_11"),
new LegacyBlock(2267, "record_12", "music_disc_wait")};
- // private static final Map LEGACY_ID_TO_STRING_PLOT_BLOCK = new HashMap<>();
private static final Map LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK =
new HashMap<>();
private static final Map NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>();
private static final Map OLD_STRING_TO_STRING_PLOT_BLOCK = new HashMap<>();
- public BukkitLegacyMappings() {
+ @SuppressWarnings("deprecation") public BukkitLegacyMappings() {
this.addAll(Arrays.asList(BLOCKS));
// Make sure to add new blocks as well
final List missing = new ArrayList<>();
for (final Material material : Material.values()) {
final String materialName = material.name().toLowerCase(Locale.ENGLISH);
- if (OLD_STRING_TO_STRING_PLOT_BLOCK.get(materialName) == null) {
- final LegacyBlock missingBlock =
- new LegacyBlock(material.getId(), materialName, materialName);
- missing.add(missingBlock);
+ if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.get(materialName) == null) {
+ try {
+ final LegacyBlock missingBlock =
+ new LegacyBlock(material.getId(), materialName, materialName);
+ missing.add(missingBlock);
+ } catch (Exception ignored) {
+ }
}
}
addAll(missing);
@@ -687,13 +701,6 @@ public final class BukkitLegacyMappings extends LegacyMappings {
private void addAll(@NonNull final Collection blocks) {
for (final LegacyBlock legacyBlock : blocks) {
- // LEGACY_ID_TO_STRING_PLOT_BLOCK
- // .put(legacyBlock.getNumericalId(), legacyBlock.toStringPlotBlock());
- /*if (legacyBlock.getDataValue() != 0) {
- LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK
- .put(new IdDataPair(legacyBlock.getNumericalId(), legacyBlock.getDataValue()),
- legacyBlock.toStringPlotBlock());
- } */
LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK
.put(new IdDataPair(legacyBlock.getNumericalId(), legacyBlock.getDataValue()),
legacyBlock.toStringPlotBlock());
@@ -705,7 +712,14 @@ public final class BukkitLegacyMappings extends LegacyMappings {
try {
material = Material.valueOf(legacyBlock.getNewName());
} catch (final Exception e) {
- material = Material.getMaterial(legacyBlock.getLegacyName(), true);
+ try {
+ material = Material.getMaterial(legacyBlock.getLegacyName(), true);
+ } catch (NoSuchMethodError error) {
+ PlotSquared.log("You can't use this version of PlotSquared on a server "
+ + "less than Minecraft 1.13.2");
+ Bukkit.shutdown();
+ break;
+ }
}
legacyBlock.material = material;
}
@@ -724,13 +738,10 @@ public final class BukkitLegacyMappings extends LegacyMappings {
}
/**
- * Try to find a legacy plot block by any means possible.
- * Strategy:
- * - Check if the name contains a namespace, if so, strip it
- * - Check if there's a (new) material matching the name
- * - Check if there's a legacy material matching the name
- * - Check if there's a numerical ID matching the name
- * - Return null if everything else fails
+ * Try to find a legacy plot block by any means possible. Strategy: - Check if the name contains
+ * a namespace, if so, strip it - Check if there's a (new) material matching the name - Check if
+ * there's a legacy material matching the name - Check if there's a numerical ID matching the
+ * name - Return null if everything else fails
*
* @param string String ID
* @return LegacyBlock if found, else null
@@ -741,19 +752,31 @@ public final class BukkitLegacyMappings extends LegacyMappings {
}
String workingString = string;
String[] parts = null;
+ IdDataPair idDataPair = null;
if (string.contains(":")) {
parts = string.split(":");
if (parts.length > 1) {
if (parts[0].equalsIgnoreCase("minecraft")) {
workingString = parts[1];
} else {
- workingString = parts[0];
+ if (parts[0].matches("^\\d+$")) {
+ idDataPair =
+ new IdDataPair(Integer.parseInt(parts[0]), Integer.parseInt(parts[0]));
+ } else {
+ workingString = parts[0];
+ }
}
}
+ } else if (string.matches("^\\d+$")) {
+ idDataPair = new IdDataPair(Integer.parseInt(string), 0);
}
PlotBlock plotBlock;
- if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.keySet().contains(workingString.toLowerCase())) {
+ if (Material.matchMaterial(workingString) != null) {
return PlotBlock.get(workingString);
+ } else if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.keySet().contains(workingString.toLowerCase())) {
+ return PlotBlock.get(workingString);
+ } else if ((plotBlock = fromLegacyToString(idDataPair)) != null) {
+ return plotBlock;
} else if ((plotBlock = fromLegacyToString(workingString)) != null) {
return plotBlock;
} else {
@@ -775,6 +798,13 @@ public final class BukkitLegacyMappings extends LegacyMappings {
return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(new IdDataPair(id, data));
}
+ public PlotBlock fromLegacyToString(IdDataPair idDataPair) {
+ if (idDataPair == null) {
+ return null;
+ }
+ return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(idDataPair);
+ }
+
public PlotBlock fromLegacyToString(final String id) {
return OLD_STRING_TO_STRING_PLOT_BLOCK.get(id);
}
@@ -804,6 +834,20 @@ public final class BukkitLegacyMappings extends LegacyMappings {
this(numericalId, dataValue, legacyName, legacyName);
}
+ LegacyBlock(final int numericalId, final int dataValue, @NonNull final String legacyName,
+ @NonNull final String newName, @NonNull final String new14Name) {
+ this(numericalId, dataValue, legacyName,
+ PlotSquared.get().IMP.getServerVersion()[1] == 13 ? newName : new14Name);
+ }
+
+ LegacyBlock(final int numericalId, @NonNull final String legacyName,
+ @NonNull final String newName, @NonNull final String new14Name) {
+ this(numericalId, 0, legacyName,
+ Bukkit.getBukkitVersion().split("-")[0].split("\\.")[1].equals("13") ?
+ newName :
+ new14Name);
+ }
+
LegacyBlock(final int numericalId, @NonNull final String legacyName,
@NonNull final String newName) {
this(numericalId, 0, legacyName, newName);
diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java
index efdb034cd..958def626 100644
--- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java
+++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java
@@ -9,8 +9,12 @@ import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.SetupObject;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
-import org.bukkit.*;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.World;
import org.bukkit.World.Environment;
+import org.bukkit.WorldCreator;
+import org.bukkit.WorldType;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
@@ -61,11 +65,11 @@ public class BukkitSetupUtils extends SetupUtils {
}
if (save) {
for (Chunk chunk : world.getLoadedChunks()) {
- chunk.unload(true, false);
+ chunk.unload(true);
}
} else {
for (Chunk chunk : world.getLoadedChunks()) {
- chunk.unload(false, false);
+ chunk.unload(false);
}
}
Bukkit.unloadWorld(world, false);
@@ -123,23 +127,28 @@ public class BukkitSetupUtils extends SetupUtils {
break;
}
case 1: {
- if (!PlotSquared.get().worlds.contains(worldPath)) {
- PlotSquared.get().worlds.createSection(worldPath);
- }
- ConfigurationSection worldSection =
- PlotSquared.get().worlds.getConfigurationSection(worldPath);
- for (ConfigurationNode step : steps) {
- worldSection.set(step.getConstant(), step.getValue());
- }
- PlotSquared.get().worlds.set("worlds." + world + ".generator.type", object.type);
- PlotSquared.get().worlds
- .set("worlds." + world + ".generator.terrain", object.terrain);
- PlotSquared.get().worlds
- .set("worlds." + world + ".generator.plugin", object.plotManager);
- if (object.setupGenerator != null && !object.setupGenerator
- .equals(object.plotManager)) {
+ if (!object.plotManager.endsWith(":single")) {
+ if (!PlotSquared.get().worlds.contains(worldPath)) {
+ PlotSquared.get().worlds.createSection(worldPath);
+ }
+ if (steps.length != 0) {
+ ConfigurationSection worldSection =
+ PlotSquared.get().worlds.getConfigurationSection(worldPath);
+ for (ConfigurationNode step : steps) {
+ worldSection.set(step.getConstant(), step.getValue());
+ }
+ }
PlotSquared.get().worlds
- .set("worlds." + world + ".generator.init", object.setupGenerator);
+ .set("worlds." + world + ".generator.type", object.type);
+ PlotSquared.get().worlds
+ .set("worlds." + world + ".generator.terrain", object.terrain);
+ PlotSquared.get().worlds
+ .set("worlds." + world + ".generator.plugin", object.plotManager);
+ if (object.setupGenerator != null && !object.setupGenerator
+ .equals(object.plotManager)) {
+ PlotSquared.get().worlds
+ .set("worlds." + world + ".generator.init", object.setupGenerator);
+ }
}
GeneratorWrapper> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
@@ -166,9 +175,9 @@ public class BukkitSetupUtils extends SetupUtils {
} catch (IOException e) {
e.printStackTrace();
}
+ Plugin plugin = Bukkit.getPluginManager().getPlugin("Multiverse-Core");
if (object.setupGenerator != null) {
- if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit
- .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
+ if (plugin != null && plugin.isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv create " + world + " normal -g " + object.setupGenerator);
setGenerator(world, object.setupGenerator);
@@ -176,15 +185,6 @@ public class BukkitSetupUtils extends SetupUtils {
return world;
}
}
- if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit
- .getPluginManager().getPlugin("MultiWorld").isEnabled()) {
- Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
- "mw create " + world + " plugin:" + object.setupGenerator);
- setGenerator(world, object.setupGenerator);
- if (Bukkit.getWorld(world) != null) {
- return world;
- }
- }
WorldCreator wc = new WorldCreator(object.world);
wc.generator(object.setupGenerator);
wc.environment(Environment.NORMAL);
@@ -192,22 +192,13 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator);
} else {
- if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit
- .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
+ if (plugin != null && plugin.isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) {
return world;
}
}
- if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit
- .getPluginManager().getPlugin("MultiWorld").isEnabled()) {
- Bukkit.getServer()
- .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
- if (Bukkit.getWorld(world) != null) {
- return world;
- }
- }
World bw =
Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
}
diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java
index dcee95c67..66b509615 100644
--- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java
+++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java
@@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.util;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
-import com.github.intellectualsites.plotsquared.plot.config.C;
+import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem;
import com.github.intellectualsites.plotsquared.plot.util.*;
@@ -13,7 +13,7 @@ import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.*;
-import org.bukkit.block.data.type.WallSign;
+import org.bukkit.block.data.Directional;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
@@ -174,9 +174,9 @@ import java.util.*;
*
* @param player the recipient of the message
* @param caption the message
- * @see MainUtil#sendMessage(PlotPlayer, C, String...)
+ * @see MainUtil#sendMessage(com.github.intellectualsites.plotsquared.commands.CommandCaller, Captions, String...)
*/
- public static void sendMessage(Player player, C caption) {
+ public static void sendMessage(Player player, Captions caption) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), caption);
}
@@ -264,34 +264,28 @@ import java.util.*;
return getWorld(world).getBiome(x, z).name();
}
- @Override @SuppressWarnings("deprecation")
- public void setSign(@NonNull final String worldName, final int x, final int y, final int z,
- @NonNull final String[] lines) {
- final World world = getWorld(worldName);
- final Block block = world.getBlockAt(x, y, z);
- // block.setType(Material.AIR);
- final Material type = block.getType();
- if (type != Material.SIGN && type != Material.WALL_SIGN) {
- BlockFace facing = BlockFace.EAST;
- if (world.getBlockAt(x, y, z + 1).getType().isSolid())
- facing = BlockFace.NORTH;
- else if (world.getBlockAt(x + 1, y, z).getType().isSolid())
- facing = BlockFace.WEST;
- else if (world.getBlockAt(x, y, z - 1).getType().isSolid())
- facing = BlockFace.SOUTH;
- block.setType(Material.WALL_SIGN, false);
- final WallSign sign = (WallSign) block.getBlockData();
- sign.setFacing(facing);
- block.setBlockData(sign, false);
- }
- final BlockState blockstate = block.getState();
- if (blockstate instanceof Sign) {
- final Sign sign = (Sign) blockstate;
- for (int i = 0; i < lines.length; i++) {
- sign.setLine(i, lines[i]);
+ @Override public int getHighestBlock(@NonNull final String world, final int x, final int z) {
+ final World bukkitWorld = getWorld(world);
+ // Skip top and bottom block
+ int air = 1;
+ for (int y = bukkitWorld.getMaxHeight() - 1; y >= 0; y--) {
+ Block block = bukkitWorld.getBlockAt(x, y, z);
+ if (block != null) {
+ Material type = block.getType();
+ if (type.isSolid()) {
+ if (air > 1) {
+ return y;
+ }
+ air = 0;
+ } else {
+ if (block.isLiquid()) {
+ return y;
+ }
+ air++;
+ }
}
- sign.update(true);
}
+ return bukkitWorld.getMaxHeight() - 1;
}
@Override @Nullable public String[] getSign(@NonNull final Location location) {
@@ -330,29 +324,39 @@ import java.util.*;
}
}
- @Override public int getHighestBlock(@NonNull final String world, final int x, final int z) {
- final World bukkitWorld = getWorld(world);
- // Skip top and bottom block
- int air = 1;
- for (int y = bukkitWorld.getMaxHeight() - 1; y >= 0; y--) {
- Block block = bukkitWorld.getBlockAt(x, y, z);
- if (block != null) {
- Material type = block.getType();
- if (type.isSolid()) {
- if (air > 1)
- return y;
- air = 0;
- } else {
- switch (type) {
- case WATER:
- case LAVA:
- return y;
- }
- air++;
- }
+ @Override @SuppressWarnings("deprecation")
+ public void setSign(@NonNull final String worldName, final int x, final int y, final int z,
+ @NonNull final String[] lines) {
+ final World world = getWorld(worldName);
+ final Block block = world.getBlockAt(x, y, z);
+ // block.setType(Material.AIR);
+ final Material type = block.getType();
+ if (type != Material.LEGACY_SIGN && type != Material.LEGACY_WALL_SIGN) {
+ BlockFace facing = BlockFace.EAST;
+ if (world.getBlockAt(x, y, z + 1).getType().isSolid()) {
+ facing = BlockFace.NORTH;
+ } else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) {
+ facing = BlockFace.WEST;
+ } else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) {
+ facing = BlockFace.SOUTH;
}
+ if (PlotSquared.get().IMP.getServerVersion()[1] == 13) {
+ block.setType(Material.valueOf("WALL_SIGN"), false);
+ } else {
+ block.setType(Material.valueOf("OAK_WALL_SIGN"), false);
+ }
+ final Directional sign = (Directional) block.getBlockData();
+ sign.setFacing(facing);
+ block.setBlockData(sign, false);
+ }
+ final BlockState blockstate = block.getState();
+ if (blockstate instanceof Sign) {
+ final Sign sign = (Sign) blockstate;
+ for (int i = 0; i < lines.length; i++) {
+ sign.setLine(i, lines[i]);
+ }
+ sign.update(true);
}
- return bukkitWorld.getMaxHeight() - 1;
}
@Override public int getBiomeFromString(@NonNull final String biomeString) {
@@ -366,11 +370,7 @@ import java.util.*;
@Override public String[] getBiomeList() {
final Biome[] biomes = Biome.values();
- final String[] list = new String[biomes.length];
- for (int i = 0; i < biomes.length; i++) {
- list[i] = biomes[i].name();
- }
- return list;
+ return Arrays.stream(biomes).map(Enum::name).toArray(String[]::new);
}
@Override
diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java
new file mode 100644
index 000000000..ff6e1b310
--- /dev/null
+++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java
@@ -0,0 +1,695 @@
+package com.github.intellectualsites.plotsquared.bukkit.util;
+
+import org.bukkit.Bukkit;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.RegisteredServiceProvider;
+import org.bukkit.plugin.ServicePriority;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.Callable;
+import java.util.logging.Level;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * bStats collects some data for plugin authors.
+ *
+ * Check out https://bStats.org/ to learn more about bStats!
+ */
+@SuppressWarnings({"WeakerAccess", "unused"})
+public class Metrics {
+
+ static {
+ // You can use the property to disable the check in your test environment
+ if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
+ // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
+ final String defaultPackage = new String(
+ new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
+ final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
+ // We want to make sure nobody just copy & pastes the example and use the wrong package names
+ if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
+ throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
+ }
+ }
+ }
+
+ // The version of this bStats class
+ public static final int B_STATS_VERSION = 1;
+
+ // The url to which the data is sent
+ private static final String URL = "https://bStats.org/submitData/bukkit";
+
+ // Is bStats enabled on this server?
+ private boolean enabled;
+
+ // Should failed requests be logged?
+ private static boolean logFailedRequests;
+
+ // Should the sent data be logged?
+ private static boolean logSentData;
+
+ // Should the response text be logged?
+ private static boolean logResponseStatusText;
+
+ // The uuid of the server
+ private static String serverUUID;
+
+ // The plugin
+ private final Plugin plugin;
+
+ // A list with all custom charts
+ private final List charts = new ArrayList<>();
+
+ /**
+ * Class constructor.
+ *
+ * @param plugin The plugin which stats should be submitted.
+ */
+ public Metrics(Plugin plugin) {
+ if (plugin == null) {
+ throw new IllegalArgumentException("Plugin cannot be null!");
+ }
+ this.plugin = plugin;
+
+ // Get the config file
+ File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
+ File configFile = new File(bStatsFolder, "config.yml");
+ YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
+
+ // Check if the config file exists
+ if (!config.isSet("serverUuid")) {
+
+ // Add default values
+ config.addDefault("enabled", true);
+ // Every server gets it's unique random id.
+ config.addDefault("serverUuid", UUID.randomUUID().toString());
+ // Should failed request be logged?
+ config.addDefault("logFailedRequests", false);
+ // Should the sent data be logged?
+ config.addDefault("logSentData", false);
+ // Should the response text be logged?
+ config.addDefault("logResponseStatusText", false);
+
+ // Inform the server owners about bStats
+ config.options().header(
+ "bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
+ "To honor their work, you should not disable it.\n" +
+ "This has nearly no effect on the server performance!\n" +
+ "Check out https://bStats.org/ to learn more :)"
+ ).copyDefaults(true);
+ try {
+ config.save(configFile);
+ } catch (IOException ignored) { }
+ }
+
+ // Load the data
+ enabled = config.getBoolean("enabled", true);
+ serverUUID = config.getString("serverUuid");
+ logFailedRequests = config.getBoolean("logFailedRequests", false);
+ logSentData = config.getBoolean("logSentData", false);
+ logResponseStatusText = config.getBoolean("logResponseStatusText", false);
+
+ if (enabled) {
+ boolean found = false;
+ // Search for all other bStats Metrics classes to see if we are the first one
+ for (Class> service : Bukkit.getServicesManager().getKnownServices()) {
+ try {
+ service.getField("B_STATS_VERSION"); // Our identifier :)
+ found = true; // We aren't the first
+ break;
+ } catch (NoSuchFieldException ignored) { }
+ }
+ // Register our service
+ Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
+ if (!found) {
+ // We are the first!
+ startSubmitting();
+ }
+ }
+ }
+
+ /**
+ * Checks if bStats is enabled.
+ *
+ * @return Whether bStats is enabled or not.
+ */
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ /**
+ * Adds a custom chart.
+ *
+ * @param chart The chart to add.
+ */
+ public void addCustomChart(CustomChart chart) {
+ if (chart == null) {
+ throw new IllegalArgumentException("Chart cannot be null!");
+ }
+ charts.add(chart);
+ }
+
+ /**
+ * Starts the Scheduler which submits our data every 30 minutes.
+ */
+ private void startSubmitting() {
+ final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
+ timer.scheduleAtFixedRate(new TimerTask() {
+ @Override
+ public void run() {
+ if (!plugin.isEnabled()) { // Plugin was disabled
+ timer.cancel();
+ return;
+ }
+ // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
+ // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
+ Bukkit.getScheduler().runTask(plugin, () -> submitData());
+ }
+ }, 1000 * 60 * 5, 1000 * 60 * 30);
+ // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
+ // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
+ // WARNING: Just don't do it!
+ }
+
+ /**
+ * Gets the plugin specific data.
+ * This method is called using Reflection.
+ *
+ * @return The plugin specific data.
+ */
+ public JSONObject getPluginData() {
+ JSONObject data = new JSONObject();
+
+ String pluginName = plugin.getDescription().getName();
+ String pluginVersion = plugin.getDescription().getVersion();
+
+ data.put("pluginName", pluginName); // Append the name of the plugin
+ data.put("pluginVersion", pluginVersion); // Append the version of the plugin
+ JSONArray customCharts = new JSONArray();
+ for (CustomChart customChart : charts) {
+ // Add the data of the custom charts
+ JSONObject chart = customChart.getRequestJsonObject();
+ if (chart == null) { // If the chart is null, we skip it
+ continue;
+ }
+ customCharts.add(chart);
+ }
+ data.put("customCharts", customCharts);
+
+ return data;
+ }
+
+ /**
+ * Gets the server specific data.
+ *
+ * @return The server specific data.
+ */
+ private JSONObject getServerData() {
+ // Minecraft specific data
+ int playerAmount;
+ try {
+ // Around MC 1.8 the return type was changed to a collection from an array,
+ // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
+ Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
+ playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
+ ? ((Collection>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
+ : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
+ } catch (Exception e) {
+ playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
+ }
+ int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
+ String bukkitVersion = Bukkit.getVersion();
+
+ // OS/Java specific data
+ String javaVersion = System.getProperty("java.version");
+ String osName = System.getProperty("os.name");
+ String osArch = System.getProperty("os.arch");
+ String osVersion = System.getProperty("os.version");
+ int coreCount = Runtime.getRuntime().availableProcessors();
+
+ JSONObject data = new JSONObject();
+
+ data.put("serverUUID", serverUUID);
+
+ data.put("playerAmount", playerAmount);
+ data.put("onlineMode", onlineMode);
+ data.put("bukkitVersion", bukkitVersion);
+
+ data.put("javaVersion", javaVersion);
+ data.put("osName", osName);
+ data.put("osArch", osArch);
+ data.put("osVersion", osVersion);
+ data.put("coreCount", coreCount);
+
+ return data;
+ }
+
+ /**
+ * Collects the data and sends it afterwards.
+ */
+ private void submitData() {
+ final JSONObject data = getServerData();
+
+ JSONArray pluginData = new JSONArray();
+ // Search for all other bStats Metrics classes to get their plugin data
+ for (Class> service : Bukkit.getServicesManager().getKnownServices()) {
+ try {
+ service.getField("B_STATS_VERSION"); // Our identifier :)
+
+ for (RegisteredServiceProvider> provider : Bukkit.getServicesManager().getRegistrations(service)) {
+ try {
+ pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
+ } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
+ }
+ } catch (NoSuchFieldException ignored) { }
+ }
+
+ data.put("plugins", pluginData);
+
+ // Create a new thread for the connection to the bStats server
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ // Send the data
+ sendData(plugin, data);
+ } catch (Exception e) {
+ // Something went wrong! :(
+ if (logFailedRequests) {
+ plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
+ }
+ }
+ }
+ }).start();
+ }
+
+ /**
+ * Sends the data to the bStats server.
+ *
+ * @param plugin Any plugin. It's just used to get a logger instance.
+ * @param data The data to send.
+ * @throws Exception If the request failed.
+ */
+ private static void sendData(Plugin plugin, JSONObject data) throws Exception {
+ if (data == null) {
+ throw new IllegalArgumentException("Data cannot be null!");
+ }
+ if (Bukkit.isPrimaryThread()) {
+ throw new IllegalAccessException("This method must not be called from the main thread!");
+ }
+ if (logSentData) {
+ plugin.getLogger().info("Sending data to bStats: " + data.toString());
+ }
+ HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
+
+ // Compress the data to save bandwidth
+ byte[] compressedData = compress(data.toString());
+
+ // Add headers
+ connection.setRequestMethod("POST");
+ connection.addRequestProperty("Accept", "application/json");
+ connection.addRequestProperty("Connection", "close");
+ connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
+ connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
+ connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
+ connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
+
+ // Send data
+ connection.setDoOutput(true);
+ DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
+ outputStream.write(compressedData);
+ outputStream.flush();
+ outputStream.close();
+
+ InputStream inputStream = connection.getInputStream();
+ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
+
+ StringBuilder builder = new StringBuilder();
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ builder.append(line);
+ }
+ bufferedReader.close();
+ if (logResponseStatusText) {
+ plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
+ }
+ }
+
+ /**
+ * Gzips the given String.
+ *
+ * @param str The string to gzip.
+ * @return The gzipped String.
+ * @throws IOException If the compression failed.
+ */
+ private static byte[] compress(final String str) throws IOException {
+ if (str == null) {
+ return null;
+ }
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
+ gzip.write(str.getBytes(StandardCharsets.UTF_8));
+ gzip.close();
+ return outputStream.toByteArray();
+ }
+
+ /**
+ * Represents a custom chart.
+ */
+ public static abstract class CustomChart {
+
+ // The id of the chart
+ final String chartId;
+
+ /**
+ * Class constructor.
+ *
+ * @param chartId The id of the chart.
+ */
+ CustomChart(String chartId) {
+ if (chartId == null || chartId.isEmpty()) {
+ throw new IllegalArgumentException("ChartId cannot be null or empty!");
+ }
+ this.chartId = chartId;
+ }
+
+ private JSONObject getRequestJsonObject() {
+ JSONObject chart = new JSONObject();
+ chart.put("chartId", chartId);
+ try {
+ JSONObject data = getChartData();
+ if (data == null) {
+ // If the data is null we don't send the chart.
+ return null;
+ }
+ chart.put("data", data);
+ } catch (Throwable t) {
+ if (logFailedRequests) {
+ Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
+ }
+ return null;
+ }
+ return chart;
+ }
+
+ protected abstract JSONObject getChartData() throws Exception;
+
+ }
+
+ /**
+ * Represents a custom simple pie.
+ */
+ public static class SimplePie extends CustomChart {
+
+ private final Callable callable;
+
+ /**
+ * Class constructor.
+ *
+ * @param chartId The id of the chart.
+ * @param callable The callable which is used to request the chart data.
+ */
+ public SimplePie(String chartId, Callable callable) {
+ super(chartId);
+ this.callable = callable;
+ }
+
+ @Override
+ protected JSONObject getChartData() throws Exception {
+ JSONObject data = new JSONObject();
+ String value = callable.call();
+ if (value == null || value.isEmpty()) {
+ // Null = skip the chart
+ return null;
+ }
+ data.put("value", value);
+ return data;
+ }
+ }
+
+ /**
+ * Represents a custom advanced pie.
+ */
+ public static class AdvancedPie extends CustomChart {
+
+ private final Callable