Merge branch 'breaking' into paperstuff

# Conflicts:
#	Bukkit/build.gradle
#	Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java
#	Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java
#	Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Trust.java
#	Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Visit.java
This commit is contained in:
MattBDev 2019-08-03 23:11:02 -04:00
commit bb21abb110
250 changed files with 9153 additions and 8615 deletions

View File

@ -1,22 +1,30 @@
__*NOTICE: Bukkit/Spigot versions 1.7.10 to 1.12.2 are considered legacy and will receive limited support. Please consider upgrading to 1.13 for future support. Plugins exist for 1.13+ that bring back old behaviors found in 1.8*__
# Bug report template
<!--- In order to create a valid issue report you have to follow this template. -->
<!--- Incomplete reports might be marked as invalid. -->
<!-- Feature requests and enhancements may be suggested at https://github.com/IntellectualSites/PlotSquaredSuggestions. -->
**Debug paste link:**
<!--- Enter /plot debugpaste in game or in your console and copy the output here -->
**[REQUIRED] PlotSquared Version Number:** <!--- Enter /plot version in game or in your console and copy the output here -->
**Description of the problem:**
**[REQUIRED] Spigot/Paper Version Number:**
**[REQUIRED] Minecraft Version Number:**
**Links to worlds.yml file and settings.yml file:**
<!--- Copy and paste the information to the service of your choosing and provide the link here. -->
**[REQUIRED] Description of the problem:**
**Any relevant console output or screenshots:**
**Plugins being used on the server:**
<!--- Optional but recommended --->
**How to replicate:**
<!--- If you can reproduce the issue please tell us as detailed as possible step by step how to do that -->
**Checklist**:
<!-- Make sure you have completed the following steps (put an "X" between of brackets): -->
- [] I included a `/plot debugpaste` link
- [] I included all information required in the sections above
- [] I made sure there are no duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues?utf8=%E2%9C%93&q=is%3Aissue)
- [] I made sure I am using an up-to-date version of PlotSquared
- [] I Made sure the bug/error is not caused by any other plugin
- [] I made sure the bug/error is not caused by any other plugin

View File

@ -2,7 +2,7 @@
issueOpened: >
Thank your for raising a issue. We will try and get back to you as soon as possible.
Please make sure that you followed the issue template, and provied all neccessary information.
Please make sure that you followed the issue template, and provided all neccessary information.
Failure to do so will prevent us from resolving the issue in a timely manner.
Please note that suggestions are now to be submitted to https://git.io/fN5B4 rather than this issue tracker!

1
.gitignore vendored
View File

@ -140,3 +140,4 @@ classes/
p2error.txt
*.bat
Nukkit/build/resources/main/plugin.yml
docs/

View File

@ -1,6 +1,6 @@
repositories {
maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" }
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "http://nexus.hc.to/content/repositories/pub_releases" }
maven { url = "https://repo.codemc.org/repository/maven-public" }
maven {
@ -11,16 +11,16 @@ repositories {
}
dependencies {
implementation project(':Core')
compile project(':Core')
testCompile project(':Core')
compile 'org.spigotmc:spigot-api:1.13.2-R0.1-SNAPSHOT'
compile(group: 'com.sk89q.worldedit', name: 'worldedit-bukkit', version: '7.0.0-SNAPSHOT')
compile(group: 'org.bstats', name: 'bstats-bukkit', version: '1.4')
compile 'com.destroystokyo.paper:paper-api:1.14.3-R0.1-SNAPSHOT'
//implementation 'com.onarandombox.multiversecore:Multiverse-Core:3.0.0-SNAPSHOT'
implementation 'org.spigotmc:spigot-api:1.14.3-R0.1-SNAPSHOT'
compile(group: 'com.sk89q.worldedit', name: 'worldedit-bukkit', version: '7.0.0')
compile "io.papermc:paperlib:1.0.1"
compile("net.milkbowl.vault:VaultAPI:1.7") {
exclude module: 'bukkit'
}
compile 'org.spigotmc:spigot-api:1.13.2-R0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
@ -41,7 +41,12 @@ jar.enabled = false
shadowJar {
dependencies {
include(dependency(':Core'))
include(dependency('org.bstats:bstats-bukkit:1.4'))
// update notification stuff
include(dependency('com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT'))
include(dependency('com.squareup.retrofit2:retrofit:2.4.0'))
include(dependency('com.squareup.okhttp3:okhttp:3.14.0'))
include(dependency('com.squareup.okio:okio:2.2.2'))
include(dependency('org.jetbrains.kotlin:kotlin-stdlib:1.3.30'))
include(dependency("io.papermc:paperlib:1.0.1"))
}
relocate 'io.papermc.lib', 'com.github.intellectualsites.plotsquared.bukkit.paperlib'

View File

@ -9,7 +9,7 @@ import com.github.intellectualsites.plotsquared.bukkit.uuid.*;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.plot.IPlotMain;
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.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
@ -42,8 +42,19 @@ import org.bukkit.generator.ChunkGenerator;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
import javax.annotation.Nullable;
import java.io.File;
@ -57,25 +68,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Getter private static WorldEdit worldEdit;
static {
// Disable AWE as otherwise both fail to load
PluginManager manager = Bukkit.getPluginManager();
try {
Settings.load(new File("plugins/PlotSquared/config/settings.yml"));
} catch (Throwable ignored) {
}
// Force WorldEdit to load
try {
System.out.println("[P2] Force loading WorldEdit");
if (!manager.isPluginEnabled("WorldEdit")) {
manager.enablePlugin(WorldEditPlugin.getPlugin(WorldEditPlugin.class));
}
System.out.println("[P2] Testing platform capabilities");
WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS);
} catch (final Throwable throwable) {
throw new IllegalStateException(
"Failed to force load WorldEdit." + " Road schematics will fail to generate",
throwable);
}
}
private final LegacyMappings legacyMappings = new BukkitLegacyMappings();
@ -115,17 +111,54 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override public void onEnable() {
this.pluginName = getDescription().getName();
getServer().getName();
PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer);
PaperLib.suggestPaper(this);
new PlotSquared(this, "Bukkit");
if (Settings.Enabled_Components.METRICS) {
this.startMetrics();
} else {
PlotSquared.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(getPluginName()));
if (PlotSquared.get().IMP.getServerVersion()[1] < 13) {
System.out.println(
"You can't use this version of PlotSquared on a server less than Minecraft 1.13.2.");
System.out
.println("Please check the download page for the link to the legacy versions.");
System.out.println("The server will now be shutdown to prevent any corruption.");
Bukkit.shutdown();
return;
}
// Check for updates
if (PlotSquared.get().getUpdateUtility() != null) {
final UpdateUtility updateUtility = PlotSquared.get().getUpdateUtility();
updateUtility
.checkForUpdate(this.getPluginVersionString(), ((updateDescription, throwable) -> {
Bukkit.getScheduler().runTask(BukkitMain.this, () -> {
getLogger().info("-------- PlotSquared Update Check --------");
if (throwable != null) {
getLogger().severe(String
.format("Could not check for update. Reason: %s",
throwable.getMessage()));
} else {
if (updateDescription == null) {
getLogger().info(
"You appear to be running the latest version of PlotSquared. Congratulations!");
} else {
getLogger()
.info("There appears to be a PlotSquared update available!");
getLogger().info(String.format("You are running version %s,"
+ " the newest available version is %s",
getPluginVersionString(), updateDescription.getVersion()));
getLogger().info(
String.format("Update URL: %s", updateDescription.getUrl()));
}
}
getLogger().info("-------- PlotSquared Update Check --------");
});
}));
} else {
getLogger().warning("Update checking disabled. Skipping.");
}
this.startMetrics();
if (Settings.Enabled_Components.WORLDS) {
TaskManager.IMP.taskRepeat(this::unload, 20);
try {
@ -165,11 +198,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
continue;
}
final PlotId id = PlotId.fromString(name);
if (id != null) {
PlotId id;
try {
id = PlotId.fromString(name);
} catch (IllegalArgumentException ignored) {
continue;
}
final Plot plot = area.getOwnedPlot(id);
if (plot != null) {
if (PlotPlayer.wrap(plot.owner) == null) {
if (!MainUtil.isServerOwned(plot) || PlotPlayer.wrap(plot.getOwner()) == null) {
if (world.getKeepSpawnInMemory()) {
world.setKeepSpawnInMemory(false);
return;
@ -195,16 +232,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
continue outer;
}
} else {
result = world
.unloadChunk(chunkI.getX(), chunkI.getZ(), true, false);
result = world.unloadChunk(chunkI.getX(), chunkI.getZ(), true);
}
if (!result) {
continue outer;
}
} while (index < chunks.length
&& System.currentTimeMillis() - start < 5);
if (System.currentTimeMillis() - start > 5) {
return;
}
} while (index < chunks.length);
}
}
}
@ -219,7 +255,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override public void log(@NonNull String message) {
try {
message = C.color(message);
message = Captions.color(message);
if (!Settings.Chat.CONSOLE_COLOR) {
message = ChatColor.stripColor(message);
}
@ -233,10 +269,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
this.getServer().getPluginManager().disablePlugin(this);
}
@Override public void disable() {
onDisable();
}
@Override public int[] getPluginVersion() {
String ver = getDescription().getVersion();
if (ver.contains("-")) {
@ -272,10 +304,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
@Override @SuppressWarnings("deprecation") public void runEntityTask() {
PlotSquared.log(C.PREFIX + "KillAllEntities started.");
TaskManager
.runTaskRepeat(() -> PlotSquared.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea plotArea) {
PlotSquared.log(Captions.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(() -> PlotSquared.get().forEachPlotArea(plotArea -> {
final World world = Bukkit.getWorld(plotArea.worldname);
try {
if (world == null) {
@ -287,15 +317,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
Entity entity = iterator.next();
switch (entity.getType()) {
case EGG:
case COMPLEX_PART:
case FISHING_HOOK:
case ENDER_SIGNAL:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD:
case EXPERIENCE_ORB:
case LEASH_HITCH:
case FIREWORK:
case WEATHER:
case LIGHTNING:
case WITHER_SKULL:
case UNKNOWN:
@ -307,7 +334,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case SNOWBALL:
case SHULKER_BULLET:
case SPECTRAL_ARROW:
case TIPPED_ARROW:
case ENDER_PEARL:
case ARROW:
case LLAMA_SPIT:
@ -355,15 +381,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
iterator.remove();
entity.remove();
}
continue;
} else {
continue;
}
continue;
case SMALL_FIREBALL:
case FIREBALL:
case DRAGON_FIREBALL:
case DROPPED_ITEM:
if (Settings.Enabled_Components.KILL_ROAD_ITEMS) {
if (Settings.Enabled_Components.KILL_ROAD_ITEMS && plotArea
.getOwnedPlotAbs(BukkitUtil.getLocation(entity.getLocation()))
== null) {
entity.remove();
}
// dropped item
@ -372,6 +398,53 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case FALLING_BLOCK:
// managed elsewhere
continue;
case SHULKER:
if (Settings.Enabled_Components.KILL_ROAD_MOBS) {
LivingEntity livingEntity = (LivingEntity) entity;
List<MetadataValue> meta = entity.getMetadata("shulkerPlot");
if (!meta.isEmpty()) {
if (livingEntity.isLeashed()) {
continue;
}
List<MetadataValue> keep = entity.getMetadata("keep");
if (!keep.isEmpty()) {
continue;
}
PlotId originalPlotId = (PlotId) meta.get(0).value();
if (originalPlotId != null) {
com.github.intellectualsites.plotsquared.plot.object.Location
pLoc = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = pLoc.getPlotArea();
if (area != null) {
PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc));
if (!originalPlotId.equals(currentPlotId) && (
currentPlotId == null || !area
.getPlot(originalPlotId)
.equals(area.getPlot(currentPlotId)))) {
if (entity.hasMetadata("ps-tmp-teleport")) {
continue;
}
iterator.remove();
entity.remove();
}
}
}
} else {
//This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java)
com.github.intellectualsites.plotsquared.plot.object.Location
pLoc = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = pLoc.getPlotArea();
if (area != null) {
PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc));
if (currentPlotId != null) {
entity.setMetadata("shulkerPlot", new FixedMetadataValue(
(Plugin) PlotSquared.get().IMP, currentPlotId));
}
}
}
}
continue;
case LLAMA:
case DONKEY:
case MULE:
@ -419,6 +492,16 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case WITHER:
case WOLF:
case ZOMBIE:
case PARROT:
case SALMON:
case DOLPHIN:
case TROPICAL_FISH:
case DROWNED:
case COD:
case TURTLE:
case PUFFERFISH:
case PHANTOM:
case ILLUSIONER:
default: {
if (Settings.Enabled_Components.KILL_ROAD_MOBS) {
Location location = entity.getLocation();
@ -454,94 +537,33 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
continue;
}
case SHULKER: {
if (Settings.Enabled_Components.KILL_ROAD_MOBS) {
LivingEntity livingEntity = (LivingEntity) entity;
List<MetadataValue> meta = entity.getMetadata("plot");
if (meta != null && !meta.isEmpty()) {
if (livingEntity.isLeashed())
continue;
List<MetadataValue> keep = entity.getMetadata("keep");
if (keep != null && !keep.isEmpty())
continue;
PlotId originalPlotId = (PlotId) meta.get(0).value();
if (originalPlotId != null) {
com.github.intellectualsites.plotsquared.plot.object.Location
pLoc =
BukkitUtil.getLocation(entity.getLocation());
PlotArea area = pLoc.getPlotArea();
if (area != null) {
PlotId currentPlotId =
PlotId.of(area.getPlotAbs(pLoc));
if (!originalPlotId.equals(currentPlotId) && (
currentPlotId == null || !area
.getPlot(originalPlotId)
.equals(area.getPlot(currentPlotId)))) {
if (entity.hasMetadata("ps-tmp-teleport")) {
continue;
}
iterator.remove();
entity.remove();
}
}
}
} else {
//This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java)
com.github.intellectualsites.plotsquared.plot.object.Location
pLoc = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = pLoc.getPlotArea();
if (area != null) {
PlotId currentPlotId =
PlotId.of(area.getPlotAbs(pLoc));
if (currentPlotId != null) {
entity.setMetadata("plot",
new FixedMetadataValue(
(Plugin) PlotSquared.get().IMP,
currentPlotId));
}
}
}
}
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}), 20);
}
@Override @Nullable
public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
public final ChunkGenerator getDefaultWorldGenerator(@NotNull final String worldName,
final String id) {
final IndependentPlotGenerator result;
if (id != null && id.equalsIgnoreCase("single")) {
result = new SingleWorldGenerator();
} else {
result = PlotSquared.get().IMP.getDefaultGenerator();
if (!PlotSquared.get().setupPlotWorld(world, id, result)) {
if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) {
return null;
}
}
return (ChunkGenerator) result.specify(world);
return (ChunkGenerator) result.specify(worldName);
}
@Override public void registerPlayerEvents() {
final PlayerEvents main = new PlayerEvents();
getServer().getPluginManager().registerEvents(main, this);
try {
getServer().getClass().getMethod("spigot");
Class.forName("org.bukkit.event.entity.EntitySpawnEvent");
getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this);
} catch (final NoSuchMethodException | ClassNotFoundException ignored) {
PlotSquared.debug("Not running Spigot. Skipping EntitySpawnListener event.");
}
}
@Override public void registerInventoryEvents() {
// Part of PlayerEvents - can be moved if necessary
}
@Override public void registerPlotPlusEvents() {
@ -613,55 +635,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return new BukkitSetupUtils();
}
@Override public UUIDHandlerImplementation initUUIDHandler() {
boolean checkVersion = false;
try {
OfflinePlayer.class.getDeclaredMethod("getUniqueId");
checkVersion = true;
} catch (Throwable ignore) {
}
final UUIDWrapper wrapper;
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper();
} else {
wrapper = new OfflineUUIDWrapper();
}
Settings.UUID.OFFLINE = true;
} else if (checkVersion) {
wrapper = new DefaultUUIDWrapper();
Settings.UUID.OFFLINE = false;
} else {
if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper();
} else {
wrapper = new OfflineUUIDWrapper();
}
Settings.UUID.OFFLINE = true;
}
if (!checkVersion) {
PlotSquared.log(C.PREFIX
+ " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false;
} else {
AbstractTitle.TITLE_CLASS = new DefaultTitle_111();
if (wrapper instanceof DefaultUUIDWrapper
|| wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
Settings.UUID.NATIVE_UUID_PROVIDER = true;
}
}
if (Settings.UUID.OFFLINE) {
PlotSquared.log(C.PREFIX + " &6" + getPluginName()
+ " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
+ "Bukkit");
} else {
PlotSquared.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs");
}
if (Settings.UUID.USE_SQLUUIDHANDLER) {
return new SQLUUIDHandler(wrapper);
} else {
return new FileUUIDHandler(wrapper);
@Override public void startMetrics() {
if (this.metricsStarted) {
return;
}
this.metricsStarted = true;
Metrics metrics = new Metrics(this);// bstats
PlotSquared.log(Captions.PREFIX + "&6Metrics enabled.");
}
@Override public ChunkManager initChunkManager() {
@ -684,7 +664,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@Override public IndependentPlotGenerator getDefaultGenerator() {
@NotNull @Override public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen();
}
@ -692,15 +672,37 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return new BukkitInventoryUtil();
}
@Override public void startMetrics() {
if (this.metricsStarted) {
return;
@Override public UUIDHandlerImplementation initUUIDHandler() {
final UUIDWrapper wrapper;
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper();
} else {
wrapper = new OfflineUUIDWrapper();
}
Settings.UUID.OFFLINE = true;
} else {
wrapper = new DefaultUUIDWrapper();
Settings.UUID.OFFLINE = false;
}
if (!Bukkit.getVersion().contains("git-Spigot")) {
if (wrapper instanceof DefaultUUIDWrapper
|| wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
Settings.UUID.NATIVE_UUID_PROVIDER = true;
}
}
if (Settings.UUID.OFFLINE) {
PlotSquared.log(Captions.PREFIX + " &6" + getPluginName()
+ " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
+ "Bukkit");
} else {
PlotSquared.log(Captions.PREFIX + " &6" + getPluginName() + " is using online UUIDs");
}
if (Settings.UUID.USE_SQLUUIDHANDLER) {
return new SQLUUIDHandler(wrapper);
} else {
return new FileUUIDHandler(wrapper);
}
System.setProperty("bstats.relocatecheck",
"false"); // We do not want to relocate the package...
new org.bstats.bukkit.Metrics(this); // bstats
PlotSquared.log(C.PREFIX + "&6Metrics enabled.");
this.metricsStarted = true;
}
@Override public void setGenerator(@NonNull final String worldName) {
@ -730,6 +732,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return;
}
}
assert world != null;
ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) {
PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen);
@ -744,11 +747,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return new BukkitSchematicHandler();
}
@Override public AbstractTitle initTitleManager() {
// Already initialized in UUID handler
return AbstractTitle.TITLE_CLASS;
}
@Override @Nullable public PlotPlayer wrapPlayer(final Object player) {
if (player instanceof Player) {
return BukkitUtil.getPlayer((Player) player);

View File

@ -5,7 +5,10 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import org.bukkit.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.Statistic.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
@ -320,34 +323,6 @@ public class FancyMessage
return this;
}
/**
* Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
* <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
*
* @param which The achievement to display.
* @return This builder instance.
*/
public FancyMessage achievementTooltip(final Achievement which) {
try {
Object achievement = Reflection
.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement",
Achievement.class).invoke(null, which);
return achievementTooltip(
(String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name")
.get(achievement));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
} catch (IllegalArgumentException e) {
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
/**
* Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text.
* <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
@ -648,9 +623,7 @@ public class FancyMessage
* @return This builder instance.
*/
public FancyMessage translationReplacements(final FancyMessage... replacements) {
for (FancyMessage str : replacements) {
latest().translationReplacements.add(str);
}
Collections.addAll(latest().translationReplacements, replacements);
dirty = true;
@ -869,7 +842,6 @@ public class FancyMessage
* <li>The core text of the message part.</li>
* </ol>
* The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort.
* </p>
* <p>
* Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.</p>
*

View File

@ -134,7 +134,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
json.endObject();
} catch (IOException e) {
Bukkit.getLogger()
.log(Level.WARNING, "A problem occured during writing of JSON string", e);
.log(Level.WARNING, "A problem occurred during writing of JSON string", e);
}
}

View File

@ -43,10 +43,6 @@ public final class Reflection {
*/
public synchronized static String getVersion() {
if (_versionString == null) {
if (Bukkit.getServer() == null) {
// The server hasn't started, static initializer call?
return null;
}
String name = Bukkit.getServer().getClass().getPackage().getName();
_versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
}
@ -180,15 +176,11 @@ public final class Reflection {
* @return A method object with the specified name declared by the specified class.
*/
public synchronized static Method getMethod(Class<?> clazz, String name, Class<?>... args) {
if (!_loadedMethods.containsKey(clazz)) {
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}
_loadedMethods.computeIfAbsent(clazz, k -> new HashMap<>());
Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames =
_loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
}
loadedMethodNames.computeIfAbsent(name, k -> new HashMap<>());
Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args);

View File

@ -10,7 +10,7 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory;
import com.github.intellectualsites.plotsquared.plot.commands.RequiredType;
import com.github.intellectualsites.plotsquared.plot.commands.SubCommand;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -55,14 +55,15 @@ import java.util.Map.Entry;
Class<?> clazz = Class.forName(args[0]);
newWrapper = (UUIDWrapper) clazz.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot uuidconvert <lower|offline|online>");
return false;
}
}
if (args.length != 2 || !"-o".equals(args[1])) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot uuidconvert " + args[0] + " - o");
MainUtil.sendMessage(player, "&cBe aware of the following!");
MainUtil.sendMessage(player,
"&8 - &cUse the database command or another method to backup your plots beforehand");
@ -109,7 +110,8 @@ import java.util.Map.Entry;
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception ignored) {
MainUtil.sendMessage(player, C.PREFIX + "Invalid playerdata: " + current);
MainUtil.sendMessage(player,
Captions.PREFIX + "Invalid playerdata: " + current);
}
}
}
@ -137,7 +139,7 @@ import java.util.Map.Entry;
}
} catch (Throwable ignored) {
MainUtil.sendMessage(player,
C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
Captions.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
@ -171,8 +173,7 @@ import java.util.Map.Entry;
}
MainUtil.sendMessage(player, "&7 - Replacing cache");
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
String name = UUIDHandler.getName(entry.getKey());
if (name != null) {
@ -185,8 +186,7 @@ import java.util.Map.Entry;
File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) {
try {
List<String> lines =
Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
@ -248,11 +248,7 @@ import java.util.Map.Entry;
}
}
DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()),
new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Recovery was successful!");
}
});
() -> MainUtil.sendMessage(player, "&6Recovery was successful!"));
return;
}
} catch (Exception e) {
@ -276,21 +272,15 @@ import java.util.Map.Entry;
MainUtil.sendMessage(player, "&7 - Populating tables");
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots());
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&aConversion complete!");
}
});
}
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&aConversion complete!"));
});
MainUtil.sendMessage(player, "&aIt is now safe for players to join");
MainUtil.sendMessage(player,
"&cConversion is still in progress, you will be notified when it is complete");
}
});
return true;
}

View File

@ -1,63 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.PlotCluster;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when a flag is removed from a plot.
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot.
*
* @param flag Flag that was removed
* @param cluster PlotCluster from which the flag was removed
*/
public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the cluster involved.
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return this.cluster;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override public HandlerList getHandlers() {
return handlers;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -6,8 +6,7 @@ import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
/**
*
*/
public class PlayerLeavePlotEvent extends PlayerEvent {

View File

@ -7,8 +7,7 @@ import org.bukkit.event.HandlerList;
import java.util.UUID;
/**
*
*/
public class PlayerPlotHelperEvent extends PlotEvent {

View File

@ -4,6 +4,7 @@ import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
@ -24,7 +25,8 @@ public class BukkitAugmentedGenerator extends BlockPopulator {
return generator;
}
@Override public void populate(World world, Random r, Chunk chunk) {
AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null);
@Override
public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk source) {
AugmentedUtils.generate(world.getName(), source.getX(), source.getZ(), null);
}
}

View File

@ -4,21 +4,19 @@ import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil;
import com.github.intellectualsites.plotsquared.bukkit.util.block.GenChunk;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc;
import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.MathMan;
import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue;
import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@ -28,7 +26,8 @@ import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator
implements GeneratorWrapper<ChunkGenerator> {
private final GenChunk chunkSetter;
@SuppressWarnings("unused") public final boolean PAPER_ASYNC_SAFE = true;
private final IndependentPlotGenerator plotGenerator;
private final ChunkGenerator platformGenerator;
private final boolean full;
@ -41,24 +40,8 @@ public class BukkitPlotGenerator extends ChunkGenerator
}
this.plotGenerator = generator;
this.platformGenerator = this;
populators = new ArrayList<>();
this.populators.add(new BlockPopulator() {
private LocalBlockQueue queue;
@Override public void populate(World world, Random r, Chunk c) {
if (queue == null) {
queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
}
PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ());
ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area)) {
queue.flush();
}
}
});
this.chunkSetter = new GenChunk(null, null);
this.populators = new ArrayList<>();
this.populators.add(new PlotBlockPopulator(this.plotGenerator));
this.full = true;
MainUtil.initCache();
}
@ -69,110 +52,8 @@ public class BukkitPlotGenerator extends ChunkGenerator
+ " is already a BukkitPlotGenerator!");
}
this.full = false;
PlotSquared.debug("BukkitPlotGenerator does not fully support: " + cg);
this.platformGenerator = cg;
this.plotGenerator = new IndependentPlotGenerator() {
@Override public void processSetup(SetupObject setup) {
}
@Override public void initialize(PlotArea area) {
}
@Override public PlotManager getNewPlotManager() {
return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotManager();
}
@Override public String getName() {
return cg.getClass().getName();
}
@Override
public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return PlotSquared.get().IMP.getDefaultGenerator()
.getNewPlotArea(world, id, min, max);
}
@Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) {
BlockBucket[][] blockBuckets = new BlockBucket[16][];
HybridPlotWorld hpw = (HybridPlotWorld) settings;
// Bedrock
if (hpw.PLOT_BEDROCK) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
blockBuckets[0][(z << 4) | x] =
BlockBucket.withSingle(PlotBlock.get("bedrock"));
}
}
}
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
for (int y = 1; y < hpw.PLOT_HEIGHT; y++) {
blockBuckets[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK;
}
blockBuckets[hpw.PLOT_HEIGHT >> 4][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4)
| x] = hpw.MAIN_BLOCK;
}
}
return blockBuckets;
}
@Override
public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) {
World w = BukkitUtil.getWorld(world);
Location min = result.getMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
Random r = new Random(MathMan.pair((short) cx, (short) cz));
BiomeGrid grid = new BiomeGrid() {
@Override public void setBiome(int x, int z, Biome biome) {
result.setBiome(x, z, biome.name());
}
@Override public Biome getBiome(int arg0, int arg1) {
return Biome.FOREST;
}
};
try {
// ChunkData will spill a bit
ChunkData data = cg.generateChunkData(w, r, cx, cz, grid);
if (data != null) {
return;
}
} catch (Throwable ignored) {
}
/* TODO: Redo this
// Populator spillage
short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid);
if (tmp != null) {
for (int i = 0; i < tmp.length; i++) {
short[] section = tmp[i];
if (section == null) {
if (i < 7) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = i << 4; y < (i << 4) + 16; y++) {
result.setBlock(x, y, z, PlotBlock.get("air"));
}
}
}
}
continue;
}
for (int j = 0; j < section.length; j++) {
int x = MainUtil.x_loc[i][j];
int y = MainUtil.y_loc[i][j];
int z = MainUtil.z_loc[i][j];
result.setBlock(x, y, z, section[j], (byte) 0);
}
}
}
*/
for (BlockPopulator populator : cg.getDefaultPopulators(w)) {
populator.populate(w, r, w.getChunkAt(cx, cz));
}
}
};
this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0));
this.plotGenerator = new DelegatePlotGenerator(cg, world);
MainUtil.initCache();
}
@ -192,7 +73,7 @@ public class BukkitPlotGenerator extends ChunkGenerator
return this.platformGenerator;
}
@Override public List<BlockPopulator> getDefaultPopulators(World world) {
@Override @NotNull public List<BlockPopulator> getDefaultPopulators(@NotNull World world) {
try {
if (!this.loaded) {
String name = world.getName();
@ -226,50 +107,54 @@ public class BukkitPlotGenerator extends ChunkGenerator
if (populators == null && platformGenerator != null) {
populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world));
}
if (populators != null) {
for (BlockPopulator populator : this.populators) {
if (!existing.contains(populator)) {
toAdd.add(populator);
}
}
}
return toAdd;
}
@Override
public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) {
GenChunk result = this.chunkSetter;
@Override @NotNull
public ChunkData generateChunkData(@NotNull World world, @NotNull Random random, int x, int z,
@NotNull BiomeGrid biome) {
GenChunk result = new GenChunk();
if (this.getPlotGenerator() instanceof SingleWorldGenerator) {
if (result.getCd() != null) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
grid.setBiome(x, z, Biome.PLAINS);
if (result.getChunkData() != null) {
for (int chunkX = 0; chunkX < 16; chunkX++) {
for (int chunkZ = 0; chunkZ < 16; chunkZ++) {
biome.setBiome(chunkX, chunkZ, Biome.PLAINS);
}
}
return result.getCd();
return result.getChunkData();
}
}
// Set the chunk location
result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
result.setChunk(new ChunkWrapper(world.getName(), x, z));
// Set the result data
result.setCd(createChunkData(world));
result.grid = grid;
result.setChunkData(createChunkData(world));
result.biomeGrid = biome;
result.result = null;
// Catch any exceptions (as exceptions usually thrown)
try {
// Fill the result data if necessary
if (this.platformGenerator != this) {
return this.platformGenerator.generateChunkData(world, random, cx, cz, grid);
return this.platformGenerator.generateChunkData(world, random, x, z, biome);
} else {
generate(world, result);
generate(new ChunkLoc(x, z), world, result);
}
} catch (Throwable e) {
e.printStackTrace();
}
// Return the result data
return result.getCd();
return result.getChunkData();
}
private void generate(World world, ScopedLocalBlockQueue result) {
private void generate(ChunkLoc loc, World world, ScopedLocalBlockQueue result) {
// Load if improperly loaded
if (!this.loaded) {
String name = world.getName();
@ -277,17 +162,17 @@ public class BukkitPlotGenerator extends ChunkGenerator
this.loaded = true;
}
// Process the chunk
if (ChunkManager.preProcessChunk(result)) {
if (ChunkManager.preProcessChunk(loc, result)) {
return;
}
PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
try {
this.plotGenerator.generateChunk(this.chunkSetter, area);
this.plotGenerator.generateChunk(result, area);
} catch (Throwable e) {
// Recover from generator error
e.printStackTrace();
}
ChunkManager.postProcessChunk(result);
ChunkManager.postProcessChunk(loc, result);
}
/**
@ -298,7 +183,7 @@ public class BukkitPlotGenerator extends ChunkGenerator
* @param z Ignored
* @return always true
*/
@Override public boolean canSpawn(World world, int x, int z) {
@Override public boolean canSpawn(@NotNull final World world, final int x, final int z) {
return true;
}
@ -313,10 +198,11 @@ public class BukkitPlotGenerator extends ChunkGenerator
}
}
@Override public boolean equals(Object obj) {
@Override public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
return toString().equals(obj.toString()) || toString().equals(obj.getClass().getName());
}
}

View File

@ -0,0 +1,91 @@
package com.github.intellectualsites.plotsquared.bukkit.generator;
import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.BlockBucket;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import com.github.intellectualsites.plotsquared.plot.object.PlotManager;
import com.github.intellectualsites.plotsquared.plot.util.MathMan;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import lombok.RequiredArgsConstructor;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;
import java.util.Random;
@RequiredArgsConstructor final class DelegatePlotGenerator extends IndependentPlotGenerator {
private final ChunkGenerator chunkGenerator;
private final String world;
@Override public void initialize(PlotArea area) {
}
@Override public String getName() {
return this.chunkGenerator.getClass().getName();
}
@Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max);
}
@Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) {
BlockBucket[][] blockBuckets = new BlockBucket[16][];
HybridPlotWorld hpw = (HybridPlotWorld) settings;
// Bedrock
if (hpw.PLOT_BEDROCK) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
blockBuckets[0][(z << 4) | x] =
BlockBucket.withSingle(PlotBlock.get("bedrock"));
}
}
}
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
for (int y = 1; y < hpw.PLOT_HEIGHT; y++) {
blockBuckets[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK;
}
blockBuckets[hpw.PLOT_HEIGHT >> 4][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) | x] =
hpw.MAIN_BLOCK;
}
}
return blockBuckets;
}
@Override public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) {
World world = BukkitUtil.getWorld(this.world);
Location min = result.getMin();
int chunkX = min.getX() >> 4;
int chunkZ = min.getZ() >> 4;
Random random = new Random(MathMan.pair((short) chunkX, (short) chunkZ));
try {
ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() {
@Override public void setBiome(@Range(from = 0, to = 15) int x,
@Range(from = 0, to = 15) int z, Biome biome) {
result.setBiome(x, z, biome.name());
}
@Override @NotNull public Biome getBiome(int x, int z) {
return Biome.FOREST;
}
};
chunkGenerator.generateChunkData(world, random, chunkX, chunkZ, grid);
return;
} catch (Throwable ignored) {
}
for (BlockPopulator populator : chunkGenerator.getDefaultPopulators(world)) {
populator.populate(world, random, world.getChunkAt(chunkX, chunkZ));
}
}
}

View File

@ -0,0 +1,36 @@
package com.github.intellectualsites.plotsquared.bukkit.generator;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue;
import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import lombok.RequiredArgsConstructor;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
@RequiredArgsConstructor final class PlotBlockPopulator extends BlockPopulator {
private final IndependentPlotGenerator plotGenerator;
private LocalBlockQueue queue;
@Override public void populate(@NotNull final World world, @NotNull final Random random,
@NotNull final Chunk source) {
if (this.queue == null) {
this.queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
}
final PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
final ChunkWrapper wrap = new ChunkWrapper(area.worldname, source.getX(), source.getZ());
final ScopedLocalBlockQueue chunk = this.queue.getForChunk(wrap.x, wrap.z);
if (this.plotGenerator.populateChunk(chunk, area)) {
this.queue.flush();
}
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.bukkit.listeners;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -32,8 +32,7 @@ import java.util.HashSet;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused")
public class ChunkListener implements Listener {
@SuppressWarnings("unused") public class ChunkListener implements Listener {
private RefMethod methodGetHandleChunk;
private RefField mustSave;
@ -60,8 +59,7 @@ public class ChunkListener implements Listener {
for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false);
}
TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
TaskManager.runTaskRepeat(() -> {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
@ -70,10 +68,9 @@ public class ChunkListener implements Listener {
continue;
}
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap =
w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse = chunkMap.getClass()
.getDeclaredMethod("isChunkInUse", int.class, int.class);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse =
chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse
@ -97,12 +94,11 @@ public class ChunkListener implements Listener {
if (System.currentTimeMillis() - start > 5) {
return;
}
chunk.unload(true, false);
chunk.unload(true);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}, 1);
}
@ -112,20 +108,20 @@ public class ChunkListener implements Listener {
}
Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get() == true) {
if ((Boolean) field.get()) {
field.set(false);
if (chunk.isLoaded()) {
ignoreUnload = true;
chunk.unload(false, false);
chunk.unload(false);
ignoreUnload = false;
}
}
return true;
}
public boolean shouldSave(String world, int X, int Z) {
int x = X << 4;
int z = Z << 4;
public boolean shouldSave(String world, int chunkX, int chunkZ) {
int x = chunkX << 4;
int z = chunkZ << 4;
int x2 = x + 15;
int z2 = z + 15;
Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
@ -148,13 +144,12 @@ public class ChunkListener implements Listener {
return plot != null && plot.hasOwner();
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
@EventHandler public void onChunkUnload(ChunkUnloadEvent event) {
if (ignoreUnload) {
return;
}
if (Settings.Chunk_Processor.AUTO_TRIM) {
Chunk chunk = event.getChunk();
if (Settings.Chunk_Processor.AUTO_TRIM) {
String world = chunk.getWorld().getName();
if (PlotSquared.get().hasPlotArea(world)) {
if (unloadChunk(world, chunk, true)) {
@ -163,17 +158,15 @@ public class ChunkListener implements Listener {
}
}
if (processChunk(event.getChunk(), true)) {
event.setCancelled(true);
chunk.setForceLoaded(true);
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {
processChunk(event.getChunk(), false);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
@EventHandler(priority = EventPriority.LOWEST) public void onItemSpawn(ItemSpawnEvent event) {
Item entity = event.getEntity();
Chunk chunk = entity.getLocation().getChunk();
if (chunk == this.lastChunk) {
@ -226,14 +219,13 @@ public class ChunkListener implements Listener {
private void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get();
Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
Integer task = TaskManager.runTaskRepeat(() -> {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
.debug(Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true);
return;
}
BlockState[] tiles = chunk.getTileEntities();
@ -241,8 +233,8 @@ public class ChunkListener implements Listener {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
.debug(Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true);
return;
}
long start = System.currentTimeMillis();
@ -251,15 +243,14 @@ public class ChunkListener implements Listener {
if (i >= tiles.length) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
PlotSquared.debug(
Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true);
return;
}
tiles[i].getBlock().setType(Material.AIR, false);
i++;
}
}
}, 5);
TaskManager.tasks.put(currentIndex, task);
}
@ -277,14 +268,14 @@ public class ChunkListener implements Listener {
}
}
PlotSquared.debug(
C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4)
+ "," + (chunk.getX() << 4));
Captions.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX()
<< 4) + "," + (chunk.getX() << 4));
}
if (tiles.length > Settings.Chunk_Processor.MAX_TILES) {
if (unload) {
PlotSquared.debug(
C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (
chunk.getX() << 4));
Captions.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + ","
+ (chunk.getX() << 4));
cleanChunk(chunk);
return true;
}

View File

@ -7,6 +7,7 @@ import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
@ -18,23 +19,52 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.vehicle.*;
import org.bukkit.event.vehicle.VehicleBlockCollisionEvent;
import org.bukkit.event.vehicle.VehicleCreateEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.event.vehicle.VehicleUpdateEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@SuppressWarnings("unused") public class EntitySpawnListener implements Listener {
public class EntitySpawnListener implements Listener {
private final static String KEY = "P2";
private static boolean ignoreTP = false;
private static boolean hasPlotArea = false;
private static String areaName = null;
public static void testNether(Entity entity) {
@NotNull World world = entity.getWorld();
if (world.getEnvironment() != World.Environment.NETHER
&& world.getEnvironment() != World.Environment.THE_END) {
return;
}
test(entity);
}
public static void testCreate(Entity entity) {
@NotNull World world = entity.getWorld();
if (areaName == world.getName()) {
} else {
areaName = world.getName();
hasPlotArea = PlotSquared.get().hasPlotArea(areaName);
}
if (!hasPlotArea)
return;
test(entity);
}
public static void test(Entity entity) {
List<MetadataValue> meta = entity.getMetadata("plotworld");
World world = entity.getLocation().getWorld();
if (meta == null || meta.isEmpty()) {
@NotNull World world = entity.getWorld();
List<MetadataValue> meta = entity.getMetadata(KEY);
if (meta.isEmpty()) {
if (PlotSquared.get().hasPlotArea(world.getName())) {
entity.setMetadata("plotworld",
entity.setMetadata(KEY,
new FixedMetadataValue((Plugin) PlotSquared.get().IMP, entity.getLocation()));
}
} else {
@ -65,16 +95,17 @@ import java.util.List;
Entity entity = event.getEntity();
Location location = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
if (!location.isPlotArea()) {
return;
}
Plot plot = area.getOwnedPlotAbs(location);
Plot plot = location.getOwnedPlotAbs();
if (plot == null) {
if (!area.MOB_SPAWNING) {
EntityType type = entity.getType();
switch (type) {
case DROPPED_ITEM:
if (Settings.Enabled_Components.KILL_ROAD_ITEMS) {
event.setCancelled(true);
break;
}
case PLAYER:
@ -95,48 +126,47 @@ import java.util.List;
event.setCancelled(true);
}
case SHULKER:
if (!entity.hasMetadata("plot")) {
entity.setMetadata("plot",
if (!entity.hasMetadata("shulkerPlot")) {
entity.setMetadata("shulkerPlot",
new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot.getId()));
}
}
}
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {
@NotNull Chunk chunk = event.getChunk();
for (Entity entity : chunk.getEntities()) {
testCreate(entity);
}
}
@EventHandler public void onVehicle(VehicleUpdateEvent event) {
test(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleDestroyEvent event) {
test(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleEntityCollisionEvent event) {
test(event.getVehicle());
testNether(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleCreateEvent event) {
test(event.getVehicle());
testCreate(event.getVehicle());
}
@EventHandler public void onVehicle(VehicleBlockCollisionEvent event) {
test(event.getVehicle());
testNether(event.getVehicle());
}
@EventHandler public void onTeleport(EntityTeleportEvent event) {
Entity ent = event.getEntity();
if (ent instanceof Vehicle || ent instanceof ArmorStand)
test(event.getEntity());
if (ent instanceof Vehicle || ent instanceof ArmorStand) {
testNether(event.getEntity());
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException {
test(event.getVehicle());
public void vehicleMove(VehicleMoveEvent event) {
testNether(event.getVehicle());
}
@EventHandler public void spawn(CreatureSpawnEvent event) {
switch (event.getEntityType()) {
case ARMOR_STAND:
test(event.getEntity());
if (event.getEntityType() == EntityType.ARMOR_STAND) {
testCreate(event.getEntity());
}
}
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.listeners;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -85,7 +85,8 @@ import java.util.UUID;
if (plot.isAdded(uuid)) {
Set<PlotPlayer> players = getNearbyPlayers(player, plot);
for (PlotPlayer oPlayer : players) {
if (!Permissions.hasPermission(oPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
if (!Permissions
.hasPermission(oPlayer, Captions.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
((BukkitPlayer) oPlayer).player
.setVelocity(calculateVelocity(plotPlayer, oPlayer));
}
@ -95,7 +96,8 @@ import java.util.UUID;
if (oPlayer == null) {
return;
}
if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
if (!Permissions
.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
player.setVelocity(calculateVelocity(oPlayer, plotPlayer));
}
}

View File

@ -4,6 +4,7 @@ import com.github.intellectualsites.plotsquared.bukkit.events.PlayerEnterPlotEve
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.flag.IntervalFlag;
import com.github.intellectualsites.plotsquared.plot.listener.PlotListener;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -30,15 +31,13 @@ import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
@SuppressWarnings("unused")
public class PlotPlusListener extends PlotListener implements Listener {
@SuppressWarnings("unused") public class PlotPlusListener extends PlotListener implements Listener {
private static final HashMap<UUID, Interval> feedRunnable = new HashMap<>();
private static final HashMap<UUID, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override public void run() {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
@ -79,12 +78,10 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
}
}
}, 0L, 20L);
}
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(BlockDamageEvent event) {
@EventHandler(priority = EventPriority.HIGH) public void onInteract(BlockDamageEvent event) {
Player player = event.getPlayer();
if (player.getGameMode() != GameMode.SURVIVAL) {
return;
@ -103,13 +100,11 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
@EventHandler(priority = EventPriority.HIGH) public void onDamage(EntityDamageEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Player player = (Player) event.getEntity();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
Plot plot = BukkitUtil.getLocation(event.getEntity()).getOwnedPlot();
if (plot == null) {
return;
}
@ -118,8 +113,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
@EventHandler public void onItemDrop(PlayerDropItemEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
@ -134,27 +128,24 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
@EventHandler
public void onPlotEnter(PlayerEnterPlotEvent event) {
@EventHandler public void onPlotEnter(PlayerEnterPlotEvent event) {
Player player = event.getPlayer();
Plot plot = event.getPlot();
Optional<Integer[]> feed = plot.getFlag(Flags.FEED);
feed.ifPresent( value -> feedRunnable.put(player.getUniqueId(), new Interval(value[0], value[1], 20))
);
Optional<Integer[]> heal = plot.getFlag(Flags.HEAL);
heal.ifPresent( value -> healRunnable.put(player.getUniqueId(), new Interval(value[0], value[1], 20))
);
Optional<IntervalFlag.Interval> feed = plot.getFlag(Flags.FEED);
feed.ifPresent(value -> feedRunnable
.put(player.getUniqueId(), new Interval(value.getVal1(), value.getVal2(), 20)));
Optional<IntervalFlag.Interval> heal = plot.getFlag(Flags.HEAL);
heal.ifPresent(value -> healRunnable
.put(player.getUniqueId(), new Interval(value.getVal1(), value.getVal2(), 20)));
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
@EventHandler public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
feedRunnable.remove(player.getUniqueId());
healRunnable.remove(player.getUniqueId());
}
@EventHandler
public void onPlotLeave(PlayerLeavePlotEvent event) {
@EventHandler public void onPlotLeave(PlayerLeavePlotEvent event) {
Player leaver = event.getPlayer();
Plot plot = event.getPlot();
if (!plot.hasOwner()) {
@ -165,8 +156,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
healRunnable.remove(leaver.getUniqueId());
}
@EventHandler
public void onItemPickup(EntityPickupItemEvent event) {
@EventHandler public void onItemPickup(EntityPickupItemEvent event) {
LivingEntity ent = event.getEntity();
if (ent instanceof Player) {
Player player = (Player) ent;

View File

@ -22,17 +22,14 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
@SuppressWarnings("unused") public class SingleWorldListener implements Listener {
private Method methodGetHandleChunk;
private Field mustSave, done, lit, s;
private Field mustSave;
public SingleWorldListener(Plugin plugin) throws Exception {
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle").getRealMethod();
this.mustSave = classChunk.getField("mustSave").getRealField();
try {
this.done = classChunk.getField("done").getRealField();
this.lit = classChunk.getField("lit").getRealField();
this.s = classChunk.getField("s").getRealField();
this.mustSave = classChunk.getField("mustSave").getRealField();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
@ -42,14 +39,9 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
public void markChunkAsClean(Chunk chunk) {
try {
Object nmsChunk = methodGetHandleChunk.invoke(chunk);
if (done != null)
this.done.set(nmsChunk, true);
if (mustSave != null)
if (mustSave != null) {
this.mustSave.set(nmsChunk, false);
if (lit != null)
this.lit.set(nmsChunk, false);
if (s != null)
this.s.set(nmsChunk, false);
}
} catch (Throwable e) {
e.printStackTrace();
}
@ -59,10 +51,12 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
World world = event.getWorld();
String name = world.getName();
PlotAreaManager man = PlotSquared.get().getPlotAreaManager();
if (!(man instanceof SinglePlotAreaManager))
if (!(man instanceof SinglePlotAreaManager)) {
return;
if (!isPlotId(name))
}
if (!isPlotId(name)) {
return;
}
markChunkAsClean(event.getChunk());
}

View File

@ -12,7 +12,8 @@ import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.generator.ChunkGenerator;
@SuppressWarnings("unused") public class WorldEvents implements Listener {
@SuppressWarnings("unused")
public class WorldEvents implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWorldInit(WorldInitEvent event) {

View File

@ -2,6 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@ -19,7 +20,7 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer {
this.player = player;
}
@Override public UUID getUUID() {
@NotNull @Override public UUID getUUID() {
return this.player.getUniqueId();
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object;
import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil;
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.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -19,6 +19,7 @@ import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.RegisteredListener;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Arrays;
@ -28,6 +29,7 @@ import java.util.stream.Collectors;
public class BukkitPlayer extends PlotPlayer {
private static boolean CHECK_EFFECTIVE = true;
public final Player player;
private boolean offline;
private UUID uuid;
@ -57,7 +59,7 @@ public class BukkitPlayer extends PlotPlayer {
return location == null ? BukkitUtil.getLocation(this.player) : location;
}
@Override public UUID getUUID() {
@NotNull @Override public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
@ -82,6 +84,11 @@ public class BukkitPlayer extends PlotPlayer {
return true;
}
@Override
public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) {
player.sendTitle(title, subtitle, fadeIn, stay, fadeOut);
}
private void callEvent(final Event event) {
Preconditions.checkNotNull(event, "Event cannot be null");
@ -106,15 +113,15 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override public int hasPermissionRange(final String stub, final int range) {
if (hasPermission(C.PERMISSION_ADMIN.s())) {
if (hasPermission(Captions.PERMISSION_ADMIN.s())) {
return Integer.MAX_VALUE;
}
final String[] nodes = stub.split("\\.");
final StringBuilder n = new StringBuilder();
for (int i = 0; i < (nodes.length - 1); i++) {
n.append(nodes[i]).append(".");
if (!stub.equals(n + C.PERMISSION_STAR.s())) {
if (hasPermission(n + C.PERMISSION_STAR.s())) {
if (!stub.equals(n + Captions.PERMISSION_STAR.s())) {
if (hasPermission(n + Captions.PERMISSION_STAR.s())) {
return Integer.MAX_VALUE;
}
}
@ -123,29 +130,45 @@ public class BukkitPlayer extends PlotPlayer {
return Integer.MAX_VALUE;
}
int max = 0;
if (CHECK_EFFECTIVE) {
boolean hasAny = false;
String stubPlus = stub + ".";
final Set<PermissionAttachmentInfo> effective = player.getEffectivePermissions();
if (!effective.isEmpty()) {
for (PermissionAttachmentInfo attach : effective) {
String perm = attach.getPermission();
if (perm.startsWith(stubPlus)) {
String end = perm.substring(stubPlus.length());
String permStr = attach.getPermission();
if (permStr.startsWith(stubPlus)) {
hasAny = true;
String end = permStr.substring(stubPlus.length());
if (MathMan.isInteger(end)) {
int val = Integer.parseInt(end);
if (val > range)
if (val > range) {
return val;
if (val > max)
}
if (val > max) {
max = val;
}
}
}
} else {
}
if (hasAny) {
return max;
}
// Workaround
for (PermissionAttachmentInfo attach : effective) {
String permStr = attach.getPermission();
if (permStr.startsWith("plots.") && !permStr.equals("plots.use")) {
return max;
}
}
CHECK_EFFECTIVE = false;
}
}
for (int i = range; i > 0; i--) {
if (hasPermission(stub + "." + i)) {
return i;
}
}
}
return max;
}
@ -202,8 +225,6 @@ public class BukkitPlayer extends PlotPlayer {
this.player.setPlayerWeather(WeatherType.DOWNFALL);
break;
case RESET:
this.player.resetPlayerWeather();
break;
default:
this.player.resetPlayerWeather();
break;
@ -238,8 +259,6 @@ public class BukkitPlayer extends PlotPlayer {
this.player.setGameMode(GameMode.SPECTATOR);
break;
case SURVIVAL:
this.player.setGameMode(GameMode.SURVIVAL);
break;
default:
this.player.setGameMode(GameMode.SURVIVAL);
break;
@ -267,14 +286,15 @@ public class BukkitPlayer extends PlotPlayer {
Preconditions.checkNotNull(id, "Specified block cannot be null");
if (PlotBlock.isEverything(id) || id.isAir()) {
// Let's just stop all the discs because why not?
for (final Sound sound : Arrays.stream(Sound.values()).filter(sound -> sound.name().contains("DISC")).collect(
Collectors.toList())) {
for (final Sound sound : Arrays.stream(Sound.values())
.filter(sound -> sound.name().contains("DISC")).collect(Collectors.toList())) {
player.stopSound(sound);
}
// this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, Material.AIR);
} else {
// this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id.to(Material.class));
this.player.playSound(BukkitUtil.getLocation(location), Sound.valueOf(id.to(Material.class).name()), Float.MAX_VALUE, 1f);
this.player.playSound(BukkitUtil.getLocation(location),
Sound.valueOf(id.to(Material.class).name()), Float.MAX_VALUE, 1f);
}
}

View File

@ -1,7 +1,12 @@
package com.github.intellectualsites.plotsquared.bukkit.object.entity;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import org.bukkit.*;
import org.bukkit.Art;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Rotation;
import org.bukkit.TreeSpecies;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.*;
import org.bukkit.inventory.EntityEquipment;
@ -10,13 +15,15 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
import java.util.List;
public final class ReplicatingEntityWrapper extends EntityWrapper {
private final short depth;
private final int hash;
private final EntityBaseStats base = new EntityBaseStats();
public ItemStack[] inventory;
private ItemStack[] inventory;
// Extended
private ItemStack stack;
private byte dataByte;
@ -38,9 +45,9 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
if (depth == 0) {
return;
}
Entity passenger = entity.getPassenger();
if (passenger != null) {
this.base.passenger = new ReplicatingEntityWrapper(passenger, depth);
List<Entity> passengers = entity.getPassengers();
if (passengers.size() > 0) {
this.base.passenger = new ReplicatingEntityWrapper(passengers.get(0), depth);
}
this.base.fall = entity.getFallDistance();
this.base.fire = (short) entity.getFireTicks();
@ -61,7 +68,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
this.dataByte = getOrdinal(TreeSpecies.values(), boat.getWoodType());
return;
case ARROW:
case COMPLEX_PART:
case EGG:
case ENDER_CRYSTAL:
case ENDER_PEARL:
@ -85,15 +91,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case MINECART_FURNACE:
case SPLASH_POTION:
case THROWN_EXP_BOTTLE:
case WEATHER:
case WITHER_SKULL:
case UNKNOWN:
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case SHULKER_BULLET:
case DRAGON_FIREBALL:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD:
case TRIDENT:
case LLAMA_SPIT:
// Do this stuff later
return;
// MISC //
@ -132,13 +137,21 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
// START AGEABLE //
// START TAMEABLE //
case HORSE:
Horse horse = (Horse) entity;
case DONKEY:
case LLAMA:
case MULE:
case SKELETON_HORSE:
AbstractHorse horse = (AbstractHorse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
this.horse.chest = horse.isCarryingChest();
this.horse.variant = horse.getVariant();
this.horse.style = horse.getStyle();
this.horse.color = horse.getColor();
if (horse instanceof ChestedHorse) {
ChestedHorse horse1 = (ChestedHorse) horse;
this.horse.chest = horse1.isCarryingChest();
}
//todo these horse features need fixing
//this.horse.variant = horse.getVariant();
//this.horse.style = horse.getStyle();
//this.horse.color = horse.getColor();
storeTameable(horse);
storeAgeable(horse);
storeLiving(horse);
@ -152,9 +165,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
storeLiving((LivingEntity) entity);
return;
// END TAMEABLE //
//todo fix sheep
case SHEEP:
Sheep sheep = (Sheep) entity;
this.dataByte = (byte) (sheep.isSheared() ? 1 : 0);
if (sheep.isSheared()) {
this.dataByte = (byte) 1;
} else {
this.dataByte = (byte) 0;
}
this.dataByte2 = sheep.getColor().getDyeData();
storeAgeable(sheep);
storeLiving(sheep);
@ -164,6 +182,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case COW:
case MUSHROOM_COW:
case PIG:
case TURTLE:
case POLAR_BEAR:
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
@ -174,15 +193,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
storeLiving((LivingEntity) entity);
return;
// END AGEABLE //
case GUARDIAN:
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity);
return;
case SKELETON:
this.dataByte = getOrdinal(Skeleton.SkeletonType.values(),
((Skeleton) entity).getSkeletonType());
storeLiving((LivingEntity) entity);
return;
case ARMOR_STAND:
ArmorStand stand = (ArmorStand) entity;
this.inventory =
@ -248,6 +258,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
EnderDragon entity1 = (EnderDragon) entity;
this.dataByte = (byte) entity1.getPhase().ordinal();
return;
case SKELETON:
case WITHER_SKELETON:
case GUARDIAN:
case ELDER_GUARDIAN:
case GHAST:
case MAGMA_CUBE:
case SQUID:
@ -273,6 +287,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
this.dataByte = (byte) 0;
}
storeLiving((LivingEntity) entity);
return;
// END LIVING //
default:
PlotSquared.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
@ -308,14 +323,16 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
if (this.lived.leashed) {
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leashX, Math.floor(y) + lived.leashY, Math
// .floor(z) + lived.leashZ), EntityType.LEASH_HITCH);
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) +
// lived.leashX, Math.floor(y) + lived.leashY, Math.floor(z) + lived.leashZ),
// EntityType.LEASH_HITCH);
// entity.setLeashHolder(leash);
}
}
void restoreEquipment(LivingEntity entity) {
EntityEquipment equipment = entity.getEquipment();
if (equipment != null) {
equipment.setItemInMainHand(this.lived.mainHand);
equipment.setItemInOffHand(this.lived.offHand);
equipment.setHelmet(this.lived.helmet);
@ -323,6 +340,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
equipment.setLeggings(this.lived.leggings);
equipment.setBoots(this.lived.boots);
}
}
private void restoreInventory(InventoryHolder entity) {
try {
@ -332,7 +350,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
}
}
public void storeLiving(LivingEntity lived) {
private void storeLiving(LivingEntity lived) {
this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems();
@ -425,7 +443,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
}
if (this.base.passenger != null) {
try {
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) {
}
}
@ -454,7 +472,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
((Slime) entity).setSize(this.dataByte);
return entity;
case ARROW:
case COMPLEX_PART:
case EGG:
case ENDER_CRYSTAL:
case ENDER_PEARL:
@ -477,15 +494,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case SNOWBALL:
case SPLASH_POTION:
case THROWN_EXP_BOTTLE:
case WEATHER:
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case SHULKER_BULLET:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD:
case DRAGON_FIREBALL:
case WITHER_SKULL:
case MINECART_FURNACE:
case LLAMA_SPIT:
case TRIDENT:
case UNKNOWN:
// Do this stuff later
return entity;
@ -510,12 +526,19 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
// START AGEABLE //
// START TAMEABLE //
case HORSE:
Horse horse = (Horse) entity;
case LLAMA:
case SKELETON_HORSE:
case DONKEY:
case MULE:
AbstractHorse horse = (AbstractHorse) entity;
horse.setJumpStrength(this.horse.jump);
horse.setCarryingChest(this.horse.chest);
horse.setVariant(this.horse.variant);
horse.setStyle(this.horse.style);
horse.setColor(this.horse.color);
if (horse instanceof ChestedHorse) {
((ChestedHorse) horse).setCarryingChest(this.horse.chest);
}
//todo broken as of 1.13
//horse.setVariant(this.horse.variant);
//horse.setStyle(this.horse.style);
//horse.setColor(this.horse.color);
restoreTameable(horse);
restoreAgeable(horse);
restoreLiving(horse);
@ -543,6 +566,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case VILLAGER:
case CHICKEN:
case COW:
case TURTLE:
case POLAR_BEAR:
case MUSHROOM_COW:
case PIG:
@ -557,19 +581,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
case GUARDIAN:
if (this.dataByte != 0) {
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity);
return entity;
case SKELETON:
if (this.dataByte != 0) {
((Skeleton) entity)
.setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]);
}
storeLiving((LivingEntity) entity);
return entity;
case ARMOR_STAND:
// CHECK positions
ArmorStand stand = (ArmorStand) entity;
@ -665,6 +676,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case BLAZE:
case SNOWMAN:
case SHULKER:
case GUARDIAN:
case ELDER_GUARDIAN:
case SKELETON:
case WITHER_SKELETON:
restoreLiving((LivingEntity) entity);
return entity;
case IRON_GOLEM:

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object.schematic;
import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil;
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.sk89q.jnbt.*;
import org.bukkit.Material;
import org.bukkit.World;
@ -132,7 +132,7 @@ public class StateWrapper {
.replace("\"underlined\":true,", "&n").replace("\"italic\":true,", "&o")
.replace("[{\"text\":\"", "&0").replace("{\"text\":\"", "&0").replace("\"},", "")
.replace("\"}]", "").replace("\"}", "");
for (Entry<String, String> entry : C.replacements.entrySet()) {
for (Entry<String, String> entry : Captions.replacements.entrySet()) {
str = str.replace(entry.getKey(), entry.getValue());
}
return str;

View File

@ -1,129 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.titles;
import com.github.intellectualsites.plotsquared.bukkit.chat.Reflection;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class DefaultTitleManager extends TitleManager {
/**
* Create a new 1.8 title.
*
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime,
int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
/**
* Load spigot and NMS classes.
*/
@Override void loadClasses() {
this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle");
this.packetActions = Reflection.getNMSClass("EnumTitleAction");
this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
}
@Override public void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle
.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE,
Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if (this.fadeInTime != -1 && this.fadeOutTime != -1 && this.stayTime != -1) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle())
+ "\",color:" + this.titleColor.name().toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle())
+ "\",color:" + this.subtitleColor.name().toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
@Override public void clearTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings.
*
* @param player Player
* @throws SecurityException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
@Override public void resetTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent)
.newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
return null;
}
}
Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && (args.length == 0 || classListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
}

View File

@ -1,20 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.titles;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle;
import org.bukkit.entity.Player;
@SuppressWarnings("deprecation") public class DefaultTitle_111 extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
try {
final Player playerObj = ((BukkitPlayer) player).player;
TitleManager_1_11 title = new TitleManager_1_11(head, sub, in, delay, out);
title.send(playerObj);
return;
} catch (Throwable ignored) {
}
}
}

View File

@ -1,22 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.titles;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle;
public class HackTitle extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
try {
HackTitleManager title = new HackTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (Exception ignored) {
PlotSquared.debug("&cYour server version does not support titles!");
Settings.TITLES = false;
AbstractTitle.TITLE_CLASS = null;
}
}
}

View File

@ -1,177 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.titles;
import com.github.intellectualsites.plotsquared.bukkit.chat.Reflection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class HackTitleManager extends TitleManager {
/**
* Create a new 1.8 title.
*
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
/**
* Load spigot and NMS classes.
*/
@Override void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
}
@Override public void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle
.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle())
+ "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle
.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle())
+ "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions,
Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
@Override public void clearTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet =
this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
}
}
@Override public void resetTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet =
this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
}
}
/**
* Get the protocol version of the player.
*
* @param player Player
* @return Protocol version
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
private int getProtocolVersion(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
return (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
}
/**
* Check if running spigot.
*
* @return Spigot
*/
private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot");
}
/**
* Get class by url.
*
* @param namespace Namespace url
* @return Class
*/
private Class<?> getClass(String namespace) {
try {
return Class.forName(namespace);
} catch (ClassNotFoundException ignored) {
}
return null;
}
private Field getField(String name, Class<?> clazz)
throws NoSuchFieldException, SecurityException {
return clazz.getDeclaredField(name);
}
private Object getValue(String name, Object obj)
throws ReflectiveOperationException, SecurityException, IllegalArgumentException {
Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
}
private Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (SecurityException | NoSuchFieldException e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
}

View File

@ -1,256 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.titles;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public abstract class TitleManager {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */ Class<?> packetTitle;
/* Title packet actions ENUM */ Class<?> packetActions;
/* Chat serializer */ Class<?> nmsChatSerializer;
Class<?> chatBaseComponent;
ChatColor titleColor = ChatColor.WHITE;
ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */ int fadeInTime = -1;
int stayTime = -1;
int fadeOutTime = -1;
boolean ticks = false;
/* Title text and color */
private String title = "";
/* Subtitle text and color */
private String subtitle = "";
/**
* Create a new 1.8 title.
*
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
TitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
abstract void loadClasses();
/**
* Gets title text.
*
* @return Title text
*/
public final String getTitle() {
return this.title;
}
/**
* Sets the text for the title.
*
* @param title Title
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* Gets the subtitle text.
*
* @return Subtitle text
*/
public final String getSubtitle() {
return this.subtitle;
}
/**
* Sets subtitle text.
*
* @param subtitle Subtitle text
*/
public final void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Sets the title color.
*
* @param color Chat color
*/
public final void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Sets the subtitle color.
*
* @param color Chat color
*/
public final void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Sets title fade in time.
*
* @param time Time
*/
public final void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Sets title fade out time.
*
* @param time Time
*/
public final void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Sets title stay time.
*
* @param time Time
*/
public final void setStayTime(int time) {
this.stayTime = time;
}
/**
* Sets timings to ticks.
*/
public final void setTimingsToTicks() {
this.ticks = true;
}
/**
* Sets timings to seconds.
*/
public final void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Sends the title to a player.
*
* @param player Player
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void send(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Broadcasts the title to all players.
*
* @throws Exception
*/
public final void broadcast() throws Exception {
for (Player player : Bukkit.getOnlinePlayers()) {
send(player);
}
}
/**
* Clears the title.
*
* @param player Player
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void clearTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Resets the title settings.
*
* @param player Player
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void resetTitle(Player player)
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
private Class<?> getPrimitiveType(Class<?> clazz) {
if (CORRESPONDING_TYPES.containsKey(clazz)) {
return CORRESPONDING_TYPES.get(clazz);
} else {
return clazz;
}
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a;
if (classes != null) {
a = classes.length;
} else {
a = 0;
}
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
final Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
final Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
boolean classListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}
boolean equal = true;
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

@ -1,497 +0,0 @@
package com.github.intellectualsites.plotsquared.bukkit.titles;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Minecraft 1.8 Title
* For 1.11
*
* @author Maxim Van de Wynckel
* @version 1.1.0
*/
public class TitleManager_1_11 {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES =
new HashMap<Class<?>, Class<?>>();
/* Title packet */
private static Class<?> packetTitle;
/* Title packet actions ENUM */
private static Class<?> packetActions;
/* Chat serializer */
private static Class<?> nmsChatSerializer;
private static Class<?> chatBaseComponent;
/* NMS player and connection */
private static Class<?> nmsPlayer;
private static Class<?> nmsPlayerConnection;
private static Field playerConnection;
private static Method sendPacket;
private static Class<?> obcPlayer;
private static Method methodPlayerGetHandle;
/* Title text and color */
private String title = "";
private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */
private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
private int fadeInTime = -1;
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
public TitleManager_1_11() {
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title Title
*/
public TitleManager_1_11(String title) {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title Title text
* @param subtitle Subtitle text
*/
public TitleManager_1_11(String title, String subtitle) {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title
*
* @param title Title
*/
public TitleManager_1_11(TitleManager_1_11 title) {
// Copy title
this.title = title.getTitle();
this.subtitle = title.getSubtitle();
this.titleColor = title.getTitleColor();
this.subtitleColor = title.getSubtitleColor();
this.fadeInTime = title.getFadeInTime();
this.fadeOutTime = title.getFadeOutTime();
this.stayTime = title.getStayTime();
this.ticks = title.isTicks();
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime,
int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length)
return false;
for (int i = 0; i < a.length; i++)
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i]))
return false;
return true;
}
/**
* Load spigot and NMS classes
*/
private void loadClasses() {
if (packetTitle == null) {
packetTitle = getNMSClass("PacketPlayOutTitle");
packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction");
chatBaseComponent = getNMSClass("IChatBaseComponent");
nmsChatSerializer = getNMSClass("ChatComponentText");
nmsPlayer = getNMSClass("EntityPlayer");
nmsPlayerConnection = getNMSClass("PlayerConnection");
playerConnection = getField(nmsPlayer, "playerConnection");
sendPacket = getMethod(nmsPlayerConnection, "sendPacket");
obcPlayer = getOBCClass("entity.CraftPlayer");
methodPlayerGetHandle = getMethod("getHandle", obcPlayer);
}
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle() {
return this.title;
}
/**
* Set title text
*
* @param title Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
}
/**
* Set subtitle text
*
* @param subtitle Subtitle text
*/
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
ticks = false;
}
/**
* Send the title to a player
*
* @param player Player
*/
public void send(Player player) {
if (packetTitle != null) {
// First reset previous settings
resetTitle(player);
try {
// Send timings first
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle
.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE,
Integer.TYPE).newInstance(actions[3], null, fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1)
sendPacket.invoke(connection, packet);
Object serialized;
if (!subtitle.equals("")) {
// Send subtitle if present
serialized = nmsChatSerializer.getConstructor(String.class).newInstance(
subtitleColor + ChatColor.translateAlternateColorCodes('&', subtitle));
packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
// Send title
serialized = nmsChatSerializer.getConstructor(String.class)
.newInstance(titleColor + ChatColor.translateAlternateColorCodes('&', title));
packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void updateTimes(Player player) {
if (TitleManager_1_11.packetTitle != null) {
try {
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = TitleManager_1_11.packetActions.getEnumConstants();
Object packet = TitleManager_1_11.packetTitle.getConstructor(
new Class[] {TitleManager_1_11.packetActions, chatBaseComponent, Integer.TYPE,
Integer.TYPE, Integer.TYPE})
.newInstance(actions[3], null, this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20),
this.fadeOutTime * (this.ticks ? 1 : 20));
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void updateTitle(Player player) {
if (TitleManager_1_11.packetTitle != null) {
try {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = TitleManager_1_11.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance(
titleColor + ChatColor.translateAlternateColorCodes('&', this.title));
Object packet = TitleManager_1_11.packetTitle.getConstructor(
new Class[] {TitleManager_1_11.packetActions, chatBaseComponent})
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void updateSubtitle(Player player) {
if (TitleManager_1_11.packetTitle != null) {
try {
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = TitleManager_1_11.packetActions.getEnumConstants();
Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance(
subtitleColor + ChatColor.translateAlternateColorCodes('&', this.subtitle));
Object packet = TitleManager_1_11.packetTitle.getConstructor(
new Class[] {TitleManager_1_11.packetActions, chatBaseComponent})
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Broadcast the title to all players
*/
public void broadcast() {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
* @param player Player
*/
public void clearTitle(Player player) {
try {
// Send timings first
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Reset the title settings
*
* @param player Player
*/
public void resetTitle(Player player) {
try {
// Send timings first
Object handle = getHandle(player);
Object connection = playerConnection.get(handle);
Object[] actions = packetActions.getEnumConstants();
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent)
.newInstance(actions[5], null);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
}
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++)
types[i] = getPrimitiveType(classes[i]);
return types;
}
private Object getHandle(Player player) {
try {
return methodPlayerGetHandle.invoke(player);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t))
return m;
}
return null;
}
private String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName();
String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(String className) {
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
} catch (Exception e) {
e.printStackTrace();
}
return clazz;
}
private Class<?> getOBCClass(String className) {
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
} catch (Exception e) {
e.printStackTrace();
}
return clazz;
}
private Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods())
if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length)
return false;
for (int i = 0; i < l1.length; i++)
if (l1[i] != l2[i]) {
equal = false;
break;
}
return equal;
}
public ChatColor getTitleColor() {
return titleColor;
}
/**
* Set the title color
*
* @param color Chat color
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
public ChatColor getSubtitleColor() {
return subtitleColor;
}
/**
* Set the subtitle color
*
* @param color Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
public int getFadeInTime() {
return fadeInTime;
}
/**
* Set title fade in time
*
* @param time Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
public int getFadeOutTime() {
return fadeOutTime;
}
/**
* Set title fade out time
*
* @param time Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
public int getStayTime() {
return stayTime;
}
/**
* Set title stay time
*
* @param time Time
*/
public void setStayTime(int time) {
this.stayTime = time;
}
public boolean isTicks() {
return ticks;
}
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.util;
import com.github.intellectualsites.plotsquared.bukkit.chat.FancyMessage;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotMessage;
@ -10,8 +10,9 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.ChatManager;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class BukkitChatManager extends ChatManager<FancyMessage> {
@ -20,14 +21,12 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
}
@Override public void color(PlotMessage message, String color) {
message.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
message.$(this).color(ChatColor.getByChar(Captions.color(color).substring(1)));
}
@Override public void tooltip(PlotMessage message, PlotMessage... tooltips) {
List<FancyMessage> lines = new ArrayList<>();
for (PlotMessage tooltip : tooltips) {
lines.add(tooltip.$(this));
}
List<FancyMessage> lines =
Arrays.stream(tooltips).map(tooltip -> tooltip.$(this)).collect(Collectors.toList());
message.$(this).formattedTooltip(lines);
}

View File

@ -106,289 +106,11 @@ public class BukkitChunkManager extends ChunkManager {
Set<ChunkLoc> chunks = super.getChunkChunks(world);
for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) {
ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5);
if (!chunks.contains(loc)) {
chunks.add(loc);
}
}
return chunks;
}
@Override
public boolean copyRegion(com.github.intellectualsites.plotsquared.plot.object.Location pos1,
com.github.intellectualsites.plotsquared.plot.object.Location pos2,
com.github.intellectualsites.plotsquared.plot.object.Location newPos,
final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ();
final RegionWrapper region =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld());
final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld);
final World newWorld = Bukkit.getWorld(newPos.getWorld());
final String newWorldName = newWorld.getName();
final ContentMap map = new ContentMap();
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal<int[]>() {
@Override public void run(int[] value) {
int bx = value[2];
int bz = value[3];
int tx = value[4];
int tz = value[5];
ChunkLoc loc = new ChunkLoc(value[0], value[1]);
int cxx = loc.x << 4;
int czz = loc.z << 4;
Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z);
map.saveEntitiesIn(chunk, region);
for (int x = bx & 15; x <= (tx & 15); x++) {
for (int z = bz & 15; z <= (tz & 15); z++) {
map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ);
}
}
}
}, () -> {
for (Entry<PlotLoc, BaseBlock[]> entry : map.allBlocks.entrySet()) {
PlotLoc loc = entry.getKey();
BaseBlock[] blocks = entry.getValue();
for (int y = 0; y < blocks.length; y++) {
if (blocks[y] != null) {
BaseBlock block = blocks[y];
queue.setBlock(loc.x, y, loc.z, block);
}
}
}
queue.enqueue();
GlobalBlockQueue.IMP.addTask(() -> {
//map.restoreBlocks(newWorld, 0, 0);
map.restoreEntities(newWorld, relX, relZ);
TaskManager.runTask(whenDone);
});
}, 5);
return true;
}
@Override public boolean regenerateRegion(
final com.github.intellectualsites.plotsquared.plot.object.Location pos1,
final com.github.intellectualsites.plotsquared.plot.object.Location pos2,
final boolean ignoreAugment, final Runnable whenDone) {
final String world = pos1.getWorld();
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
final int p2z = pos2.getZ();
final int bcx = p1x >> 4;
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final List<ChunkLoc> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z));
}
}
final World worldObj = Bukkit.getWorld(world);
final BukkitWorld bukkitWorldObj = new BukkitWorld(worldObj);
TaskManager.runTask(new Runnable() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) {
final ChunkLoc chunk = chunks.remove(0);
int x = chunk.x;
int z = chunk.z;
int xxb = x << 4;
int zzb = z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
Chunk chunkObj = worldObj.getChunkAt(x, z);
if (!chunkObj.load(false)) {
continue;
}
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
RegionWrapper currentPlotClear =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) {
AugmentedUtils
.bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.x, chunk.z));
continue;
}
boolean checkX1 = false;
int xxb2;
if (x == bcx) {
xxb2 = p1x - 1;
checkX1 = true;
} else {
xxb2 = xxb;
}
boolean checkX2 = false;
int xxt2;
if (x == tcx) {
xxt2 = p2x + 1;
checkX2 = true;
} else {
xxt2 = xxt;
}
boolean checkZ1 = false;
int zzb2;
if (z == bcz) {
zzb2 = p1z - 1;
checkZ1 = true;
} else {
zzb2 = zzb;
}
boolean checkZ2 = false;
int zzt2;
if (z == tcz) {
zzt2 = p2z + 1;
checkZ2 = true;
} else {
zzt2 = zzt;
}
final ContentMap map = new ContentMap();
if (checkX1) {
map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb2, zzt2); //
}
if (checkX2) {
map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb2, zzt2); //
}
if (checkZ1) {
map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzb, zzb2); //
}
if (checkZ2) {
map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzt2, zzt); //
}
if (checkX1 && checkZ1) {
map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb, zzb2); //
}
if (checkX2 && checkZ1) {
map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb, zzb2); // ?
}
if (checkX1 && checkZ2) {
map.saveRegion(bukkitWorldObj, xxb, xxb2, zzt2, zzt); // ?
}
if (checkX2 && checkZ2) {
map.saveRegion(bukkitWorldObj, xxt2, xxt, zzt2, zzt); //
}
map.saveEntitiesOut(chunkObj, currentPlotClear);
AugmentedUtils.bypass(ignoreAugment,
() -> setChunkInPlotArea(null, new RunnableVal<ScopedLocalBlockQueue>() {
@Override public void run(ScopedLocalBlockQueue value) {
com.github.intellectualsites.plotsquared.plot.object.Location min =
value.getMin();
int bx = min.getX();
int bz = min.getZ();
for (int x1 = 0; x1 < 16; x1++) {
for (int z1 = 0; z1 < 16; z1++) {
PlotLoc loc = new PlotLoc(bx + x1, bz + z1);
BaseBlock[] ids = map.allBlocks.get(loc);
if (ids != null) {
for (int y = 0; y < Math.min(128, ids.length); y++) {
BaseBlock id = ids[y];
if (id != null) {
value.setBlock(x1, y, z1, id);
} else {
value.setBlock(x1, y, z1, PlotBlock.get("air"));
}
}
for (int y = Math.min(128, ids.length);
y < ids.length; y++) {
BaseBlock id = ids[y];
if (id != null) {
value.setBlock(x1, y, z1, id);
}
}
}
}
}
}
}, world, chunk));
//map.restoreBlocks(worldObj, 0, 0);
map.restoreEntities(worldObj, 0, 0);
}
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
TaskManager.runTaskLater(whenDone, 1);
}
}
});
return true;
}
@Override
public void clearAllEntities(com.github.intellectualsites.plotsquared.plot.object.Location pos1,
com.github.intellectualsites.plotsquared.plot.object.Location pos2) {
String world = pos1.getWorld();
List<Entity> entities = BukkitUtil.getEntities(world);
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
for (Entity entity : entities) {
if (!(entity instanceof Player)) {
org.bukkit.Location location = entity.getLocation();
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz
&& location.getZ() <= tz) {
if (entity.hasMetadata("ps-tmp-teleport")) {
continue;
}
entity.remove();
}
}
}
}
@Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force);
}
@SuppressWarnings("deprecation") @Override
public void unloadChunk(final String world, final ChunkLoc loc, final boolean save,
final boolean safe) {
if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
TaskManager
.runTask(() -> BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe));
} else {
BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe);
}
}
@Override public void swap(com.github.intellectualsites.plotsquared.plot.object.Location bot1,
com.github.intellectualsites.plotsquared.plot.object.Location top1,
com.github.intellectualsites.plotsquared.plot.object.Location bot2,
com.github.intellectualsites.plotsquared.plot.object.Location top2,
final Runnable whenDone) {
RegionWrapper region1 =
new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
RegionWrapper region2 =
new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
final World world1 = Bukkit.getWorld(bot1.getWorld());
World world2 = Bukkit.getWorld(bot2.getWorld());
int relX = bot2.getX() - bot1.getX();
int relZ = bot2.getZ() - bot1.getZ();
final ArrayDeque<ContentMap> maps = new ArrayDeque<>();
for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) {
for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) {
Chunk chunk1 = world1.getChunkAt(x, z);
Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4));
maps.add(swapChunk(world1, world2, chunk1, chunk2, region1, region2));
}
}
GlobalBlockQueue.IMP.addTask(() -> {
for (ContentMap map : maps) {
map.restoreEntities(world1, 0, 0);
TaskManager.runTaskLater(whenDone, 1);
}
});
}
@Override public int[] countEntities(Plot plot) {
int[] existing = (int[]) plot.getMeta("EntityCount");
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime")
@ -398,8 +120,8 @@ public class BukkitChunkManager extends ChunkManager {
PlotArea area = plot.getArea();
World world = BukkitUtil.getWorld(area.worldname);
com.github.intellectualsites.plotsquared.plot.object.Location bot = plot.getBottomAbs();
com.github.intellectualsites.plotsquared.plot.object.Location top = plot.getTopAbs();
Location bot = plot.getBottomAbs();
Location top = plot.getTopAbs();
int bx = bot.getX() >> 4;
int bz = bot.getZ() >> 4;
@ -464,6 +186,271 @@ public class BukkitChunkManager extends ChunkManager {
return count;
}
@Override public boolean copyRegion(Location pos1, Location pos2, Location newPos,
final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ();
final RegionWrapper region =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld());
final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld);
final World newWorld = Bukkit.getWorld(newPos.getWorld());
final String newWorldName = newWorld.getName();
final ContentMap map = new ContentMap();
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal<int[]>() {
@Override public void run(int[] value) {
int bx = value[2];
int bz = value[3];
int tx = value[4];
int tz = value[5];
ChunkLoc loc = new ChunkLoc(value[0], value[1]);
int cxx = loc.x << 4;
int czz = loc.z << 4;
Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z);
map.saveEntitiesIn(chunk, region);
for (int x = bx & 15; x <= (tx & 15); x++) {
for (int z = bz & 15; z <= (tz & 15); z++) {
map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ);
}
}
}
}, () -> {
for (Entry<PlotLoc, BaseBlock[]> entry : map.allBlocks.entrySet()) {
PlotLoc loc = entry.getKey();
BaseBlock[] blocks = entry.getValue();
for (int y = 0; y < blocks.length; y++) {
if (blocks[y] != null) {
BaseBlock block = blocks[y];
queue.setBlock(loc.getX(), y, loc.getZ(), block);
}
}
}
queue.enqueue();
GlobalBlockQueue.IMP.addTask(() -> {
//map.restoreBlocks(newWorld, 0, 0);
map.restoreEntities(newWorld, relX, relZ);
TaskManager.runTask(whenDone);
});
}, 5);
return true;
}
@Override public boolean regenerateRegion(final Location pos1, final Location pos2,
final boolean ignoreAugment, final Runnable whenDone) {
final String world = pos1.getWorld();
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
final int p2z = pos2.getZ();
final int bcx = p1x >> 4;
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final List<ChunkLoc> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z));
}
}
final World worldObj = Bukkit.getWorld(world);
final BukkitWorld bukkitWorldObj = new BukkitWorld(worldObj);
TaskManager.runTask(new Runnable() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) {
final ChunkLoc chunk = chunks.remove(0);
int x = chunk.x;
int z = chunk.z;
int xxb = x << 4;
int zzb = z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
Chunk chunkObj = worldObj.getChunkAt(x, z);
if (!chunkObj.load(false)) {
continue;
}
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z
&& PlotSquared.imp().getServerVersion()[1] == 13) {
AugmentedUtils
.bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.x, chunk.z));
continue;
}
boolean checkX1 = false;
int xxb2;
if (x == bcx) {
xxb2 = p1x - 1;
checkX1 = true;
} else {
xxb2 = xxb;
}
boolean checkX2 = false;
int xxt2;
if (x == tcx) {
xxt2 = p2x + 1;
checkX2 = true;
} else {
xxt2 = xxt;
}
boolean checkZ1 = false;
int zzb2;
if (z == bcz) {
zzb2 = p1z - 1;
checkZ1 = true;
} else {
zzb2 = zzb;
}
boolean checkZ2 = false;
int zzt2;
if (z == tcz) {
zzt2 = p2z + 1;
checkZ2 = true;
} else {
zzt2 = zzt;
}
final ContentMap map = new ContentMap();
if (checkX1) {
map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb2, zzt2); //
}
if (checkX2) {
map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb2, zzt2); //
}
if (checkZ1) {
map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzb, zzb2); //
}
if (checkZ2) {
map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzt2, zzt); //
}
if (checkX1 && checkZ1) {
map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb, zzb2); //
}
if (checkX2 && checkZ1) {
map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb, zzb2); // ?
}
if (checkX1 && checkZ2) {
map.saveRegion(bukkitWorldObj, xxb, xxb2, zzt2, zzt); // ?
}
if (checkX2 && checkZ2) {
map.saveRegion(bukkitWorldObj, xxt2, xxt, zzt2, zzt); //
}
RegionWrapper currentPlotClear =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
map.saveEntitiesOut(chunkObj, currentPlotClear);
AugmentedUtils.bypass(ignoreAugment,
() -> setChunkInPlotArea(null, new RunnableVal<ScopedLocalBlockQueue>() {
@Override public void run(ScopedLocalBlockQueue value) {
Location min = value.getMin();
int bx = min.getX();
int bz = min.getZ();
for (int x1 = 0; x1 < 16; x1++) {
for (int z1 = 0; z1 < 16; z1++) {
PlotLoc loc = new PlotLoc(bx + x1, bz + z1);
BaseBlock[] ids = map.allBlocks.get(loc);
if (ids != null) {
for (int y = 0; y < Math.min(128, ids.length); y++) {
BaseBlock id = ids[y];
if (id != null) {
value.setBlock(x1, y, z1, id);
} else {
value.setBlock(x1, y, z1, PlotBlock.get("air"));
}
}
for (int y = Math.min(128, ids.length);
y < ids.length; y++) {
BaseBlock id = ids[y];
if (id != null) {
value.setBlock(x1, y, z1, id);
}
}
}
}
}
}
}, world, chunk));
//map.restoreBlocks(worldObj, 0, 0);
map.restoreEntities(worldObj, 0, 0);
}
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
TaskManager.runTaskLater(whenDone, 1);
}
}
});
return true;
}
@Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force);
}
@SuppressWarnings("deprecation") @Override
public void unloadChunk(final String world, final ChunkLoc loc, final boolean save,
final boolean safe) {
if (!PlotSquared.get().isMainThread(Thread.currentThread())) {
TaskManager.runTask(() -> BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save));
} else {
BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save);
}
}
@Override public void clearAllEntities(Location pos1, Location pos2) {
String world = pos1.getWorld();
List<Entity> entities = BukkitUtil.getEntities(world);
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
for (Entity entity : entities) {
if (!(entity instanceof Player)) {
org.bukkit.Location location = entity.getLocation();
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz
&& location.getZ() <= tz) {
if (entity.hasMetadata("ps-tmp-teleport")) {
continue;
}
entity.remove();
}
}
}
}
@Override public void swap(Location bot1, Location top1, Location bot2, Location top2,
final Runnable whenDone) {
RegionWrapper region1 =
new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
RegionWrapper region2 =
new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
final World world1 = Bukkit.getWorld(bot1.getWorld());
World world2 = Bukkit.getWorld(bot2.getWorld());
int relX = bot2.getX() - bot1.getX();
int relZ = bot2.getZ() - bot1.getZ();
final ArrayDeque<ContentMap> maps = new ArrayDeque<>();
for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) {
for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) {
Chunk chunk1 = world1.getChunkAt(x, z);
Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4));
maps.add(swapChunk(world1, world2, chunk1, chunk2, region1, region2));
}
}
GlobalBlockQueue.IMP.addTask(() -> {
for (ContentMap map : maps) {
map.restoreEntities(world1, 0, 0);
TaskManager.runTaskLater(whenDone, 1);
}
});
}
private void count(int[] count, Entity entity) {
switch (entity.getType()) {
case PLAYER:
@ -478,7 +465,7 @@ public class BukkitChunkManager extends ChunkManager {
case SNOWBALL:
case ENDER_PEARL:
case ARROW:
case TIPPED_ARROW:
case TRIDENT:
case SHULKER_BULLET:
case SPECTRAL_ARROW:
case DRAGON_FIREBALL:
@ -488,18 +475,15 @@ public class BukkitChunkManager extends ChunkManager {
case FALLING_BLOCK:
// Block entities
case ENDER_CRYSTAL:
case COMPLEX_PART:
case FISHING_HOOK:
case ENDER_SIGNAL:
case EXPERIENCE_ORB:
case LEASH_HITCH:
case FIREWORK:
case WEATHER:
case LIGHTNING:
case WITHER_SKULL:
case UNKNOWN:
case AREA_EFFECT_CLOUD:
case LINGERING_POTION:
case EVOKER_FANGS:
// non moving / unremovable
break;
@ -539,6 +523,16 @@ public class BukkitChunkManager extends ChunkManager {
case SKELETON_HORSE:
case ZOMBIE_HORSE:
case MULE:
case DOLPHIN:
case TURTLE:
case COD:
case PARROT:
case SALMON:
case PUFFERFISH:
case TROPICAL_FISH:
case CAT:
case FOX:
case PANDA:
// animal
count[3]++;
count[1]++;
@ -589,6 +583,7 @@ public class BukkitChunkManager extends ChunkManager {
count[0]++;
}
public static class ContentMap {
final Set<EntityWrapper> entities;
@ -617,14 +612,9 @@ public class BukkitChunkManager extends ChunkManager {
}
}
public void saveEntitiesIn(Chunk chunk, RegionWrapper region) {
saveEntitiesIn(chunk, region, 0, 0, false);
}
public void saveEntitiesOut(Chunk chunk, RegionWrapper region) {
void saveEntitiesOut(Chunk chunk, RegionWrapper region) {
for (Entity entity : chunk.getEntities()) {
com.github.intellectualsites.plotsquared.plot.object.Location loc =
BukkitUtil.getLocation(entity);
Location loc = BukkitUtil.getLocation(entity);
int x = loc.getX();
int z = loc.getZ();
if (isIn(region, x, z)) {
@ -639,11 +629,14 @@ public class BukkitChunkManager extends ChunkManager {
}
}
public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ,
void saveEntitiesIn(Chunk chunk, RegionWrapper region) {
saveEntitiesIn(chunk, region, 0, 0, false);
}
void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ,
boolean delete) {
for (Entity entity : chunk.getEntities()) {
com.github.intellectualsites.plotsquared.plot.object.Location loc =
BukkitUtil.getLocation(entity);
Location loc = BukkitUtil.getLocation(entity);
int x = loc.getX();
int z = loc.getZ();
if (!isIn(region, x, z)) {
@ -665,7 +658,7 @@ public class BukkitChunkManager extends ChunkManager {
}
}
public void restoreEntities(World world, int xOffset, int zOffset) {
void restoreEntities(World world, int xOffset, int zOffset) {
for (EntityWrapper entity : this.entities) {
try {
entity.spawn(world, xOffset, zOffset);
@ -677,8 +670,8 @@ public class BukkitChunkManager extends ChunkManager {
this.entities.clear();
}
public void saveBlocks(BukkitWorld world, int maxY, int x, int z, int offsetX,
int offsetZ) {
//todo optimize maxY
void saveBlocks(BukkitWorld world, int maxY, int x, int z, int offsetX, int offsetZ) {
maxY = Math.min(255, maxY);
BaseBlock[] ids;
ids = new BaseBlock[maxY + 1];

View File

@ -1,9 +1,30 @@
package com.github.intellectualsites.plotsquared.bukkit.util;
import com.github.intellectualsites.plotsquared.bukkit.events.*;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerClaimPlotEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerPlotDeniedEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerPlotHelperEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerPlotTrustedEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlayerTeleportToPlotEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotAutoMergeEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotChangeOwnerEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotClearEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotComponentSetEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotDeleteEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotFlagAddEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotFlagRemoveEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotMergeEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotRateEvent;
import com.github.intellectualsites.plotsquared.bukkit.events.PlotUnlinkEvent;
import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.Rating;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -16,7 +37,7 @@ import java.util.List;
import java.util.UUID;
/**
* Utility class for handling Bukkit {@link Event events}
* Utility class for handling Bukkit Events.
*/
public final class BukkitEventUtil extends EventUtil {
@ -99,10 +120,6 @@ public final class BukkitEventUtil extends EventUtil {
new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner));
}
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);

View File

@ -2,6 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.util;
import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.object.*;
@ -65,11 +66,13 @@ public class BukkitHybridUtils extends HybridUtils {
System.gc();
final BlockBucket[][][] oldBlocks = new BlockBucket[256][width][length];
final PlotBlock[][][] newBlocks = new PlotBlock[256][width][length];
final BlockBucket airBucket = BlockBucket.withSingle(StringPlotBlock.EVERYTHING);
PlotArea area = PlotSquared.get().getPlotArea(world, null);
if (!(area instanceof HybridPlotWorld))
if (!(area instanceof HybridPlotWorld)) {
return;
}
HybridPlotWorld hpw = (HybridPlotWorld) area;
final BlockBucket[][] result = hpw.getBlockBucketChunk();
@ -107,7 +110,12 @@ public class BukkitHybridUtils extends HybridUtils {
}
rz[i] = v;
}
int minY = Math.min(hpw.PLOT_HEIGHT, hpw.ROAD_HEIGHT);
int minY;
if (Settings.Schematics.PASTE_ON_TOP) {
minY = hpw.SCHEM_Y;
} else {
minY = 1;
}
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
BaseBlock[] blocks = hpw.G_SCH.get(MathMan.pair(rx[x], rz[z]));
@ -140,8 +148,7 @@ public class BukkitHybridUtils extends HybridUtils {
continue;
}
int y = MainUtil.y_loc[i][j];
oldBlocks[y][x][z] =
BlockBucket.withSingle(StringPlotBlock.EVERYTHING);
oldBlocks[y][x][z] = airBucket;
}
continue;
}
@ -155,9 +162,7 @@ public class BukkitHybridUtils extends HybridUtils {
continue;
}
int y = MainUtil.y_loc[i][j];
oldBlocks[y][x][z] = result[i][j] != null ?
result[i][j] :
BlockBucket.withSingle(StringPlotBlock.EVERYTHING);
oldBlocks[y][x][z] = result[i][j] != null ? result[i][j] : airBucket;
}
}
@ -177,7 +182,7 @@ public class BukkitHybridUtils extends HybridUtils {
BlockBucket old = oldBlocks[y][x][z];
try {
if (old == null) {
old = BlockBucket.withSingle(StringPlotBlock.EVERYTHING);
old = airBucket;
}
PlotBlock now = newBlocks[y][x][z];
if (!old.getBlocks().contains(now)) {
@ -222,10 +227,6 @@ public class BukkitHybridUtils extends HybridUtils {
types.add(now);
}
} catch (NullPointerException e) {
PlotSquared.log(old != null ? old.toString() : "old null");
PlotSquared.log(x);
PlotSquared.log(y);
PlotSquared.log(z);
e.printStackTrace();
}
}
@ -303,7 +304,7 @@ public class BukkitHybridUtils extends HybridUtils {
}
}
}
worldObj.unloadChunkRequest(X, Z, true);
worldObj.unloadChunkRequest(X, Z);
}
}, () -> TaskManager.runTaskAsync(run), 5);
});

View File

@ -17,35 +17,10 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class BukkitInventoryUtil extends InventoryUtil {
public static ItemStack getItem(PlotItemStack item) {
if (item == null) {
return null;
}
ItemStack stack = new ItemStack(BukkitUtil.getMaterial(item.getPlotBlock()), item.amount);
ItemMeta meta = null;
if (item.name != null) {
meta = stack.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name));
}
if (item.lore != null) {
if (meta == null) {
meta = stack.getItemMeta();
}
List<String> lore = new ArrayList<>();
for (String entry : item.lore) {
lore.add(ChatColor.translateAlternateColorCodes('&', entry));
}
meta.setLore(lore);
}
if (meta != null) {
stack.setItemMeta(meta);
}
return stack;
}
@Override public void open(PlotInventory inv) {
BukkitPlayer bp = (BukkitPlayer) inv.player;
Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
@ -77,24 +52,50 @@ public class BukkitInventoryUtil extends InventoryUtil {
bp.player.updateInventory();
}
private static ItemStack getItem(PlotItemStack item) {
if (item == null) {
return null;
}
ItemStack stack = new ItemStack(BukkitUtil.getMaterial(item.getPlotBlock()), item.amount);
ItemMeta meta = null;
if (item.name != null) {
meta = stack.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name));
}
if (item.lore != null) {
if (meta == null) {
meta = stack.getItemMeta();
}
List<String> lore = new ArrayList<>();
for (String entry : item.lore) {
lore.add(ChatColor.translateAlternateColorCodes('&', entry));
}
meta.setLore(lore);
}
if (meta != null) {
stack.setItemMeta(meta);
}
return stack;
}
public PlotItemStack getItem(ItemStack item) {
if (item == null) {
return null;
}
// int id = item.getTypeId();
Material id = item.getType();
short data = item.getDurability();
ItemMeta meta = item.getItemMeta();
int amount = item.getAmount();
String name = null;
String[] lore = null;
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
assert meta != null;
if (meta.hasDisplayName()) {
name = meta.getDisplayName();
}
if (meta.hasLore()) {
List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]);
lore = itemLore.toArray(new String[0]);
}
}
return new PlotItemStack(id.name(), amount, name, lore);
@ -103,20 +104,21 @@ public class BukkitInventoryUtil extends InventoryUtil {
@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;
return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i)))
.toArray(PlotItemStack[]::new);
}
@Override public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) {
@Override public boolean isOpen(PlotInventory plotInventory) {
if (!plotInventory.isOpen()) {
return false;
}
BukkitPlayer bp = (BukkitPlayer) inv.player;
BukkitPlayer bp = (BukkitPlayer) plotInventory.player;
InventoryView opened = bp.player.getOpenInventory();
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING
&& opened.getTitle() == null;
if (plotInventory.isOpen()) {
if (opened.getType() == InventoryType.CRAFTING) {
opened.getTitle();
}
}
return false;
}
}

View File

@ -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:
* <p>
* Minecraft ID mappings
* Copyright (C) 2017 Max Lee (https://github.com/Phoenix616)
* Minecraft ID mappings Copyright (C) 2017 Max Lee (https://github.com/Phoenix616)
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU General Public License along with this program. If
* not, see <http://www.gnu.org/licenses/>.
*/
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<Integer, PlotBlock> LEGACY_ID_TO_STRING_PLOT_BLOCK = new HashMap<>();
private static final Map<IdDataPair, PlotBlock> LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK =
new HashMap<>();
private static final Map<String, PlotBlock> NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>();
private static final Map<String, PlotBlock> 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<LegacyBlock> 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) {
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<LegacyBlock> 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) {
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 {
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);

View File

@ -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,15 +127,19 @@ public class BukkitSetupUtils extends SetupUtils {
break;
}
case 1: {
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.type", object.type);
}
PlotSquared.get().worlds
.set("worlds." + world + ".generator.type", object.type);
PlotSquared.get().worlds
.set("worlds." + world + ".generator.terrain", object.terrain);
PlotSquared.get().worlds
@ -141,6 +149,7 @@ public class BukkitSetupUtils extends SetupUtils {
PlotSquared.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
@ -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));
}

View File

@ -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,35 +264,29 @@ 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);
@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;
}
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]);
air = 0;
} else {
if (block.isLiquid()) {
return y;
}
sign.update(true);
air++;
}
}
}
return bukkitWorld.getMaxHeight() - 1;
}
@Override @Nullable public String[] getSign(@NonNull final Location location) {
Block block = getWorld(location.getWorld())
@ -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;
@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 {
switch (type) {
case WATER:
case LAVA:
return y;
block.setType(Material.valueOf("OAK_WALL_SIGN"), false);
}
air++;
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

View File

@ -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.
* <p>
* 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<CustomChart> 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<String> 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<String> 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<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JSONObject value = new JSONObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.put(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.put(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
}

View File

@ -154,6 +154,7 @@ public class NbtFactory {
* @return The decoded NBT compound.
* @throws IOException If anything went wrong.
*/
@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed", "resource"})
public static NbtCompound fromStream(InputStream input, StreamOptions option)
throws IOException {
DataInputStream data = null;
@ -189,24 +190,11 @@ public class NbtFactory {
*/
public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option)
throws IOException {
OutputStream output = null;
DataOutputStream data = null;
boolean suppress = true;
try {
output = stream.openStream();
data = new DataOutputStream(
option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output);
try (OutputStream output = stream.openStream();
DataOutputStream data = new DataOutputStream(
option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output)) {
invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data);
suppress = false;
} finally {
if (data != null) {
Closeables.close(data, suppress);
} else if (output != null) {
Closeables.close(output, suppress);
}
}
}

View File

@ -13,14 +13,6 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
public class OfflinePlayerUtil {
public static Player loadPlayer(String name) {
return loadPlayer(Bukkit.getOfflinePlayer(name));
}
public static Player loadPlayer(UUID id) {
return loadPlayer(Bukkit.getOfflinePlayer(id));
}
public static Player loadPlayer(OfflinePlayer player) {
if (player == null) {
return null;

View File

@ -65,11 +65,7 @@ public class SendChunk {
int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
ArrayList<Chunk> list = map.computeIfAbsent(world, k -> new ArrayList<>());
list.add(chunk);
Object c = this.methodGetHandleChunk.of(chunk).call();
this.methodInitLighting.of(c).call();
@ -92,14 +88,14 @@ public class SendChunk {
if (location == null) {
location = pp.getLocation();
}
int cx = location.getX() >> 4;
int cz = location.getZ() >> 4;
int chunkX = location.getX() >> 4;
int chunkZ = location.getZ() >> 4;
Player player = ((BukkitPlayer) pp).player;
Object entity = this.methodGetHandlePlayer.of(player).call();
for (Chunk chunk : list) {
int dx = Math.abs(cx - chunk.getX());
int dz = Math.abs(cz - chunk.getZ());
int dx = Math.abs(chunkX - chunk.getX());
int dz = Math.abs(chunkZ - chunk.getZ());
if ((dx > view) || (dz > view)) {
continue;
}
@ -118,21 +114,18 @@ public class SendChunk {
}
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override public void run() {
TaskManager.runTask(() -> {
try {
chunk.unload(true, false);
chunk.unload(true);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";"
+ chunk.getZ());
PlotSquared
.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk
.getZ());
PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
}
});
}
}

View File

@ -5,12 +5,10 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
public class SetGenCB {
@ -45,12 +43,8 @@ public class SetGenCB {
}
}
if (!set) {
Iterator<BlockPopulator> iterator = world.getPopulators().iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BukkitAugmentedGenerator) {
iterator.remove();
}
}
world.getPopulators()
.removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator);
}
PlotSquared.get()
.loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null));

View File

@ -6,7 +6,6 @@ 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.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.block.BasicLocalBlockQueue;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
@ -20,21 +19,16 @@ import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;
public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
private Field fieldNeighbors;
private Method chunkGetHandle;
public class BukkitLocalQueue extends BasicLocalBlockQueue {
public BukkitLocalQueue(String world) {
super(world);
}
@Override public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) new BasicLocalChunk(this, x, z) {
@Override public LocalChunk getLocalChunk(int x, int z) {
return new BasicLocalChunk(this, x, z) {
// Custom stuff?
};
}
@ -45,21 +39,21 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
@Override public PlotBlock getBlock(int x, int y, int z) {
World worldObj = Bukkit.getWorld(getWorld());
if (worldObj != null) {
Block block = worldObj.getBlockAt(x, y, z);
if (block == null) {
return PlotBlock.get(block.getType().toString());
} else {
return PlotBlock.get(0, 0);
}
// int id = block.getTypeId();
// if (id == 0) {
// return PlotBlock.get(0, 0);
// }
// return PlotBlock.get(id, block.getData());
return PlotBlock.get(block.getType().toString());
}
@Override public void refreshChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
if (worldObj != null) {
worldObj.refreshChunk(x, z);
} else {
PlotSquared.debug("Error Refreshing Chunk");
}
}
@Override public void fixChunkLighting(int x, int z) {
@ -68,15 +62,15 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
@Override public final void regenChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
if (worldObj != null) {
worldObj.regenerateChunk(x, z);
} else {
PlotSquared.debug("Error Regenerating Chunk");
}
}
@Override public final void setComponents(LocalChunk<T> lc) {
if (isBaseBlocks()) {
@Override public final void setComponents(LocalChunk lc) {
setBaseBlocks(lc);
} else {
setBlocks(lc);
}
}
public World getBukkitWorld() {
@ -87,31 +81,7 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
return getBukkitWorld().getChunkAt(x, z);
}
public void setBlocks(LocalChunk<T> lc) {
World worldObj = Bukkit.getWorld(getWorld());
Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ());
chunk.load(true);
for (int layer = 0; layer < lc.blocks.length; layer++) {
PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer];
if (blocksLayer != null) {
for (int j = 0; j < blocksLayer.length; j++) {
if (blocksLayer[j] != null) {
PlotBlock block = blocksLayer[j];
int x = MainUtil.x_loc[layer][j];
int y = MainUtil.y_loc[layer][j];
int z = MainUtil.z_loc[layer][j];
Block existing = chunk.getBlock(x, y, z);
if (equals(block, existing)) {
continue;
}
setMaterial(block, existing);
}
}
}
}
}
public void setBaseBlocks(LocalChunk<T> lc) {
public void setBaseBlocks(LocalChunk lc) {
World worldObj = Bukkit.getWorld(getWorld());
Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ());
chunk.load(true);
@ -182,22 +152,17 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
legacyPlotBlock.id == 0 || legacyPlotBlock.data == block.getData());
}
public void setBiomes(LocalChunk<T> lc) {
public void setBiomes(LocalChunk lc) {
if (lc.biomes != null) {
World worldObj = Bukkit.getWorld(getWorld());
int bx = lc.getX() << 4;
int bz = lc.getX() << 4;
String last = null;
Biome biome = null;
for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x];
if (biomes2 != null) {
for (int y = 0; y < biomes2.length; y++) {
String biomeStr = biomes2[y];
for (String biomeStr : biomes2) {
if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = Biome.valueOf(biomeStr.toUpperCase());
}
Biome biome = Biome.valueOf(biomeStr.toUpperCase());
worldObj.setBiome(bx, bz, biome);
}
}
@ -206,59 +171,4 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
}
}
/**
* Exploiting a bug in the vanilla lighting algorithm for faster block placement
* - Could have been achieved without reflection by force unloading specific chunks
* - Much faster just setting the variable manually though
*
* @param chunk
* @return
*/
protected Object[] disableLighting(Chunk chunk) {
try {
if (chunkGetHandle == null) {
chunkGetHandle = chunk.getClass().getDeclaredMethod("getHandle");
chunkGetHandle.setAccessible(true);
}
Object nmsChunk = chunkGetHandle.invoke(chunk);
if (fieldNeighbors == null) {
fieldNeighbors = nmsChunk.getClass().getDeclaredField("neighbors");
fieldNeighbors.setAccessible(true);
}
Object value = fieldNeighbors.get(nmsChunk);
fieldNeighbors.set(nmsChunk, 0);
return new Object[] {nmsChunk, value};
} catch (Throwable ignore) {
}
return null;
}
protected void disableLighting(Object[] disableResult) {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], 0);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
protected void resetLighting(Object[] disableResult) {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], disableResult[1]);
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
}
protected void enableLighting(Object[] disableResult) {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], 0x739C0);
} catch (Throwable ignore) {
}
}
}
}

View File

@ -23,47 +23,47 @@ public class GenChunk extends ScopedLocalBlockQueue {
public final Biome[] biomes;
public PlotBlock[][] result;
public BiomeGrid grid;
public BiomeGrid biomeGrid;
public Chunk chunk;
public String world;
public int cx;
public int cz;
@Getter @Setter private ChunkData cd = null;
public int chunkX;
public int chunkZ;
@Getter @Setter private ChunkData chunkData = null;
public GenChunk(Chunk chunk, ChunkWrapper wrap) {
public GenChunk() {
super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15));
this.biomes = Biome.values();
}
public void setChunk(Chunk chunk) {
this.chunk = chunk;
}
public Chunk getChunk() {
if (chunk == null) {
World worldObj = BukkitUtil.getWorld(world);
if (worldObj != null) {
this.chunk = worldObj.getChunkAt(cx, cz);
this.chunk = worldObj.getChunkAt(chunkX, chunkZ);
}
}
return chunk;
}
public void setChunk(Chunk chunk) {
this.chunk = chunk;
}
public void setChunk(ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
cx = wrap.x;
cz = wrap.z;
chunkX = wrap.x;
chunkZ = wrap.z;
}
@Override public void fillBiome(String biomeName) {
if (grid == null) {
if (biomeGrid == null) {
return;
}
Biome biome = Biome.valueOf(biomeName.toUpperCase());
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
this.grid.setBiome(x, z, biome);
this.biomeGrid.setBiome(x, z, biome);
}
}
}
@ -82,13 +82,14 @@ public class GenChunk extends ScopedLocalBlockQueue {
Arrays.fill(data, start, end, block);
}
}
int minx = Math.min(pos1.getX(), pos2.getX());
int miny = Math.min(pos1.getY(), pos2.getY());
int minz = Math.min(pos1.getZ(), pos2.getZ());
int maxx = Math.max(pos1.getX(), pos2.getX());
int maxy = Math.max(pos1.getY(), pos2.getY());
int maxz = Math.max(pos1.getZ(), pos2.getZ());
cd.setRegion(minx, miny, minz, maxx, maxy, maxz, block.to(Material.class));
int minX = Math.min(pos1.getX(), pos2.getX());
int minY = Math.min(pos1.getY(), pos2.getY());
int minZ = Math.min(pos1.getZ(), pos2.getZ());
int maxX = Math.max(pos1.getX(), pos2.getX());
int maxY = Math.max(pos1.getY(), pos2.getY());
int maxZ = Math.max(pos1.getZ(), pos2.getZ());
chunkData
.setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, block.to(Material.class));
}
@Override public boolean setBiome(int x, int z, String biome) {
@ -96,8 +97,8 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
public boolean setBiome(int x, int z, Biome biome) {
if (this.grid != null) {
this.grid.setBiome(x, z, biome);
if (this.biomeGrid != null) {
this.biomeGrid.setBiome(x, z, biome);
return true;
}
return false;
@ -105,10 +106,10 @@ public class GenChunk extends ScopedLocalBlockQueue {
@Override public boolean setBlock(int x, int y, int z, PlotBlock id) {
if (this.result == null) {
this.cd.setBlock(x, y, z, id.to(Material.class));
this.chunkData.setBlock(x, y, z, id.to(Material.class));
return true;
}
this.cd.setBlock(x, y, z, id.to(Material.class));
this.chunkData.setBlock(x, y, z, id.to(Material.class));
this.storeCache(x, y, z, id);
return true;
}
@ -125,10 +126,10 @@ public class GenChunk extends ScopedLocalBlockQueue {
@Override public boolean setBlock(int x, int y, int z, BaseBlock id) {
if (this.result == null) {
this.cd.setBlock(x, y, z, BukkitAdapter.adapt(id));
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
return true;
}
this.cd.setBlock(x, y, z, BukkitAdapter.adapt(id));
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
this.storeCache(x, y, z, PlotBlock.get(id.getBlockType().getId()));
return true;
}
@ -136,7 +137,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
@Override public PlotBlock getBlock(int x, int y, int z) {
int i = MainUtil.CACHE_I[y][x][z];
if (result == null) {
return PlotBlock.get(cd.getType(x, y, z));
return PlotBlock.get(chunkData.getType(x, y, z));
}
PlotBlock[] array = result[i];
if (array == null) {
@ -147,11 +148,11 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
public int getX() {
return chunk == null ? cx : chunk.getX();
return chunk == null ? chunkX : chunk.getX();
}
public int getZ() {
return chunk == null ? cz : chunk.getZ();
return chunk == null ? chunkZ : chunk.getZ();
}
@Override public String getWorld() {
@ -167,8 +168,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
public GenChunk clone() {
GenChunk toReturn =
new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
GenChunk toReturn = new GenChunk();
if (this.result != null) {
for (int i = 0; i < this.result.length; i++) {
PlotBlock[] matrix = this.result[i];
@ -178,7 +178,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
}
}
toReturn.cd = this.cd;
toReturn.chunkData = this.chunkData;
return toReturn;
}
}

View File

@ -7,12 +7,14 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.UUID;
public class DefaultUUIDWrapper extends UUIDWrapper {
@Override public UUID getUUID(PlotPlayer player) {
@NotNull @Override public UUID getUUID(PlotPlayer player) {
return ((BukkitPlayer) player).player.getUniqueId();
}
@ -30,11 +32,7 @@ public class DefaultUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.uuid;
import com.github.intellectualsites.plotsquared.bukkit.util.NbtFactory;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
@ -47,9 +47,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} else {
world = worlds.get(0).getName();
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
TaskManager.runTaskAsync(() -> {
PlotSquared.debug(Captions.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
@ -81,13 +80,11 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
}
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!");
File playerDataFolder =
new File(container, world + File.separator + "playerdata");
File playerDataFolder = new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
@ -118,7 +115,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current);
PlotSquared.debug(Captions.PREFIX + "Invalid playerdata: " + current);
}
}
}
@ -129,18 +126,17 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
return;
} else {
PlotSquared.debug("Failed to cache: " + all.size()
+ " uuids - slowly processing all files");
PlotSquared.debug(
"Failed to cache: " + all.size() + " uuids - slowly processing all files");
}
}
HashSet<String> worlds = Sets.newHashSet(world, "world");
HashSet<String> worlds1 = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
File playerDataFolder = null;
for (String worldName : worlds) {
for (String worldName : worlds1) {
// Getting UUIDs
playerDataFolder =
new File(container, worldName + File.separator + "playerdata");
playerDataFolder = new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
@ -149,7 +145,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception ignored) {
PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current);
PlotSquared.debug(Captions.PREFIX + "Invalid PlayerData: " + current);
}
}
break;
@ -203,8 +199,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
}
} catch (Exception ignored) {
PlotSquared
.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
PlotSquared.debug(
Captions.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
@ -214,15 +210,15 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper
for (OfflinePlotPlayer offlinePlotPlayer : FileUUIDHandler.this.uuidWrapper
.getOfflinePlayers()) {
long last = op.getLastPlayed();
long last = offlinePlotPlayer.getLastPlayed();
if (last != 0) {
String name = op.getName();
String name = offlinePlotPlayer.getName();
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(offlinePlotPlayer);
toAdd.putIfAbsent(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
@ -234,17 +230,14 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
if (whenDone != null) {
whenDone.run();
}
}
});
return true;
}
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}
});
}
}

View File

@ -4,14 +4,14 @@ import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.google.common.base.Charsets;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper {
@Override public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(
("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
@NotNull @Override public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override public UUID getUUID(OfflinePlotPlayer player) {

View File

@ -13,9 +13,11 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
@ -32,9 +34,8 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
}
}
@Override public UUID getUUID(PlotPlayer player) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
@NotNull @Override public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override public UUID getUUID(OfflinePlotPlayer player) {
@ -70,7 +71,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
public Player[] getOnlinePlayers() {
if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
return onlinePlayers.toArray(new Player[0]);
}
try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -79,13 +80,13 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
} else {
@SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]);
return p.toArray(new Player[0]);
}
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
PlotSquared.debug("Failed to resolve online players");
this.getOnline = null;
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
return onlinePlayers.toArray(new Player[0]);
}
}
@ -95,11 +96,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.bukkit.uuid;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.SQLite;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
@ -71,17 +71,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try {
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username =
new StringWrapper(resultSet.getString("username"));
StringWrapper username = new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
}
@ -100,10 +97,8 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
return;
}
FileUUIDHandler fileHandler =
new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override public void run() {
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(() -> {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
@ -113,22 +108,16 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
return;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
while (!toFetch.isEmpty()) {
try {
for (int i = 0;
i < Math.min(500, toFetch.size()); i++) {
for (int i = 0; i < Math.min(MAX_REQUESTS, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection =
(HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid
.toString().replace("-", ""))
.openConnection();
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
HttpURLConnection connection = (HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid.toString()
.replace("-", "")).openConnection();
try (InputStream con = connection.getInputStream()) {
InputStreamReader reader = new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
@ -154,26 +143,22 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
whenDone.run();
}
return;
}
});
}
});
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
}
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PlotSquared.debug(C.PREFIX + "UUID for '" + name
PlotSquared.debug(Captions.PREFIX + "UUID for '" + name
+ "' was null. We'll cache this from the Mojang servers!");
if (ifFetch == null) {
return;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
@ -191,7 +176,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
String name1 = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
@ -199,7 +184,6 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
TaskManager.runTask(ifFetch);
}
});
}
@ -212,47 +196,43 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
}
@Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PlotSquared
.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
e.printStackTrace();
}
}
});
return true;
}
return false;
}
/**
* This is useful for name changes
*/
@Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PlotSquared.debug(
C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
Captions.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PlotSquared
.debug(Captions.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
e.printStackTrace();
}
});
return true;
}
return false;
}
private class SQLUUIDHandlerException extends RuntimeException {

View File

@ -62,7 +62,6 @@ permissions:
plots.set.flag.vehicle-use.*: true
plots.set.flag.vehicle-place.*: true
plots.set.flag.vehicle-break.*: true
plots.set.flag.player-interact.*: true
plots.set.flag.place.*: true
plots.set.flag.break.*: true
plots.set.flag.use.*: true
@ -72,19 +71,15 @@ permissions:
plots.permpack.basicinbox:
default: op
children:
comments.notifications.enabled : true
comments.notifications.enabled: true
plots.inbox.read.public: true
plots.inbox.modify.public: true
plots.inbox.modify.public: true
plots.inbox.write.public: true
plots.inbox.read.public: true
plots.inbox.read.report: true
plots.inbox.write.report: true
plots.inbox.read.report: true
plots.inbox.read.owner: true
plots.inbox.modify.owner: true
plots.inbox.write.owner: true
plots.inbox.read.owner: true
plots.comment: true
plots.inbox: true
plots.permpack.wilderness:
@ -256,9 +251,6 @@ permissions:
plotme.limit.10:
children:
plots.plot.10: true
plotme.admin.home.other:
children:
plots.plot.: true
plotme.admin.clear:
children:
plots.admin.command.clear: true

View File

@ -1,11 +1,23 @@
import org.ajoberstar.grgit.Grgit
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
testCompile 'junit:junit:4.12'
compile 'org.yaml:snakeyaml:1.23'
compile 'com.google.code.gson:gson:2.8.5'
compileOnly 'org.projectlombok:lombok:1.18.4'
implementation 'org.yaml:snakeyaml:1.23'
//keep inline with Minecraft which uses gson 2.8.0
implementation 'com.google.code.gson:gson:2.8.0'
implementation("org.projectlombok:lombok:1.18.6")
compileOnly("org.projectlombok:lombok:1.18.6")
testCompileOnly("org.projectlombok:lombok:1.18.6")
annotationProcessor("org.projectlombok:lombok:1.18.6")
testAnnotationProcessor("org.projectlombok:lombok:1.18.6")
implementation 'net.kyori:text-adapter-bukkit:3.0.2'
implementation 'com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT'
implementation 'com.squareup.okhttp3:okhttp:3.14.0'
implementation 'com.squareup.okio:okio:2.2.2'
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.30'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
@ -21,34 +33,34 @@ processResources {
}
}
jar.archiveName = "Plotsquared-Api-${project.parent.version}.jar"
jar.destinationDir = file '../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/' + project.parent.version
jar.setArchiveName("PlotSquared-API-${project.parent.version}.jar")
jar.destinationDir = file '../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/' + project.parent.version
task createPom {
doLast {
pom {
project {
groupId 'com.github.intellectualsites.plotsquared'
artifactId 'Plotsquared'
artifactId 'PlotSquared-API'
version project.parent.version
}
}.writeTo("../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/${project.parent.version}/Plotsquared-Api-${project.parent.version}.pom")
}.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/PlotSquared-API-${project.parent.version}.pom")
pom {
project {
groupId 'com.github.intellectualsites.plotsquared'
artifactId 'Plotsquared'
artifactId 'PlotSquared-API'
version 'latest'
}
}.writeTo("../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/latest/Plotsquared-Api-latest.pom")
}.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/latest/PlotSquared-API-latest.pom")
}
}
task copyFiles {
doLast {
copy {
from "../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/${project.parent.version}/"
into '../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/latest/'
from "../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/"
into '../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/latest/'
include('*.jar')
rename("Plotsquared-Api-${project.parent.version}.jar", 'Plotsquared-Api-latest.jar')
rename("PlotSquared-API-${project.parent.version}.jar", 'PlotSquared-API-latest.jar')
}
}
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.api;
import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration;
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.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -37,7 +37,7 @@ import java.util.UUID;
@SuppressWarnings({"unused", "WeakerAccess"}) @NoArgsConstructor public class PlotAPI {
/**
* Get all plots.
* Gets all plots.
*
* @return all plots
* @see PlotSquared#getPlots()
@ -47,7 +47,7 @@ import java.util.UUID;
}
/**
* Return all plots for a player.
* Gets all plots for a player.
*
* @param player Player, whose plots to search for
* @return all plots that a player owns
@ -57,7 +57,7 @@ import java.util.UUID;
}
/**
* Add a plot world.
* Adds a plot world.
*
* @param plotArea Plot World Object
* @see PlotSquared#addPlotArea(PlotArea)
@ -67,17 +67,17 @@ import java.util.UUID;
}
/**
* Returns the PlotSquared configurations file.
* Gets the configuration file for this plugin.
*
* @return main configuration
* @see PlotSquared#config
* @return the configuration file for PlotSquared
* =
*/
public YamlConfiguration getConfig() {
return PlotSquared.get().config;
return PlotSquared.get().getConfig();
}
/**
* Get the PlotSquared storage file.
* Gets the PlotSquared storage file.
*
* @return storage configuration
* @see PlotSquared#storage
@ -86,16 +86,6 @@ import java.util.UUID;
return PlotSquared.get().storage;
}
/**
* Get the main class for this plugin. Only use this if you really need it.
*
* @return PlotSquared PlotSquared Main Class
* @see PlotSquared
*/
public PlotSquared getMain() {
return PlotSquared.get();
}
/**
* ChunkManager class contains several useful methods.
* <ul>
@ -114,7 +104,7 @@ import java.util.UUID;
}
/**
* Get the block/biome set queue
* Gets the block/biome set queue
*
* @return GlobalBlockQueue.IMP
*/
@ -145,7 +135,7 @@ import java.util.UUID;
}
/**
* Get a list of PlotAreas in the world.
* Gets a list of PlotAreas in the world.
*
* @param world The world to check for plot areas
* @return A set of PlotAreas
@ -161,20 +151,20 @@ import java.util.UUID;
* Send a message to the console. The message supports color codes.
*
* @param message the message
* @see MainUtil#sendConsoleMessage(C, String...)
* @see MainUtil#sendConsoleMessage(Captions, String...)
*/
public void sendConsoleMessage(String message) {
PlotSquared.log(message);
}
/**
* Send a message to the console.
* Sends a message to the console.
*
* @param caption the message
* @see #sendConsoleMessage(String)
* @see C
* @see Captions
*/
public void sendConsoleMessage(C caption) {
public void sendConsoleMessage(Captions caption) {
sendConsoleMessage(caption.s());
}
@ -198,7 +188,7 @@ import java.util.UUID;
}
/**
* Get the PlotPlayer for a UUID.
* Gets the PlotPlayer for a UUID.
*
* <p><i>Please note that PlotSquared can be configured to provide
* different UUIDs than bukkit</i>
@ -212,7 +202,7 @@ import java.util.UUID;
}
/**
* Get the PlotPlayer for a username.
* Gets the PlotPlayer for a username.
*
* @param player the player to wrap
* @return a {@code PlotPlayer}

View File

@ -5,12 +5,16 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory;
import com.github.intellectualsites.plotsquared.plot.commands.MainCommand;
import com.github.intellectualsites.plotsquared.plot.commands.RequiredType;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.object.PlotMessage;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.MathMan;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.github.intellectualsites.plotsquared.plot.util.StringComparison;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@ -102,7 +106,7 @@ public abstract class Command {
return this.id;
}
public List<Command> getCommands(PlotPlayer player) {
public List<Command> getCommands(CommandCaller player) {
List<Command> commands = new ArrayList<>();
for (Command cmd : this.allCommands) {
if (cmd.canExecute(player, false)) {
@ -112,15 +116,10 @@ public abstract class Command {
return commands;
}
public List<Command> getCommands(CommandCategory cat, PlotPlayer player) {
public List<Command> getCommands(CommandCategory category, CommandCaller player) {
List<Command> commands = getCommands(player);
if (cat != null) {
Iterator<Command> iterator = commands.iterator();
while (iterator.hasNext()) {
if (iterator.next().category != cat) {
iterator.remove();
}
}
if (category != null) {
commands.removeIf(command -> command.category != category);
}
return commands;
}
@ -129,7 +128,7 @@ public abstract class Command {
return this.allCommands;
}
public boolean hasConfirmation(PlotPlayer player) {
public boolean hasConfirmation(CommandCaller player) {
return this.confirmation && !player.hasPermission(getPermission() + ".confirm.bypass");
}
@ -158,10 +157,10 @@ public abstract class Command {
this.perm = declaration.permission();
this.required = declaration.requiredType();
this.category = declaration.category();
HashMap<String, Object> options = new HashMap<>();
List<String> aliasOptions = new ArrayList<>();
aliasOptions.add(this.id);
aliasOptions.addAll(Arrays.asList(declaration.aliases()));
HashMap<String, Object> options = new HashMap<>();
options.put("aliases", aliasOptions);
options.put("description", declaration.description());
options.put("usage", declaration.usage());
@ -245,18 +244,19 @@ public abstract class Command {
if (page < totalPages && page > 0) { // Back | Next
new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ")
.color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2))
.text(C.CLICKABLE.s()).color("$2").send(player);
.text(Captions.CLICKABLE.s()).color("$2").send(player);
return;
}
if (page == 0 && totalPages != 0) { // Next
new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1")
.command(baseCommand + " " + (0 + 2)).text(C.CLICKABLE.s()).color("$2")
.command(baseCommand + " " + (0 + 2)).text(Captions.CLICKABLE.s()).color("$2")
.send(player);
return;
}
if (page == totalPages && totalPages != 0) { // Back
new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ")
.color("$3").text("->").color("$3").text(C.CLICKABLE.s()).color("$2").send(player);
.color("$3").text("->").color("$3").text(Captions.CLICKABLE.s()).color("$2")
.send(player);
}
}
@ -274,7 +274,7 @@ public abstract class Command {
if (this.parent == null) {
MainCommand.getInstance().help.displayHelp(player, null, 0);
} else {
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
}
return CompletableFuture.completedFuture(false);
}
@ -286,7 +286,7 @@ public abstract class Command {
Command cmd = getCommand(args[0]);
if (cmd == null) {
if (this.parent != null) {
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
return CompletableFuture.completedFuture(false);
}
// Help command
@ -301,11 +301,11 @@ public abstract class Command {
} catch (IllegalArgumentException ignored) {
}
// Command recommendation
MainUtil.sendMessage(player, C.NOT_VALID_SUBCOMMAND);
MainUtil.sendMessage(player, Captions.NOT_VALID_SUBCOMMAND);
List<Command> commands = getCommands(player);
if (commands.isEmpty()) {
MainUtil
.sendMessage(player, C.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage());
MainUtil.sendMessage(player, Captions.DID_YOU_MEAN,
MainCommand.getInstance().help.getUsage());
return CompletableFuture.completedFuture(false);
}
HashSet<String> setArgs = new HashSet<>(args.length);
@ -323,7 +323,7 @@ public abstract class Command {
if (cmd == null) {
cmd = new StringComparison<>(args[0], this.allCommands).getMatchObject();
}
MainUtil.sendMessage(player, C.DID_YOU_MEAN, cmd.getUsage());
MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, cmd.getUsage());
return CompletableFuture.completedFuture(false);
}
String[] newArgs = Arrays.copyOfRange(args, 1, args.length);
@ -338,7 +338,7 @@ public abstract class Command {
return CompletableFuture.completedFuture(true);
}
public boolean checkArgs(PlotPlayer player, String[] args) {
public boolean checkArgs(CommandCaller player, String[] args) {
Argument<?>[] reqArgs = getRequiredArguments();
if (reqArgs != null && reqArgs.length > 0) {
boolean failed = args.length < reqArgs.length;
@ -355,7 +355,7 @@ public abstract class Command {
failed = failed || reqArgs[i].parse(args[i]) == null;
}
if (failed) {
C.COMMAND_SYNTAX.send(player, StringMan.join(fullSplit, " "));
Captions.COMMAND_SYNTAX.send(player, StringMan.join(fullSplit, " "));
return false;
}
}
@ -363,14 +363,10 @@ public abstract class Command {
}
public int getMatch(String[] args, Command cmd) {
int count = 0;
String perm = cmd.getPermission();
HashSet<String> desc = new HashSet<>();
for (String alias : cmd.getAliases()) {
if (alias.startsWith(args[0])) {
count += 5;
}
}
int count = cmd.getAliases().stream().filter(alias -> alias.startsWith(args[0]))
.mapToInt(alias -> 5).sum();
Collections.addAll(desc, cmd.getDescription().split(" "));
for (String arg : args) {
if (perm.startsWith(arg)) {
@ -435,18 +431,19 @@ public abstract class Command {
return null;
}
public boolean canExecute(PlotPlayer player, boolean message) {
public boolean canExecute(CommandCaller player, boolean message) {
if (player == null) {
return true;
}
if (!this.required.allows(player)) {
if (message) {
MainUtil.sendMessage(player,
this.required == RequiredType.PLAYER ? C.IS_CONSOLE : C.NOT_CONSOLE);
MainUtil.sendMessage(player, this.required == RequiredType.PLAYER ?
Captions.IS_CONSOLE :
Captions.NOT_CONSOLE);
}
} else if (!Permissions.hasPermission(player, getPermission())) {
if (message) {
C.NO_PERMISSION.send(player, getPermission());
Captions.NO_PERMISSION.send(player, getPermission());
}
} else {
return true;
@ -460,7 +457,6 @@ public abstract class Command {
}
public String getCommandString() {
String base;
if (this.parent == null) {
return "/" + toString();
} else {
@ -563,13 +559,13 @@ public abstract class Command {
return this.getFullId().hashCode();
}
public void checkTrue(boolean mustBeTrue, C message, Object... args) {
public void checkTrue(boolean mustBeTrue, Captions message, Object... args) {
if (!mustBeTrue) {
throw new CommandException(message, args);
}
}
public <T extends Object> T check(T object, C message, Object... args) {
public <T extends Object> T check(T object, Captions message, Object... args) {
if (object == null) {
throw new CommandException(message, args);
}
@ -583,14 +579,14 @@ public abstract class Command {
public static class CommandException extends RuntimeException {
private final Object[] args;
private final C message;
private final Captions message;
public CommandException(C message, Object... args) {
public CommandException(Captions message, Object... args) {
this.message = message;
this.args = args;
}
public void perform(PlotPlayer player) {
public void perform(CommandCaller player) {
if (player != null && message != null) {
message.send(player, args);
}

View File

@ -6,6 +6,7 @@ import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguratio
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
/**
* This is a base class for all File based implementations of {@link
@ -14,13 +15,13 @@ import java.nio.charset.StandardCharsets;
public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Creates an empty {@link FileConfiguration} with no default values.
* Creates an empty FileConfiguration with no default values.
*/
FileConfiguration() {
}
/**
* Creates an empty {@link FileConfiguration} using the specified {@link
* Creates an empty FileConfiguration using the specified {@link
* Configuration} as a source for all default values.
*
* @param defaults Default value provider
@ -30,7 +31,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
}
/**
* Saves this {@link FileConfiguration} to the specified location.
* Saves this FileConfiguration to the specified location.
*
* <p>If the file does not exist, it will be created. If already exists, it
* will be overwritten. If it cannot be overwritten or created, an
@ -58,14 +59,14 @@ public abstract class FileConfiguration extends MemoryConfiguration {
}
/**
* Saves this {@link FileConfiguration} to a string, and returns it.
* Saves this FileConfiguration to a string, and returns it.
*
* @return String containing this configuration.
*/
public abstract String saveToString();
/**
* Loads this {@link FileConfiguration} from the specified location.
* Loads this FileConfiguration from the specified location.
*
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
@ -84,13 +85,13 @@ public abstract class FileConfiguration extends MemoryConfiguration {
*/
public void load(File file) throws IOException, InvalidConfigurationException {
FileInputStream stream = new FileInputStream(file);
try (FileInputStream stream = new FileInputStream(file)) {
load(new InputStreamReader(stream, StandardCharsets.UTF_8));
}
}
/**
* Loads this {@link FileConfiguration} from the specified reader.
* Loads this FileConfiguration from the specified reader.
*
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
@ -103,24 +104,20 @@ public abstract class FileConfiguration extends MemoryConfiguration {
*/
public void load(Reader reader) throws IOException, InvalidConfigurationException {
StringBuilder builder = new StringBuilder();
String builder;
try (BufferedReader input = reader instanceof BufferedReader ?
(BufferedReader) reader :
new BufferedReader(reader)) {
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
builder = input.lines().map(line -> line + '\n').collect(Collectors.joining());
}
loadFromString(builder.toString());
loadFromString(builder);
}
/**
* Loads this {@link FileConfiguration} from the specified string, as
* Loads this FileConfiguration from the specified string, as
* opposed to from file.
*
* <p>All the values contained within this configuration will be removed,
@ -136,7 +133,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
public abstract void loadFromString(String contents) throws InvalidConfigurationException;
/**
* Compiles the header for this {@link FileConfiguration} and returns the
* Compiles the header for this FileConfiguration and returns the
* result.
*
* <p>This will use the header from {@link #options()} -> {@link

View File

@ -212,10 +212,15 @@ public class ConfigurationSerialization {
return result;
}
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) {
if (ex instanceof InvocationTargetException) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + this.clazz
+ " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
+ " for deserialization", ex.getCause());
} else {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + this.clazz
+ " for deserialization", ex);
}
}
return null;
@ -226,10 +231,15 @@ public class ConfigurationSerialization {
try {
return ctor.newInstance(args);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
if (ex instanceof InvocationTargetException) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call constructor '" + ctor.toString() + "' of " + this.clazz
+ " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
+ " for deserialization", ex.getCause());
} else {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call constructor '" + ctor.toString() + "' of " + this.clazz
+ " for deserialization", ex);
}
}
return null;

View File

@ -9,6 +9,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.IntStream;
/**
* A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces
@ -296,11 +297,7 @@ public class JSONObject {
if (length == 0) {
return null;
}
String[] names = new String[length];
for (int i = 0; i < length; i += 1) {
names[i] = fields[i].getName();
}
return names;
return IntStream.range(0, length).mapToObj(i -> fields[i].getName()).toArray(String[]::new);
}
/**

View File

@ -8,6 +8,7 @@ import com.github.intellectualsites.plotsquared.plot.object.BlockRegistry;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.List;
@ -15,28 +16,28 @@ import java.util.List;
public interface IPlotMain extends ILogger {
/**
* Log a message to console.
* Logs a message to console.
*
* @param message The message to log
* @param message the message to log
*/
void log(String message);
/**
* Get the `PlotSquared` directory.
* Gets the directory which contains PlotSquared files. The directory may not exist.
*
* @return The plugin directory
* @return the PlotSquared directory
*/
File getDirectory();
/**
* Get the directory containing all the worlds.
* Gets the folder where all world data is stored.
*
* @return The directory containing the worlds
* @return the world folder
*/
File getWorldContainer();
/**
* Wrap a player into a PlotPlayer object.
* Wraps a player into a PlotPlayer object.
*
* @param player The player to convert to a PlotPlayer
* @return A PlotPlayer
@ -44,70 +45,56 @@ public interface IPlotMain extends ILogger {
PlotPlayer wrapPlayer(Object player);
/**
* Disable the implementation.
*
* <ul>
* <li>If a full disable isn't feasibly, just disable what it can.
* </ul>
*/
void disable();
/**
* Completely shut down the plugin
* Completely shuts down the plugin.
*/
void shutdown();
/**
* Get the version of the PlotSquared being used.
* Gets the version of the PlotSquared being used.
*
* @return the plugin version
*/
int[] getPluginVersion();
/**
* Get the version of the PlotSquared being used as a string.
* Gets the version of the PlotSquared being used as a string.
*
* @return the plugin version as a string
*/
String getPluginVersionString();
/**
* Usually PlotSquared
*
* @return
*/
String getPluginName();
/**
* Get the version of Minecraft that is running.
* Gets the version of Minecraft that is running.
*
* @return
*/
int[] getServerVersion();
/**
* Get the server implementation name and version
* Gets the server implementation name and version
*/
String getServerImplementation();
/**
* Get the NMS package prefix.
* Gets the NMS package prefix.
*
* @return The NMS package prefix
*/
String getNMSPackage();
/**
* Get the schematic handler.
* Gets the schematic handler.
*
* @return The {@link SchematicHandler}
*/
SchematicHandler initSchematicHandler();
/**
* Get the Chat Manager.
* Starts the {@link ChatManager}.
*
* @return The {@link ChatManager}
* @return the ChatManager
*/
ChatManager initChatManager();
@ -124,7 +111,7 @@ public interface IPlotMain extends ILogger {
void runEntityTask();
/**
* Register the implementation specific commands.
* Registerss the implementation specific commands.
*/
void registerCommands();
@ -133,11 +120,6 @@ public interface IPlotMain extends ILogger {
*/
void registerPlayerEvents();
/**
* Register inventory related events.
*/
void registerInventoryEvents();
/**
* Register plot plus related events.
*/
@ -149,54 +131,54 @@ public interface IPlotMain extends ILogger {
void registerForceFieldEvents();
/**
* Register the WorldEdit hook.
* Registers the WorldEdit hook.
*/
boolean initWorldEdit();
/**
* Get the economy provider.
* Gets the economy provider.
*
* @return
*/
EconHandler getEconomyHandler();
/**
* Get the {@link QueueProvider} class.
* Gets the {@link QueueProvider} class.
*
* @return
*/
QueueProvider initBlockQueue();
/**
* Get the {@link WorldUtil} class.
* Gets the {@link WorldUtil} class.
*
* @return
*/
WorldUtil initWorldUtil();
/**
* Get the EventUtil class.
* Gets the EventUtil class.
*
* @return
*/
EventUtil initEventUtil();
/**
* Get the chunk manager.
* Gets the chunk manager.
*
* @return
*/
ChunkManager initChunkManager();
/**
* Get the {@link SetupUtils} class.
* Gets the {@link SetupUtils} class.
*
* @return
*/
SetupUtils initSetupUtils();
/**
* Get {@link HybridUtils} class.
* Gets {@link HybridUtils} class.
*
* @return
*/
@ -215,7 +197,7 @@ public interface IPlotMain extends ILogger {
void setGenerator(String world);
/**
* Get the {@link UUIDHandlerImplementation} which will cache and
* Gets the {@link UUIDHandlerImplementation} which will cache and
* provide UUIDs.
*
* @return
@ -223,7 +205,7 @@ public interface IPlotMain extends ILogger {
UUIDHandlerImplementation initUUIDHandler();
/**
* Get the {@link InventoryUtil} class (used for implementation specific
* Gets the {@link InventoryUtil} class (used for implementation specific
* inventory guis).
*
* @return
@ -231,14 +213,14 @@ public interface IPlotMain extends ILogger {
InventoryUtil initInventoryUtil();
/**
* Unregister a PlotPlayer from cache e.g. if they have logged off.
* Unregisters a {@link PlotPlayer} from cache e.g. if they have logged off.
*
* @param player
*/
void unregister(PlotPlayer player);
/**
* Get the generator wrapper for a world (world) and generator (name).
* Gets the generator wrapper for a world (world) and generator (name).
*
* @param world
* @param name
@ -265,14 +247,7 @@ public interface IPlotMain extends ILogger {
*
* @return Default implementation generator
*/
IndependentPlotGenerator getDefaultGenerator();
/**
* Get the class that will manage player titles.
*
* @return
*/
AbstractTitle initTitleManager();
@NotNull IndependentPlotGenerator getDefaultGenerator();
List<String> getPluginIds();

View File

@ -1,6 +1,6 @@
package com.github.intellectualsites.plotsquared.plot;
public enum Platform {
Bukkit, Sponge, Spigot, Cauldron
Bukkit, Sponge, Spigot, Paper
}

View File

@ -32,10 +32,9 @@ public class PlotVersion {
@Override public String toString() {
if (hash == 0 && build == 0) {
return "PlotSquared-" + year + "." + month + "." + day + "-SNAPSHOT";
return "PlotSquared-NoVer-SNAPSHOT";
} else {
return "PlotSquared-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash)
+ "-" + build;
return "PlotSquared-4." + build;
}
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Command;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -20,7 +20,7 @@ import java.util.concurrent.CompletableFuture;
@CommandDeclaration(command = "add",
description = "Allow a user to build in a plot while you are online",
usage = "/plot add <player>", category = CommandCategory.SETTINGS, permission = "plots.add",
requiredType = RequiredType.NONE) public class Add extends Command {
requiredType = RequiredType.PLAYER) public class Add extends Command {
public Add() {
super(MainCommand.getInstance(), true);
@ -29,39 +29,41 @@ import java.util.concurrent.CompletableFuture;
@Override public CompletableFuture<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT);
checkTrue(plot.hasOwner(), C.PLOT_UNOWNED);
final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT);
checkTrue(plot.hasOwner(), Captions.PLOT_UNOWNED);
checkTrue(plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.NO_PLOT_PERMS);
checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage());
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST),
Captions.NO_PLOT_PERMS);
checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage());
final Set<UUID> uuids = MainUtil.getUUIDsFromString(args[0]);
checkTrue(!uuids.isEmpty(), C.INVALID_PLAYER, args[0]);
Iterator<UUID> iter = uuids.iterator();
checkTrue(!uuids.isEmpty(), Captions.INVALID_PLAYER, args[0]);
Iterator<UUID> iterator = uuids.iterator();
int size = plot.getTrusted().size() + plot.getMembers().size();
while (iter.hasNext()) {
UUID uuid = iter.next();
while (iterator.hasNext()) {
UUID uuid = iterator.next();
if (uuid == DBFunc.EVERYONE && !(
Permissions.hasPermission(player, C.PERMISSION_TRUST_EVERYONE) || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST))) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, MainUtil.getName(uuid));
iter.remove();
Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) {
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid));
iterator.remove();
continue;
}
if (plot.isOwner(uuid)) {
MainUtil.sendMessage(player, C.ALREADY_OWNER, MainUtil.getName(uuid));
iter.remove();
MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid));
iterator.remove();
continue;
}
if (plot.getMembers().contains(uuid)) {
MainUtil.sendMessage(player, C.ALREADY_ADDED, MainUtil.getName(uuid));
iter.remove();
MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid));
iterator.remove();
continue;
}
size += plot.getTrusted().contains(uuid) ? 0 : 1;
}
checkTrue(!uuids.isEmpty(), null);
checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS);
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST),
Captions.PLOT_MAX_MEMBERS);
// Success
confirm.run(this, () -> {
for (UUID uuid : uuids) {
@ -74,7 +76,7 @@ import java.util.concurrent.CompletableFuture;
}
plot.addMember(uuid);
EventUtil.manager.callMember(player, plot, uuid, true);
MainUtil.sendMessage(player, C.MEMBER_ADDED);
MainUtil.sendMessage(player, Captions.MEMBER_ADDED);
}
}, null);

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -15,29 +15,29 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
@CommandDeclaration(command = "setalias", permission = "plots.alias",
description = "Set the plot name", usage = "/plot alias <set|remove> <alias>",
aliases = {"alias", "sa", "name", "rename", "setname", "seta", "nameplot"},
category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Alias
category = CommandCategory.SETTINGS, requiredType = RequiredType.PLAYER) public class Alias
extends SubCommand {
@Override public boolean onCommand(PlotPlayer player, String[] args) {
if (args.length == 0) {
C.COMMAND_SYNTAX.send(player, "/plot alias <set|remove> <value>");
Captions.COMMAND_SYNTAX.send(player, "/plot alias <set|remove> <value>");
return false;
}
Location loc = player.getLocation();
Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(player, C.NOT_IN_PLOT);
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot.hasOwner()) {
sendMessage(player, C.PLOT_NOT_CLAIMED);
sendMessage(player, Captions.PLOT_NOT_CLAIMED);
return false;
}
if (!plot.isOwner(player.getUUID())) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS);
return false;
}
@ -46,25 +46,25 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
switch (args[0].toLowerCase()) {
case "set":
if (args.length != 2) {
C.COMMAND_SYNTAX.send(player, "/plot alias <set> <value>");
Captions.COMMAND_SYNTAX.send(player, "/plot alias <set> <value>");
return false;
}
if (canExecuteCommand(player, C.PERMISSION_ALIAS_SET, false) || canExecuteCommand(
player, C.PERMISSION_ALIAS_SET_OBSOLETE, false)) {
if (canExecuteCommand(player, Captions.PERMISSION_ALIAS_SET, false)
|| canExecuteCommand(player, Captions.PERMISSION_ALIAS_SET_OBSOLETE, false)) {
result = setAlias(player, plot, args[1]);
} else {
MainUtil.sendMessage(player, C.NO_PERMISSION);
MainUtil.sendMessage(player, Captions.NO_PERMISSION);
}
break;
case "remove":
if (canExecuteCommand(player, C.PERMISSION_ALIAS_REMOVE, true)) {
if (canExecuteCommand(player, Captions.PERMISSION_ALIAS_REMOVE, true)) {
result = removeAlias(player, plot);
}
break;
default:
C.COMMAND_SYNTAX.send(player, "/plot alias <set|remove> <alias>");
Captions.COMMAND_SYNTAX.send(player, "/plot alias <set|remove> <alias>");
result = false;
}
@ -74,47 +74,47 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
private boolean setAlias(PlotPlayer player, Plot plot, String alias) {
if (alias.isEmpty()) {
C.COMMAND_SYNTAX.send(player, "/plot alias <set> <value>");
Captions.COMMAND_SYNTAX.send(player, "/plot alias <set> <value>");
return false;
}
if (alias.length() >= 50) {
MainUtil.sendMessage(player, C.ALIAS_TOO_LONG);
MainUtil.sendMessage(player, Captions.ALIAS_TOO_LONG);
return false;
}
if (alias.contains(" ")) {
C.NOT_VALID_VALUE.send(player);
Captions.NOT_VALID_VALUE.send(player);
return false;
}
if (MathMan.isInteger(alias)) {
C.NOT_VALID_VALUE.send(player);
Captions.NOT_VALID_VALUE.send(player);
return false;
}
for (Plot p : PlotSquared.get().getPlots(plot.getArea())) {
if (p.getAlias().equalsIgnoreCase(alias)) {
MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN);
MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN);
return false;
}
}
if (UUIDHandler.nameExists(new StringWrapper(alias)) || PlotSquared.get()
.hasPlotArea(alias)) {
MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN);
MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN);
return false;
}
plot.setAlias(alias);
MainUtil.sendMessage(player, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
MainUtil.sendMessage(player, Captions.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
return true;
}
private boolean removeAlias(PlotPlayer player, Plot plot) {
plot.setAlias(null);
MainUtil.sendMessage(player, C.ALIAS_REMOVED.s());
MainUtil.sendMessage(player, Captions.ALIAS_REMOVED.s());
return true;
}
private boolean canExecuteCommand(PlotPlayer player, C caption, boolean sendMessage) {
private boolean canExecuteCommand(PlotPlayer player, Captions caption, boolean sendMessage) {
if (!Permissions.hasPermission(player, caption)) {
if (sendMessage) {
MainUtil.sendMessage(player, C.NO_PERMISSION);
MainUtil.sendMessage(player, Captions.NO_PERMISSION);
}
return false;
}

View File

@ -3,7 +3,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
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.config.Configuration;
import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld;
@ -23,20 +23,20 @@ import java.util.Set;
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length == 0) {
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
return false;
}
switch (args[0].toLowerCase()) {
case "c":
case "setup":
case "create":
if (!Permissions.hasPermission(player, C.PERMISSION_AREA_CREATE)) {
C.NO_PERMISSION.send(player, C.PERMISSION_AREA_CREATE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_CREATE)) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_CREATE);
return false;
}
switch (args.length) {
case 1:
C.COMMAND_SYNTAX
Captions.COMMAND_SYNTAX
.send(player, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
case 2:
@ -44,13 +44,13 @@ import java.util.Set;
case "pos1": { // Set position 1
HybridPlotWorld area = player.getMeta("area_create_area");
if (area == null) {
C.COMMAND_SYNTAX.send(player,
Captions.COMMAND_SYNTAX.send(player,
"/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
Location location = player.getLocation();
player.setMeta("area_pos1", location);
C.SET_ATTRIBUTE.send(player, "area_pos1",
Captions.SET_ATTRIBUTE.send(player, "area_pos1",
location.getX() + "," + location.getZ());
MainUtil.sendMessage(player,
"You will now set pos2: /plot area create pos2"
@ -60,7 +60,7 @@ import java.util.Set;
case "pos2": // Set position 2 and finish creation for type=2 (partial)
final HybridPlotWorld area = player.getMeta("area_create_area");
if (area == null) {
C.COMMAND_SYNTAX.send(player,
Captions.COMMAND_SYNTAX.send(player,
"/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
@ -87,7 +87,7 @@ import java.util.Set;
Set<PlotArea> areas =
PlotSquared.get().getPlotAreas(area.worldname, region);
if (!areas.isEmpty()) {
C.CLUSTER_INTERSECTION
Captions.CLUSTER_INTERSECTION
.send(player, areas.iterator().next().toString());
return false;
}
@ -104,8 +104,7 @@ import java.util.Set;
final String path =
"worlds." + area.worldname + ".areas." + area.id + '-'
+ object.min + '-' + object.max;
Runnable run = new Runnable() {
@Override public void run() {
Runnable run = () -> {
if (offsetX != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX);
@ -117,7 +116,7 @@ import java.util.Set;
final String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
PlotSquared.get().loadWorld(world, null);
C.SETUP_FINISHED.send(player);
Captions.SETUP_FINISHED.send(player);
player.teleport(WorldUtil.IMP.getSpawn(world));
if (area.TERRAIN != 3) {
ChunkManager.largeRegionTask(world, region,
@ -134,7 +133,6 @@ import java.util.Set;
"An error occurred while creating the world: "
+ area.worldname);
}
}
};
if (hasConfirmation(player)) {
CmdConfirm.addPending(player,
@ -145,7 +143,6 @@ import java.util.Set;
return true;
}
default: // Start creation
final SetupObject object = new SetupObject();
String[] split = args[1].split(":");
String id;
if (split.length == 2) {
@ -153,12 +150,13 @@ import java.util.Set;
} else {
id = null;
}
final SetupObject object = new SetupObject();
object.world = split[0];
final HybridPlotWorld pa = new HybridPlotWorld(object.world, id,
PlotSquared.get().IMP.getDefaultGenerator(), null, null);
PlotArea other = PlotSquared.get().getPlotArea(pa.worldname, id);
if (other != null && Objects.equals(pa.id, other.id)) {
C.SETUP_WORLD_TAKEN.send(player, pa.toString());
Captions.SETUP_WORLD_TAKEN.send(player, pa.toString());
return false;
}
Set<PlotArea> areas = PlotSquared.get().getPlotAreas(pa.worldname);
@ -170,7 +168,7 @@ import java.util.Set;
for (int i = 2; i < args.length; i++) {
String[] pair = args[i].split("=");
if (pair.length != 2) {
C.COMMAND_SYNTAX.send(player, getCommandString()
Captions.COMMAND_SYNTAX.send(player, getCommandString()
+ " create [world[:id]] [<modifier>=<value>]...");
return false;
}
@ -218,18 +216,17 @@ import java.util.Set;
object.type = pa.TYPE;
break;
default:
C.COMMAND_SYNTAX.send(player, getCommandString()
Captions.COMMAND_SYNTAX.send(player, getCommandString()
+ " create [world[:id]] [<modifier>=<value>]...");
return false;
}
}
if (pa.TYPE != 2) {
if (WorldUtil.IMP.isWorld(pa.worldname)) {
C.SETUP_WORLD_TAKEN.send(player, pa.worldname);
Captions.SETUP_WORLD_TAKEN.send(player, pa.worldname);
return false;
}
Runnable run = new Runnable() {
@Override public void run() {
Runnable run = () -> {
String path = "worlds." + pa.worldname;
if (!PlotSquared.get().worlds.contains(path)) {
PlotSquared.get().worlds.createSection(path);
@ -242,7 +239,7 @@ import java.util.Set;
object.setupGenerator = PlotSquared.imp().getPluginName();
String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
C.SETUP_FINISHED.send(player);
Captions.SETUP_FINISHED.send(player);
player.teleport(WorldUtil.IMP.getSpawn(world));
} else {
MainUtil.sendMessage(player,
@ -254,7 +251,6 @@ import java.util.Set;
} catch (IOException e) {
e.printStackTrace();
}
}
};
if (hasConfirmation(player)) {
CmdConfirm.addPending(player,
@ -265,7 +261,7 @@ import java.util.Set;
return true;
}
if (pa.id == null) {
C.COMMAND_SYNTAX.send(player, getCommandString()
Captions.COMMAND_SYNTAX.send(player, getCommandString()
+ " create [world[:id]] [<modifier>=<value>]...");
return false;
}
@ -288,8 +284,8 @@ import java.util.Set;
return true;
case "i":
case "info": {
if (!Permissions.hasPermission(player, C.PERMISSION_AREA_INFO)) {
C.NO_PERMISSION.send(player, C.PERMISSION_AREA_INFO);
if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_INFO)) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_INFO);
return false;
}
PlotArea area;
@ -301,14 +297,14 @@ import java.util.Set;
area = PlotSquared.get().getPlotAreaByString(args[1]);
break;
default:
C.COMMAND_SYNTAX.send(player, getCommandString() + " info [area]");
Captions.COMMAND_SYNTAX.send(player, getCommandString() + " info [area]");
return false;
}
if (area == null) {
if (args.length == 2) {
C.NOT_VALID_PLOT_WORLD.send(player, args[1]);
Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]);
} else {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
return false;
}
@ -335,13 +331,14 @@ import java.util.Set;
+ "\n$1Claimed: $2" + claimed + "\n$1Clusters: $2" + clusters + "\n$1Region: $2"
+ region + "\n$1Generator: $2" + generator;
MainUtil.sendMessage(player,
C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false);
Captions.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + Captions.PLOT_INFO_FOOTER
.s(), false);
return true;
}
case "l":
case "list":
if (!Permissions.hasPermission(player, C.PERMISSION_AREA_LIST)) {
C.NO_PERMISSION.send(player, C.PERMISSION_AREA_LIST);
if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_LIST)) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_LIST);
return false;
}
int page;
@ -355,7 +352,7 @@ import java.util.Set;
break;
}
default:
C.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]");
Captions.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]");
return false;
}
ArrayList<PlotArea> areas = new ArrayList<>(PlotSquared.get().getPlotAreas());
@ -397,19 +394,19 @@ import java.util.Set;
.color("$1").text(" - ").color("$2")
.text(area.TYPE + ":" + area.TERRAIN).color("$3");
}
}, "/plot area list", C.AREA_LIST_HEADER_PAGED.s());
}, "/plot area list", Captions.AREA_LIST_HEADER_PAGED.s());
return true;
case "regen":
case "clear":
case "reset":
case "regenerate": {
if (!Permissions.hasPermission(player, C.PERMISSION_AREA_REGEN)) {
C.NO_PERMISSION.send(player, C.PERMISSION_AREA_REGEN);
if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_REGEN)) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_REGEN);
return false;
}
final PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
return false;
}
if (area.TYPE != 2) {
@ -422,11 +419,7 @@ import java.util.Set;
@Override public void run(ChunkLoc value) {
AugmentedUtils.generate(area.worldname, value.x, value.z, null);
}
}, new Runnable() {
@Override public void run() {
player.sendMessage("Regen complete");
}
});
}, () -> player.sendMessage("Regen complete"));
return true;
}
case "goto":
@ -434,17 +427,17 @@ import java.util.Set;
case "teleport":
case "visit":
case "tp":
if (!Permissions.hasPermission(player, C.PERMISSION_AREA_TP)) {
C.NO_PERMISSION.send(player, C.PERMISSION_AREA_TP);
if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_TP)) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_TP);
return false;
}
if (args.length != 2) {
C.COMMAND_SYNTAX.send(player, "/plot visit [area]");
Captions.COMMAND_SYNTAX.send(player, "/plot visit [area]");
return false;
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]);
if (area == null) {
C.NOT_VALID_PLOT_WORLD.send(player, args[1]);
Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]);
return false;
}
Location center;
@ -470,7 +463,7 @@ import java.util.Set;
+ "\n$1Stop the server and delete it from these locations.");
return true;
}
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
return false;
}

View File

@ -2,11 +2,20 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.object.Expression;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities;
import com.github.intellectualsites.plotsquared.plot.util.EconHandler;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import javax.annotation.Nullable;
import java.util.Set;
@ -21,36 +30,41 @@ public class Auto extends SubCommand {
}
private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea,
@Nullable Integer allowed_plots, int size_x, int size_z) {
if (allowed_plots == null)
allowed_plots = player.getAllowedPlots();
int currentPlots =
Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname);
int diff = currentPlots - allowed_plots;
if (diff + size_x * size_z > 0) {
@Nullable Integer allowedPlots, int sizeX, int sizeZ) {
if (allowedPlots == null) {
allowedPlots = player.getAllowedPlots();
}
int currentPlots;
if (Settings.Limit.GLOBAL) {
currentPlots = player.getPlotCount();
} else {
currentPlots = player.getPlotCount(plotarea.worldname);
}
int diff = currentPlots - allowedPlots;
if (diff + sizeX * sizeZ > 0) {
if (diff < 0) {
MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + "");
MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS_NUM, -diff + "");
return false;
} else if (player.hasPersistentMeta("grantedPlots")) {
int grantedPlots =
ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots"));
if (grantedPlots - diff < size_x * size_z) {
if (grantedPlots - diff < sizeX * sizeZ) {
player.removePersistentMeta("grantedPlots");
MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS);
MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS);
return false;
} else {
int left = grantedPlots - diff - size_x * size_z;
int left = grantedPlots - diff - sizeX * sizeZ;
if (left == 0) {
player.removePersistentMeta("grantedPlots");
} else {
player.setPersistentMeta("grantedPlots",
ByteArrayUtilities.integerToBytes(left));
}
MainUtil.sendMessage(player, C.REMOVED_GRANTED_PLOT, "" + left,
MainUtil.sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "" + left,
"" + (grantedPlots - left));
}
} else {
MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS);
MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS);
return false;
}
}
@ -63,15 +77,15 @@ public class Auto extends SubCommand {
* @param player
* @param area
* @param start
* @param schem
* @param schematic
*/
public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start,
final String schem) {
final String schematic) {
Set<Plot> plots = player.getPlots();
if (!plots.isEmpty()) {
plots.iterator().next().teleportPlayer(player);
} else {
autoClaimSafe(player, area, start, schem);
autoClaimSafe(player, area, start, schematic);
}
}
@ -81,11 +95,11 @@ public class Auto extends SubCommand {
* @param player
* @param area
* @param start
* @param schem
* @param schematic
*/
public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start,
final String schem) {
autoClaimSafe(player, area, start, schem, null);
final String schematic) {
autoClaimSafe(player, area, start, schematic, null);
}
/**
@ -94,10 +108,10 @@ public class Auto extends SubCommand {
* @param player
* @param area
* @param start
* @param schem
* @param schematic
*/
public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start,
final String schem, @Nullable final Integer allowed_plots) {
final String schematic, @Nullable final Integer allowedPlots) {
player.setMeta(Auto.class.getName(), true);
autoClaimFromDatabase(player, area, start, new RunnableVal<Plot>() {
@Override public void run(final Plot plot) {
@ -105,9 +119,9 @@ public class Auto extends SubCommand {
@Override public void run(Object ignore) {
player.deleteMeta(Auto.class.getName());
if (plot == null) {
MainUtil.sendMessage(player, C.NO_FREE_PLOTS);
} else if (checkAllowedPlots(player, area, allowed_plots, 1, 1)) {
plot.claim(player, true, schem, false);
MainUtil.sendMessage(player, Captions.NO_FREE_PLOTS);
} else if (checkAllowedPlots(player, area, allowedPlots, 1, 1)) {
plot.claim(player, true, schematic, false);
if (area.AUTO_MERGE) {
plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true);
}
@ -129,11 +143,8 @@ public class Auto extends SubCommand {
}
whenDone.value = plot;
plot.owner = player.getUUID();
DBFunc.createPlotSafe(plot, whenDone, new Runnable() {
@Override public void run() {
autoClaimFromDatabase(player, area, plot.getId(), whenDone);
}
});
DBFunc.createPlotSafe(plot, whenDone,
() -> autoClaimFromDatabase(player, area, plot.getId(), whenDone));
}
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
@ -152,7 +163,7 @@ public class Auto extends SubCommand {
}
}
if (plotarea == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT_WORLD);
MainUtil.sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
return false;
}
}
@ -160,7 +171,7 @@ public class Auto extends SubCommand {
int size_z = 1;
String schematic = null;
if (args.length > 0) {
if (Permissions.hasPermission(player, C.PERMISSION_AUTO_MEGA)) {
if (Permissions.hasPermission(player, Captions.PERMISSION_AUTO_MEGA)) {
try {
String[] split = args[0].split(",|;");
size_x = Integer.parseInt(split[0]);
@ -181,29 +192,31 @@ public class Auto extends SubCommand {
}
} else {
schematic = args[0];
// PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
// PlayerFunctions.sendMessage(plr, Captions.NO_PERMISSION);
// return false;
}
}
if (size_x * size_z > Settings.Claim.MAX_AUTO_AREA) {
MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM,
MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS_NUM,
Settings.Claim.MAX_AUTO_AREA + "");
return false;
}
final int allowed_plots = player.getAllowedPlots();
if (player.getMeta(Auto.class.getName(), false) || !checkAllowedPlots(player, plotarea,
allowed_plots, size_x, size_z))
allowed_plots, size_x, size_z)) {
return false;
}
if (schematic != null && !schematic.isEmpty()) {
if (!plotarea.SCHEMATICS.contains(schematic.toLowerCase())) {
sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
sendMessage(player, Captions.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true;
}
if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic))
&& !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLAIM_SCHEMATIC.f(schematic));
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic))
&& !Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic));
return true;
}
}
@ -215,11 +228,11 @@ public class Auto extends SubCommand {
cost = (size_x * size_z) * cost;
if (cost > 0d) {
if (EconHandler.manager.getMoney(player) < cost) {
sendMessage(player, C.CANNOT_AFFORD_PLOT, "" + cost);
sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost);
return true;
}
EconHandler.manager.withdrawMoney(player, cost);
sendMessage(player, C.REMOVED_BALANCE, cost + "");
sendMessage(player, Captions.REMOVED_BALANCE, cost + "");
}
}
// TODO handle type 2 the same as normal worlds!
@ -228,7 +241,7 @@ public class Auto extends SubCommand {
return true;
} else {
if (plotarea.TYPE == 2) {
MainUtil.sendMessage(player, C.NO_FREE_PLOTS);
MainUtil.sendMessage(player, Captions.NO_FREE_PLOTS);
return false;
}
while (true) {
@ -243,8 +256,7 @@ public class Auto extends SubCommand {
plot.claim(player, teleport, null);
}
}
if (!plotarea
.mergePlots(MainUtil.getPlotSelectionIds(start, end), true)) {
if (!plotarea.mergePlots(MainUtil.getPlotSelectionIds(start, end), true)) {
return false;
}
break;

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
@ -17,21 +17,19 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil;
int biome = WorldUtil.IMP.getBiomeFromString(value);
if (biome == -1) {
String biomes =
StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s());
C.NEED_BIOME.send(player);
MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes);
StringMan.join(WorldUtil.IMP.getBiomeList(), Captions.BLOCK_LIST_SEPARATER.s());
Captions.NEED_BIOME.send(player);
MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes);
return false;
}
if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
return false;
}
plot.addRunning();
plot.setBiome(value.toUpperCase(), new Runnable() {
@Override public void run() {
plot.setBiome(value.toUpperCase(), () -> {
plot.removeRunning();
MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase());
}
MainUtil.sendMessage(player, Captions.BIOME_SET_TO.s() + value.toLowerCase());
});
return true;
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Command;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -27,39 +27,40 @@ import java.util.concurrent.CompletableFuture;
@Override public CompletableFuture<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
final RunnableVal2<Command, CommandResult> whenDone) {
check(EconHandler.manager, C.ECON_DISABLED);
check(EconHandler.manager, Captions.ECON_DISABLED);
final Plot plot;
if (args.length != 0) {
checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage());
checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage());
plot = check(MainUtil.getPlotFromString(player, args[0], true), null);
} else {
plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT);
plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT);
}
checkTrue(plot.hasOwner(), C.PLOT_UNOWNED);
checkTrue(!plot.isOwner(player.getUUID()), C.CANNOT_BUY_OWN);
checkTrue(plot.hasOwner(), Captions.PLOT_UNOWNED);
checkTrue(!plot.isOwner(player.getUUID()), Captions.CANNOT_BUY_OWN);
Set<Plot> plots = plot.getConnectedPlots();
checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(),
C.CANT_CLAIM_MORE_PLOTS);
Captions.CANT_CLAIM_MORE_PLOTS);
Optional<Double> flag = plot.getFlag(Flags.PRICE);
if (!flag.isPresent()) {
throw new CommandException(C.NOT_FOR_SALE);
throw new CommandException(Captions.NOT_FOR_SALE);
}
final double price = flag.get();
checkTrue(player.getMoney() >= price, C.CANNOT_AFFORD_PLOT);
checkTrue(player.getMoney() >= price, Captions.CANNOT_AFFORD_PLOT);
player.withdraw(price);
// Failure
// Success
confirm.run(this, () -> {
C.REMOVED_BALANCE.send(player, price);
Captions.REMOVED_BALANCE.send(player, price);
EconHandler.manager
.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price);
PlotPlayer owner = UUIDHandler.getPlayer(plot.owner);
if (owner != null) {
C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price);
Captions.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price);
}
plot.removeFlag(Flags.PRICE);
plot.setOwner(player.getUUID());
C.CLAIMED.send(player);
Captions.CLAIMED.send(player);
whenDone.run(Buy.this, CommandResult.SUCCESS);
}, () -> {
player.deposit(price);

View File

@ -5,7 +5,7 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@CommandDeclaration(command = "chat", description = "Toggle plot chat on or off",
usage = "/plot chat [on|off]", permission = "plots.chat", category = CommandCategory.CHAT,
requiredType = RequiredType.NONE) public class Chat extends SubCommand {
requiredType = RequiredType.PLAYER) public class Chat extends SubCommand {
@Override public boolean onCommand(PlotPlayer player, String[] args) {
MainCommand.getInstance().toggle.chat(this, player, new String[0], null, null);

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.*;
@ -23,7 +23,7 @@ public class Claim extends SubCommand {
Location loc = player.getLocation();
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return sendMessage(player, C.NOT_IN_PLOT);
return sendMessage(player, Captions.NOT_IN_PLOT);
}
int currentPlots =
Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld());
@ -34,40 +34,43 @@ public class Claim extends SubCommand {
ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots"));
if (grants <= 0) {
player.removePersistentMeta("grantedPlots");
return sendMessage(player, C.CANT_CLAIM_MORE_PLOTS);
return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS);
}
} else {
return sendMessage(player, C.CANT_CLAIM_MORE_PLOTS);
return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS);
}
}
if (!plot.canClaim(player)) {
return sendMessage(player, C.PLOT_IS_CLAIMED);
return sendMessage(player, Captions.PLOT_IS_CLAIMED);
}
final PlotArea area = plot.getArea();
if (!schematic.isEmpty()) {
if (area.SCHEMATIC_CLAIM_SPECIFY) {
if (!area.SCHEMATICS.contains(schematic.toLowerCase())) {
return sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return sendMessage(player, Captions.SCHEMATIC_INVALID,
"non-existent: " + schematic);
}
if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic))
&& !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) {
return sendMessage(player, C.NO_SCHEMATIC_PERMISSION, schematic);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic))
&& !Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) {
return sendMessage(player, Captions.NO_SCHEMATIC_PERMISSION, schematic);
}
}
}
int border = area.getBorder();
if (border != Integer.MAX_VALUE && plot.getDistanceFromOrigin() > border) {
return !sendMessage(player, C.BORDER);
return !sendMessage(player, Captions.BORDER);
}
if ((EconHandler.manager != null) && area.USE_ECONOMY) {
Expression<Double> costExr = area.PRICES.get("claim");
double cost = costExr.evaluate((double) currentPlots);
if (cost > 0d) {
if (EconHandler.manager.getMoney(player) < cost) {
return sendMessage(player, C.CANNOT_AFFORD_PLOT, "" + cost);
return sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost);
}
EconHandler.manager.withdrawMoney(player, cost);
sendMessage(player, C.REMOVED_BALANCE, cost + "");
sendMessage(player, Captions.REMOVED_BALANCE, cost + "");
}
}
if (grants > 0) {
@ -77,30 +80,22 @@ public class Claim extends SubCommand {
player.setPersistentMeta("grantedPlots",
ByteArrayUtilities.integerToBytes(grants - 1));
}
sendMessage(player, C.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1));
sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1));
}
if (plot.canClaim(player)) {
plot.owner = player.getUUID();
final String finalSchematic = schematic;
DBFunc.createPlotSafe(plot, new Runnable() {
@Override public void run() {
TaskManager.IMP.sync(new RunnableVal<Object>() {
DBFunc.createPlotSafe(plot, () -> TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override public void run(Object value) {
plot.claim(player, true, finalSchematic, false);
if (area.AUTO_MERGE) {
plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true);
}
}
});
}
}, new Runnable() {
@Override public void run() {
sendMessage(player, C.PLOT_NOT_CLAIMED);
}
});
}), () -> sendMessage(player, Captions.PLOT_NOT_CLAIMED));
return true;
} else {
sendMessage(player, C.PLOT_NOT_CLAIMED);
sendMessage(player, Captions.PLOT_NOT_CLAIMED);
}
return false;
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Command;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.flag.FlagManager;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
@ -30,13 +30,14 @@ import java.util.concurrent.CompletableFuture;
@Override public CompletableFuture<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
checkTrue(args.length == 0, C.COMMAND_SYNTAX, getUsage());
final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT);
checkTrue(args.length == 0, Captions.COMMAND_SYNTAX, getUsage());
final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT);
checkTrue(plot.isOwner(player.getUUID()) || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CLEAR), C.NO_PLOT_PERMS);
checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER);
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_CLEAR),
Captions.NO_PLOT_PERMS);
checkTrue(plot.getRunning() == 0, Captions.WAIT_FOR_TIMER);
checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions
.hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE);
.hasPermission(player, Captions.PERMISSION_CONTINUE), Captions.DONE_ALREADY_DONE);
confirm.run(this, () -> {
final long start = System.currentTimeMillis();
boolean result = plot.clear(true, false, () -> {
@ -50,12 +51,12 @@ import java.util.concurrent.CompletableFuture;
if (plot.getFlag(Flags.ANALYSIS).isPresent()) {
FlagManager.removePlotFlag(plot, Flags.ANALYSIS);
}
MainUtil.sendMessage(player, C.CLEARING_DONE,
MainUtil.sendMessage(player, Captions.CLEARING_DONE,
"" + (System.currentTimeMillis() - start));
});
});
if (!result) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
} else {
plot.addRunning();
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.*;
@ -25,56 +25,59 @@ import java.util.UUID;
// list, create, delete, resize, invite, kick, leave, helpers, tp, sethome
if (args.length == 0) {
// return arguments
MainUtil.sendMessage(player, C.CLUSTER_AVAILABLE_ARGS);
MainUtil.sendMessage(player, Captions.CLUSTER_AVAILABLE_ARGS);
return false;
}
String sub = args[0].toLowerCase();
switch (sub) {
case "l":
case "list": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_LIST)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_LIST);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_LIST)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_LIST);
return false;
}
if (args.length != 1) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster list");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster list");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
return false;
}
Set<PlotCluster> clusters = area.getClusters();
MainUtil.sendMessage(player, C.CLUSTER_LIST_HEADING, clusters.size() + "");
MainUtil.sendMessage(player, Captions.CLUSTER_LIST_HEADING, clusters.size() + "");
for (PlotCluster cluster : clusters) {
// Ignore unmanaged clusters
String name = "'" + cluster.getName() + "' : " + cluster.toString();
if (player.getUUID().equals(cluster.owner)) {
MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, "&a" + name);
MainUtil.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, "&a" + name);
} else if (cluster.helpers.contains(player.getUUID())) {
MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, "&3" + name);
MainUtil.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, "&3" + name);
} else if (cluster.invited.contains(player.getUUID())) {
MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, "&9" + name);
MainUtil.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, "&9" + name);
} else {
MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, cluster.toString());
MainUtil
.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, cluster.toString());
}
}
return true;
}
case "c":
case "create": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_CREATE)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_CREATE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_CREATE)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_CREATE);
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
return false;
}
if (args.length != 4) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster create <name> <id-bot> <id-top>");
return false;
}
@ -82,19 +85,22 @@ import java.util.UUID;
player.getClusterCount() :
player.getPlotCount(player.getLocation().getWorld());
if (currentClusters >= player.getAllowedPlots()) {
return sendMessage(player, C.CANT_CLAIM_MORE_CLUSTERS);
return sendMessage(player, Captions.CANT_CLAIM_MORE_CLUSTERS);
}
PlotId pos1;
PlotId pos2;
// check pos1 / pos2
PlotId pos1 = PlotId.fromString(args[2]);
PlotId pos2 = PlotId.fromString(args[3]);
if (pos1 == null || pos2 == null) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID);
try {
pos1 = PlotId.fromString(args[2]);
pos2 = PlotId.fromString(args[3]);
} catch (IllegalArgumentException ignored) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID);
return false;
}
// check if name is taken
String name = args[1];
if (area.getCluster(name) != null) {
MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN);
MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN);
return false;
}
if (pos2.x < pos1.x || pos2.y < pos1.y) {
@ -105,22 +111,23 @@ import java.util.UUID;
//check if overlap
PlotCluster cluster = area.getFirstIntersectingCluster(pos1, pos2);
if (cluster != null) {
MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, cluster.getName());
MainUtil.sendMessage(player, Captions.CLUSTER_INTERSECTION, cluster.getName());
return false;
}
// Check if it occupies existing plots
if (!area.contains(pos1) || !area.contains(pos2)) {
C.CLUSTER_OUTSIDE.send(player, area);
Captions.CLUSTER_OUTSIDE.send(player, area);
return false;
}
Set<Plot> plots = area.getPlotSelectionOwned(pos1, pos2);
if (!plots.isEmpty()) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_CREATE_OTHER)) {
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_CREATE_OTHER)) {
UUID uuid = player.getUUID();
for (Plot plot : plots) {
if (!plot.isOwner(uuid)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_CREATE_OTHER);
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_CREATE_OTHER);
return false;
}
}
@ -134,11 +141,12 @@ import java.util.UUID;
} else {
current = player.getPlayerClusterCount(player.getLocation().getWorld());
}
int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER_SIZE,
int allowed = Permissions
.hasPermissionRange(player, Captions.PERMISSION_CLUSTER_SIZE,
Settings.Limit.MAX_PLOTS);
if (current + cluster.getArea() > allowed) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea()));
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea()));
return false;
}
// create cluster
@ -148,72 +156,79 @@ import java.util.UUID;
// Add any existing plots to the current cluster
for (Plot plot : plots) {
if (plot.hasOwner()) {
if (!cluster.isAdded(plot.owner)) {
cluster.invited.add(plot.owner);
DBFunc.setInvited(cluster, plot.owner);
if (!cluster.isAdded(plot.getOwner())) {
cluster.invited.add(plot.getOwner());
DBFunc.setInvited(cluster, plot.getOwner());
}
}
}
MainUtil.sendMessage(player, C.CLUSTER_ADDED);
MainUtil.sendMessage(player, Captions.CLUSTER_ADDED);
return true;
}
case "disband":
case "del":
case "delete": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_DELETE)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_DELETE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_DELETE)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_DELETE);
return false;
}
if (args.length != 1 && args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster delete [name]");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster delete [name]");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster;
if (args.length == 2) {
cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]);
MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
}
if (!cluster.owner.equals(player.getUUID())) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_DELETE_OTHER)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_DELETE_OTHER);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_DELETE_OTHER)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_DELETE_OTHER);
return false;
}
}
DBFunc.delete(cluster);
MainUtil.sendMessage(player, C.CLUSTER_DELETED);
MainUtil.sendMessage(player, Captions.CLUSTER_DELETED);
return true;
}
case "res":
case "resize": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_RESIZE);
return false;
}
if (args.length != 3) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster resize <pos1> <pos2>");
return false;
}
PlotId pos1;
PlotId pos2;
// check pos1 / pos2
PlotId pos1 = PlotId.fromString(args[1]);
PlotId pos2 = PlotId.fromString(args[2]);
if (pos1 == null || pos2 == null) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID);
try {
pos1 = PlotId.fromString(args[2]);
pos2 = PlotId.fromString(args[3]);
} catch (IllegalArgumentException ignored) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID);
return false;
}
if (pos2.x < pos1.x || pos2.y < pos1.y) {
@ -223,29 +238,30 @@ import java.util.UUID;
// check if in cluster
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(player.getUUID())) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_OTHER)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_RESIZE_OTHER);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE_OTHER)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_RESIZE_OTHER);
return false;
}
}
//check if overlap
PlotCluster intersect = area.getFirstIntersectingCluster(pos1, pos2);
if (intersect != null) {
MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, intersect.getName());
MainUtil
.sendMessage(player, Captions.CLUSTER_INTERSECTION, intersect.getName());
return false;
}
Set<Plot> existing =
area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2());
Set<Plot> existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2());
Set<Plot> newPlots = area.getPlotSelectionOwned(pos1, pos2);
// Set<Plot> removed = (HashSet<Plot>) existing.clone();
Set<Plot> removed = new HashSet<>(existing);
@ -253,17 +269,19 @@ import java.util.UUID;
removed.removeAll(newPlots);
// Check expand / shrink
if (!removed.isEmpty()) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_SHRINK)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_RESIZE_SHRINK);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE_SHRINK)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_RESIZE_SHRINK);
return false;
}
}
newPlots.removeAll(existing);
if (!newPlots.isEmpty()) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_EXPAND)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_RESIZE_EXPAND);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE_EXPAND)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_RESIZE_EXPAND);
return false;
}
}
@ -275,50 +293,53 @@ import java.util.UUID;
current = player.getPlayerClusterCount(player.getLocation().getWorld());
}
current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y);
int allowed = Permissions
.hasPermissionRange(player, C.PERMISSION_CLUSTER, Settings.Limit.MAX_PLOTS);
int allowed = Permissions.hasPermissionRange(player, Captions.PERMISSION_CLUSTER,
Settings.Limit.MAX_PLOTS);
if (current + cluster.getArea() > allowed) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea()));
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea()));
return false;
}
// resize cluster
DBFunc.resizeCluster(cluster, pos1, pos2);
MainUtil.sendMessage(player, C.CLUSTER_RESIZED);
MainUtil.sendMessage(player, Captions.CLUSTER_RESIZED);
return true;
}
case "add":
case "inv":
case "invite": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INVITE)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_INVITE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_INVITE)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_INVITE);
return false;
}
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster invite <player>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster invite <player>");
return false;
}
// check if in cluster
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(player.getUUID())) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INVITE_OTHER)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_INVITE_OTHER);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_INVITE_OTHER)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_INVITE_OTHER);
return false;
}
}
// check uuid
UUID uuid = UUIDHandler.getUUID(args[1], null);
if (uuid == null) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, args[2]);
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[2]);
return false;
}
if (!cluster.isAdded(uuid)) {
@ -327,49 +348,52 @@ import java.util.UUID;
DBFunc.setInvited(cluster, uuid);
PlotPlayer player2 = UUIDHandler.getPlayer(uuid);
if (player2 != null) {
MainUtil.sendMessage(player2, C.CLUSTER_INVITED, cluster.getName());
MainUtil.sendMessage(player2, Captions.CLUSTER_INVITED, cluster.getName());
}
}
MainUtil.sendMessage(player, C.CLUSTER_ADDED_USER);
MainUtil.sendMessage(player, Captions.CLUSTER_ADDED_USER);
return true;
}
case "k":
case "remove":
case "kick": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_KICK)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_KICK)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_KICK);
return false;
}
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster kick <player>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster kick <player>");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(player.getUUID())) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_KICK_OTHER)) {
MainUtil
.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK_OTHER);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_KICK_OTHER)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_KICK_OTHER);
return false;
}
}
// check uuid
UUID uuid = UUIDHandler.getUUID(args[1], null);
if (uuid == null) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, args[1]);
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[1]);
return false;
}
// Can't kick if the player is yourself, the owner, or not added to the cluster
if (uuid.equals(player.getUUID()) || uuid.equals(cluster.owner) || !cluster
.isAdded(uuid)) {
MainUtil.sendMessage(player, C.CANNOT_KICK_PLAYER, cluster.getName());
MainUtil.sendMessage(player, Captions.CANNOT_KICK_PLAYER, cluster.getName());
return false;
}
if (cluster.helpers.contains(uuid)) {
@ -380,7 +404,7 @@ import java.util.UUID;
DBFunc.removeInvited(cluster, uuid);
PlotPlayer player2 = UUIDHandler.getPlayer(uuid);
if (player2 != null) {
MainUtil.sendMessage(player2, C.CLUSTER_REMOVED, cluster.getName());
MainUtil.sendMessage(player2, Captions.CLUSTER_REMOVED, cluster.getName());
}
for (Plot plot : new ArrayList<>(
PlotSquared.get().getPlots(player2.getLocation().getWorld(), uuid))) {
@ -389,44 +413,46 @@ import java.util.UUID;
plot.unclaim();
}
}
MainUtil.sendMessage(player2, C.CLUSTER_KICKED_USER);
MainUtil.sendMessage(player2, Captions.CLUSTER_KICKED_USER);
return true;
}
case "quit":
case "leave": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_LEAVE)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_LEAVE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_LEAVE)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_LEAVE);
return false;
}
if (args.length != 1 && args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster leave [name]");
MainUtil
.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster leave [name]");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
PlotCluster cluster;
if (args.length == 2) {
cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]);
MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
}
UUID uuid = player.getUUID();
if (!cluster.isAdded(uuid)) {
MainUtil.sendMessage(player, C.CLUSTER_NOT_ADDED);
MainUtil.sendMessage(player, Captions.CLUSTER_NOT_ADDED);
return false;
}
if (uuid.equals(cluster.owner)) {
MainUtil.sendMessage(player, C.CLUSTER_CANNOT_LEAVE);
MainUtil.sendMessage(player, Captions.CLUSTER_CANNOT_LEAVE);
return false;
}
if (cluster.helpers.contains(uuid)) {
@ -435,12 +461,11 @@ import java.util.UUID;
}
cluster.invited.remove(uuid);
DBFunc.removeInvited(cluster, uuid);
MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName());
MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED, cluster.getName());
for (Plot plot : new ArrayList<>(
PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) {
PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) {
player.getLocation().getWorld();
plot.unclaim();
}
}
@ -450,102 +475,107 @@ import java.util.UUID;
case "admin":
case "helper":
case "helpers": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_HELPERS)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_HELPERS);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_HELPERS)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_HELPERS);
return false;
}
if (args.length != 3) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster helpers <add|remove> <player>");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
UUID uuid = UUIDHandler.getUUID(args[2], null);
if (uuid == null) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, args[2]);
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[2]);
return false;
}
if (args[1].equalsIgnoreCase("add")) {
cluster.helpers.add(uuid);
DBFunc.setHelper(cluster, uuid);
return MainUtil.sendMessage(player, C.CLUSTER_ADDED_HELPER);
return MainUtil.sendMessage(player, Captions.CLUSTER_ADDED_HELPER);
}
if (args[1].equalsIgnoreCase("remove")) {
cluster.helpers.remove(uuid);
DBFunc.removeHelper(cluster, uuid);
return MainUtil.sendMessage(player, C.CLUSTER_REMOVED_HELPER);
return MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED_HELPER);
}
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot cluster helpers <add|remove> <player>");
return false;
}
case "spawn":
case "home":
case "tp": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_TP)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_TP)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_TP);
return false;
}
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster tp <name>");
MainUtil
.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster tp <name>");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
return false;
}
PlotCluster cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]);
MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]);
return false;
}
UUID uuid = player.getUUID();
if (!cluster.isAdded(uuid)) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_TP_OTHER)) {
MainUtil
.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP_OTHER);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_TP_OTHER)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_TP_OTHER);
return false;
}
}
player.teleport(cluster.getHome());
return MainUtil.sendMessage(player, C.CLUSTER_TELEPORTING);
return MainUtil.sendMessage(player, Captions.CLUSTER_TELEPORTING);
}
case "i":
case "info":
case "show":
case "information": {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INFO)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_INFO);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_INFO)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_INFO);
return false;
}
if (args.length != 1 && args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster info [name]");
MainUtil
.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster info [name]");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
PlotCluster cluster;
if (args.length == 2) {
cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]);
MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
}
@ -558,7 +588,7 @@ import java.util.UUID;
String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + (
cluster.getP2().y - cluster.getP1().y + 1);
String rights = cluster.isAdded(player.getUUID()) + "";
String message = C.CLUSTER_INFO.s();
String message = Captions.CLUSTER_INFO.s();
message = message.replaceAll("%id%", id);
message = message.replaceAll("%owner%", owner);
message = message.replaceAll("%name%", name);
@ -570,27 +600,29 @@ import java.util.UUID;
case "sh":
case "setspawn":
case "sethome":
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_SETHOME)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_SETHOME);
if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_SETHOME)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_SETHOME);
return false;
}
if (args.length != 1 && args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster sethome");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster sethome");
return false;
}
PlotArea area = player.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(player);
Captions.NOT_IN_PLOT_WORLD.send(player);
}
PlotCluster cluster = area.getCluster(player.getLocation());
if (cluster == null) {
MainUtil.sendMessage(player, C.NOT_IN_CLUSTER);
MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(player.getUUID())) {
if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_SETHOME_OTHER)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_CLUSTER_SETHOME_OTHER);
if (!Permissions
.hasPermission(player, Captions.PERMISSION_CLUSTER_SETHOME_OTHER)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_CLUSTER_SETHOME_OTHER);
return false;
}
}
@ -600,9 +632,9 @@ import java.util.UUID;
cluster.settings.setPosition(blockloc);
DBFunc.setPosition(cluster,
relative.getX() + "," + relative.getY() + "," + relative.getZ());
return MainUtil.sendMessage(player, C.POSITION_SET);
return MainUtil.sendMessage(player, Captions.POSITION_SET);
}
MainUtil.sendMessage(player, C.CLUSTER_AVAILABLE_ARGS);
MainUtil.sendMessage(player, Captions.CLUSTER_AVAILABLE_ARGS);
return false;
}
}

View File

@ -1,56 +1,58 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import lombok.RequiredArgsConstructor;
/**
* CommandCategory.
*/
public enum CommandCategory {
@RequiredArgsConstructor public enum CommandCategory {
/**
* Claiming CommandConfig.
* Such as: /plot claim
*/
CLAIMING("Claiming"), /**
CLAIMING(Captions.COMMAND_CATEGORY_CLAIMING),
/**
* Teleportation CommandConfig.
* Such as: /plot visit
*/
TELEPORT("Teleport"), /**
TELEPORT(Captions.COMMAND_CATEGORY_TELEPPORT),
/**
* Protection.
*/
SETTINGS("Protection"), /**
SETTINGS(Captions.COMMAND_CATEGORY_SETTINGS),
/**
* Chat.
*/
CHAT("Chat"), /**
CHAT(Captions.COMMAND_CATEGORY_CHAT),
/**
* Web.
*/
SCHEMATIC("Web"), /**
SCHEMATIC(Captions.COMMAND_CATEGORY_SCHEMATIC),
/**
* Cosmetic.
*/
APPEARANCE("Cosmetic"), /**
APPEARANCE(Captions.COMMAND_CATEGORY_APPEARANCE),
/**
* Information CommandConfig.
* Such as: /plot info
*/
INFO("Info"), /**
INFO(Captions.COMMAND_CATEGORY_INFO),
/**
* Debug CommandConfig.
* Such as: /plot debug
*/
DEBUG("Debug"), /**
DEBUG(Captions.COMMAND_CATEGORY_DEBUG),
/**
* Administration commands.
*/
ADMINISTRATION("Admin");
ADMINISTRATION(Captions.COMMAND_CATEGORY_ADMINISTRATION);
/**
* The category name (Readable).
*/
private final String name;
/**
* Constructor.
*
* @param name readable name
*/
CommandCategory(String name) {
this.name = name;
}
private final Captions caption;
@Override public String toString() {
return this.name;
return this.caption.s();
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
@ -17,23 +17,29 @@ import java.util.Arrays;
import java.util.Map.Entry;
@CommandDeclaration(command = "comment", aliases = {"msg"}, description = "Comment on a plot",
category = CommandCategory.CHAT, requiredType = RequiredType.NONE, permission = "plots.comment")
category = CommandCategory.CHAT, requiredType = RequiredType.PLAYER, permission = "plots.comment")
public class Comment extends SubCommand {
@Override public boolean onCommand(PlotPlayer player, String[] args) {
if (args.length < 2) {
sendMessage(player, C.COMMENT_SYNTAX,
sendMessage(player, Captions.COMMENT_SYNTAX,
StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase());
if (inbox == null) {
sendMessage(player, C.COMMENT_SYNTAX,
sendMessage(player, Captions.COMMENT_SYNTAX,
StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
Location loc = player.getLocation();
PlotId id = PlotId.fromString(args[1]);
PlotId id;
try {
id = PlotId.fromString(args[1]);
} catch (IllegalArgumentException ignored) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID);
return false;
}
Plot plot = MainUtil.getPlotFromString(player, args[1], false);
int index;
if (plot == null) {
@ -41,14 +47,14 @@ public class Comment extends SubCommand {
plot = loc.getPlotAbs();
} else {
if (args.length < 4) {
sendMessage(player, C.COMMENT_SYNTAX,
sendMessage(player, Captions.COMMENT_SYNTAX,
StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
index = 2;
}
if (!inbox.canWrite(plot, player)) {
sendMessage(player, C.NO_PERM_INBOX, "");
sendMessage(player, Captions.NO_PERM_INBOX, "");
return false;
}
String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " ");
@ -57,8 +63,8 @@ public class Comment extends SubCommand {
System.currentTimeMillis());
boolean result = inbox.addComment(plot, comment);
if (!result) {
sendMessage(player, C.NO_PLOT_INBOX, "");
sendMessage(player, C.COMMENT_SYNTAX,
sendMessage(player, Captions.NO_PLOT_INBOX, "");
sendMessage(player, Captions.COMMENT_SYNTAX,
StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
@ -68,7 +74,7 @@ public class Comment extends SubCommand {
MainUtil.sendMessage(pp, "/plot comment " + StringMan.join(args, " "));
}
}
sendMessage(player, C.COMMENT_ADDED);
sendMessage(player, Captions.COMMENT_ADDED);
return true;
}
}

View File

@ -11,7 +11,11 @@ import com.github.intellectualsites.plotsquared.plot.util.MathMan;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.WorldUtil;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
@ -104,6 +108,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
return false;
}
MainUtil.sendMessage(player, "TASK STARTED...");
Condense.TASK = true;
Runnable run = new Runnable() {
@Override public void run() {
if (!Condense.TASK) {
@ -126,14 +131,12 @@ import java.util.concurrent.atomic.AtomicBoolean;
}
i++;
final AtomicBoolean result = new AtomicBoolean(false);
result.set(origin.move(possible, new Runnable() {
@Override public void run() {
result.set(origin.move(possible, () -> {
if (result.get()) {
MainUtil.sendMessage(player,
"Moving: " + origin + " -> " + possible);
TaskManager.runTaskLater(task, 1);
}
}
}, false));
if (result.get()) {
break;
@ -149,7 +152,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
}
}
};
Condense.TASK = true;
TaskManager.runTaskAsync(run);
return true;
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.CmdInstance;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -16,13 +16,13 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
@Override public boolean onCommand(PlotPlayer player, String[] args) {
CmdInstance command = CmdConfirm.getPending(player);
if (command == null) {
MainUtil.sendMessage(player, C.FAILED_CONFIRM);
MainUtil.sendMessage(player, Captions.FAILED_CONFIRM);
return false;
}
CmdConfirm.removePending(player);
if ((System.currentTimeMillis() - command.timestamp)
> Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000) {
MainUtil.sendMessage(player, C.EXPIRED_CONFIRM);
MainUtil.sendMessage(player, Captions.EXPIRED_CONFIRM);
return false;
}
TaskManager.runTask(command.command);

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -17,29 +17,30 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions;
@Override public boolean onCommand(PlotPlayer player, String[] args) {
Plot plot = player.getCurrentPlot();
if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(player, C.NOT_IN_PLOT);
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot.isOwner(player.getUUID()) && !Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CONTINUE)) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_CONTINUE)) {
MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS);
return false;
}
if (!plot.hasFlag(Flags.DONE)) {
MainUtil.sendMessage(player, C.DONE_NOT_DONE);
MainUtil.sendMessage(player, Captions.DONE_NOT_DONE);
return false;
}
int size = plot.getConnectedPlots().size();
if (Settings.Done.COUNTS_TOWARDS_LIMIT && (player.getAllowedPlots()
< player.getPlotCount() + size)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND_CONTINUE);
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_ADMIN_COMMAND_CONTINUE);
return false;
}
if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
return false;
}
plot.removeFlag(Flags.DONE);
MainUtil.sendMessage(player, C.DONE_REMOVED);
MainUtil.sendMessage(player, Captions.DONE_REMOVED);
return true;
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@ -16,15 +16,15 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions;
Location loc = player.getLocation();
Plot plot1 = loc.getPlotAbs();
if (plot1 == null) {
return !MainUtil.sendMessage(player, C.NOT_IN_PLOT);
return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot1.isOwner(player.getUUID()) && !Permissions
.hasPermission(player, C.PERMISSION_ADMIN.s())) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
.hasPermission(player, Captions.PERMISSION_ADMIN.s())) {
MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS);
return false;
}
if (args.length != 1) {
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
return false;
}
Plot plot2 = MainUtil.getPlotFromString(player, args[0], true);
@ -32,22 +32,18 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions;
return false;
}
if (plot1.equals(plot2)) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID);
C.COMMAND_SYNTAX.send(player, getUsage());
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID);
Captions.COMMAND_SYNTAX.send(player, getUsage());
return false;
}
if (!plot1.getArea().isCompatible(plot2.getArea())) {
C.PLOTWORLD_INCOMPATIBLE.send(player);
Captions.PLOTWORLD_INCOMPATIBLE.send(player);
return false;
}
if (plot1.copy(plot2, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, C.COPY_SUCCESS);
}
})) {
if (plot1.copy(plot2, () -> MainUtil.sendMessage(player, Captions.COPY_SUCCESS))) {
return true;
} else {
MainUtil.sendMessage(player, C.REQUIRES_UNOWNED);
MainUtil.sendMessage(player, Captions.REQUIRES_UNOWNED);
return false;
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.object.Location;
@ -19,10 +19,10 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
Location loc = player.getLocation();
Plot plot = loc.getPlotAbs();
if (plot == null) {
return sendMessage(player, C.NOT_IN_PLOT);
return sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!(loc.getPlotArea() instanceof HybridPlotWorld)) {
return sendMessage(player, C.NOT_IN_PLOT_WORLD);
return sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
HybridUtils.manager.setupRoadSchematic(plot);
MainUtil.sendMessage(player,

View File

@ -30,26 +30,19 @@ import java.util.Map.Entry;
public static void insertPlots(final SQLManager manager, final List<Plot> plots,
final PlotPlayer player) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
TaskManager.runTaskAsync(() -> {
try {
ArrayList<Plot> ps = new ArrayList<>();
for (Plot p : plots) {
ps.add(p);
}
ArrayList<Plot> ps = new ArrayList<>(plots);
MainUtil.sendMessage(player, "&6Starting...");
manager.createPlotsAndData(ps, new Runnable() {
@Override public void run() {
manager.createPlotsAndData(ps, () -> {
MainUtil.sendMessage(player, "&6Database conversion finished!");
manager.close();
}
});
} catch (Exception e) {
MainUtil.sendMessage(player,
"Failed to insert plot objects, see stacktrace for info");
MainUtil
.sendMessage(player, "Failed to insert plot objects, see stacktrace for info");
e.printStackTrace();
}
}
});
}
@ -94,8 +87,8 @@ import java.util.Map.Entry;
HashMap<String, HashMap<PlotId, Plot>> map = manager.getPlots();
plots = new ArrayList<>();
for (Entry<String, HashMap<PlotId, Plot>> entry : map.entrySet()) {
String areaname = entry.getKey();
PlotArea pa = PlotSquared.get().getPlotAreaByString(areaname);
String areaName = entry.getKey();
PlotArea pa = PlotSquared.get().getPlotAreaByString(areaName);
if (pa != null) {
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
Plot plot = entry2.getValue();
@ -130,20 +123,13 @@ import java.util.Map.Entry;
plots.add(plot);
}
} else {
HashMap<PlotId, Plot> plotmap =
PlotSquared.get().plots_tmp.get(areaname);
if (plotmap == null) {
plotmap = new HashMap<>();
PlotSquared.get().plots_tmp.put(areaname, plotmap);
}
plotmap.putAll(entry.getValue());
HashMap<PlotId, Plot> plotMap = PlotSquared.get().plots_tmp
.computeIfAbsent(areaName, k -> new HashMap<>());
plotMap.putAll(entry.getValue());
}
}
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Database conversion finished!");
}
});
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&6Database conversion finished!"));
return true;
case "mysql":
if (args.length < 6) {

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
@ -14,23 +14,23 @@ public class Debug extends SubCommand {
@Override public boolean onCommand(PlotPlayer player, String[] args) {
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
StringBuilder msg = new StringBuilder();
for (C caption : C.values()) {
for (Captions caption : Captions.values()) {
msg.append(caption.s()).append("\n");
}
MainUtil.sendMessage(player, msg.toString());
return true;
}
StringBuilder information = new StringBuilder();
String header = C.DEBUG_HEADER.s();
String line = C.DEBUG_LINE.s();
String section = C.DEBUG_SECTION.s();
String header = Captions.DEBUG_HEADER.s();
String line = Captions.DEBUG_LINE.s();
String section = Captions.DEBUG_SECTION.s();
information.append(header);
information.append(getSection(section, "PlotArea"));
information.append(
getLine(line, "Plot Worlds", StringMan.join(PlotSquared.get().getPlotAreas(), ", ")));
information.append(getLine(line, "Owned Plots", PlotSquared.get().getPlots().size()));
information.append(getSection(section, "Messages"));
information.append(getLine(line, "Total Messages", C.values().length));
information.append(getLine(line, "Total Messages", Captions.values().length));
information.append(getLine(line, "View all captions", "/plot debug msg"));
MainUtil.sendMessage(player, information.toString());
return true;

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import java.util.ArrayList;
@ -19,10 +19,10 @@ import java.util.UUID;
if (unsafeAllowed.contains(player.getUUID())) {
unsafeAllowed.remove(player.getUUID());
sendMessage(player, C.DEBUGALLOWUNSAFE_OFF);
sendMessage(player, Captions.DEBUGALLOWUNSAFE_OFF);
} else {
unsafeAllowed.add(player.getUUID());
sendMessage(player, C.DEBUGALLOWUNSAFE_ON);
sendMessage(player, Captions.DEBUGALLOWUNSAFE_ON);
}
return true;
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
@ -29,7 +29,7 @@ public class DebugClaimTest extends SubCommand {
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
C.NOT_VALID_PLOT_WORLD.send(player, args[0]);
Captions.NOT_VALID_PLOT_WORLD.send(player, args[0]);
return false;
}
PlotId min, max;
@ -55,7 +55,7 @@ public class DebugClaimTest extends SubCommand {
MainUtil.sendMessage(player, " - &cDB Already contains: " + plot.getId());
continue;
}
Location loc = manager.getSignLoc(area, plot);
Location loc = manager.getSignLoc(plot);
ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);
boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false);
if (!result) {

View File

@ -3,7 +3,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Command;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
@ -17,12 +17,21 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager;
import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis;
import com.google.common.io.Files;
import javax.script.*;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@CommandDeclaration(command = "debugexec", permission = "plots.admin",
@ -32,6 +41,8 @@ import java.util.concurrent.CompletableFuture;
private Bindings scope;
public DebugExec() {
init();
/*
try {
if (PlotSquared.get() != null) {
File file = new File(PlotSquared.get().IMP.getDirectory(),
@ -50,6 +61,7 @@ import java.util.concurrent.CompletableFuture;
} catch (IOException | ScriptException ignored) {
ignored.printStackTrace();
}
*/
}
public ScriptEngine getEngine() {
@ -67,7 +79,15 @@ import java.util.concurrent.CompletableFuture;
if (this.engine != null) {
return;
}
this.engine = new ScriptEngineManager(null).getEngineByName("nashorn");
//create script engine manager
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
//create nashorn engine
this.engine = scriptEngineManager.getEngineByName("nashorn");
try {
engine.eval("print('PlotSquared Scripting Test');");
} catch (ScriptException e) {
e.printStackTrace();
}
if (this.engine == null) {
this.engine = new ScriptEngineManager(null).getEngineByName("JavaScript");
}
@ -97,7 +117,6 @@ import java.util.concurrent.CompletableFuture;
this.scope.put("WEManager", new WEManager());
}
this.scope.put("TaskManager", TaskManager.IMP);
this.scope.put("TitleManager", AbstractTitle.TITLE_CLASS);
this.scope.put("ConsolePlayer", ConsolePlayer.getConsole());
this.scope.put("SchematicHandler", SchematicHandler.manager);
this.scope.put("ChunkManager", ChunkManager.manager);
@ -112,7 +131,7 @@ import java.util.concurrent.CompletableFuture;
this.scope.put("MainCommand", MainCommand.getInstance());
// enums
for (Enum<?> value : C.values()) {
for (Enum<?> value : Captions.values()) {
this.scope.put("C_" + value.name(), value);
}
}
@ -130,7 +149,7 @@ import java.util.concurrent.CompletableFuture;
case "analyze": {
Plot plot = player.getCurrentPlot();
if (plot == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT);
MainUtil.sendMessage(player, Captions.NOT_IN_PLOT);
return false;
}
PlotAnalysis analysis = plot.getComplexity(null);
@ -149,7 +168,7 @@ import java.util.concurrent.CompletableFuture;
}
case "calibrate-analysis":
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot debugexec analyze <threshold>");
MainUtil.sendMessage(player,
"$1<threshold> $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating "
@ -165,8 +184,8 @@ import java.util.concurrent.CompletableFuture;
"$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100");
return false;
}
PlotAnalysis.calcOptimalModifiers(
() -> MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold);
PlotAnalysis.calcOptimalModifiers(() -> MainUtil
.sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold);
return true;
case "stop-expire":
if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) {
@ -175,7 +194,7 @@ import java.util.concurrent.CompletableFuture;
return MainUtil.sendMessage(player, "Cancelled task.");
case "remove-flag":
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX,
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot debugexec remove-flag <flag>");
return false;
}
@ -195,7 +214,7 @@ import java.util.concurrent.CompletableFuture;
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]);
if (area == null) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD, args[1]);
return false;
}
boolean result;
@ -275,7 +294,7 @@ import java.util.concurrent.CompletableFuture;
DebugExec.this.engine.eval(cmd, DebugExec.this.scope);
} catch (ScriptException e) {
e.printStackTrace();
MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG);
MainUtil.sendMessage(player, Captions.COMMAND_WENT_WRONG);
}
return CompletableFuture.completedFuture(true);
}
@ -283,8 +302,8 @@ import java.util.concurrent.CompletableFuture;
return true;
} catch (IOException e) {
e.printStackTrace();
MainUtil
.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd <file>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot debugexec addcmd <file>");
return false;
}
case "runasync":
@ -324,7 +343,8 @@ import java.util.concurrent.CompletableFuture;
break;
}
default:
C.COMMAND_SYNTAX.send(player, "/plot debugexec list-scripts [#]");
Captions.COMMAND_SYNTAX
.send(player, "/plot debugexec list-scripts [#]");
return false;
}
@ -341,7 +361,7 @@ import java.util.concurrent.CompletableFuture;
return true;
case "allcmd":
if (args.length < 3) {
C.COMMAND_SYNTAX
Captions.COMMAND_SYNTAX
.send(player, "/plot debugexec allcmd <condition> <command>");
return false;
}
@ -381,7 +401,8 @@ import java.util.concurrent.CompletableFuture;
break;
case "all":
if (args.length < 3) {
C.COMMAND_SYNTAX.send(player, "/plot debugexec all <condition> <code>");
Captions.COMMAND_SYNTAX
.send(player, "/plot debugexec all <condition> <code>");
return false;
}
script =
@ -394,7 +415,7 @@ import java.util.concurrent.CompletableFuture;
script = StringMan.join(args, " ");
}
if (!(player instanceof ConsolePlayer)) {
MainUtil.sendMessage(player, C.NOT_CONSOLE);
MainUtil.sendMessage(player, Captions.NOT_CONSOLE);
return false;
}
init();
@ -411,8 +432,8 @@ import java.util.concurrent.CompletableFuture;
} catch (ScriptException e) {
e.printStackTrace();
}
PlotSquared.log(
"> " + (System.currentTimeMillis() - start) + "ms -> " + result);
PlotSquared
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
});
} else {
long start = System.currentTimeMillis();

View File

@ -3,7 +3,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Argument;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -28,7 +28,7 @@ public class DebugFixFlags extends SubCommand {
@Override public boolean onCommand(PlotPlayer player, String[] args) {
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[0]);
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD, args[0]);
return false;
}
MainUtil.sendMessage(player, "&8--- &6Starting task &8 ---");

View File

@ -37,10 +37,20 @@ import java.util.concurrent.CompletableFuture;
SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea();
PlotId id = new PlotId(0, 0);
File container = PlotSquared.imp().getWorldContainer();
if (container.equals(new File("."))) {
player.sendMessage(
"World container must be configured to be a separate directory to your base files!");
return;
}
for (File folder : container.listFiles()) {
String name = folder.getName();
if (!WorldUtil.IMP.isWorld(name) && PlotId.fromString(name) == null) {
UUID uuid = UUIDHandler.getUUID(name, null);
if (!WorldUtil.IMP.isWorld(name) && PlotId.fromStringOrNull(name) == null) {
UUID uuid;
if (name.length() > 16) {
uuid = UUID.fromString(name);
} else {
uuid = UUIDHandler.getUUID(name, null);
}
if (uuid == null) {
uuid =
UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.IncendoPaster;
@ -18,25 +18,37 @@ import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@CommandDeclaration(command = "debugpaste", aliases = "dp", usage = "/plot debugpaste",
description = "Upload settings.yml, worlds.yml, PlotSquared.use_THIS.yml and your latest.log to https://incendo.org",
description = "Upload settings.yml, worlds.yml, PlotSquared.use_THIS.yml and your latest.log to https://athion.net/ISPaster/paste",
permission = "plots.debugpaste", category = CommandCategory.DEBUG) public class DebugPaste
extends SubCommand {
private static String readFile(@NonNull final File file) throws IOException {
final List<String> lines;
try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
lines = reader.lines().collect(Collectors.toList());
}
final StringBuilder content = new StringBuilder();
for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) {
content.append(lines.get(i)).append("\n");
}
return content.toString();
}
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
TaskManager.runTaskAsync(() -> {
try {
final IncendoPaster incendoPaster = new IncendoPaster("plotsquared");
StringBuilder b = new StringBuilder();
b.append(
"# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your "
+ "problem\n\n");
b.append("# Server Information\n");
b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation()).append("\n");
b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation())
.append("\n");
b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';')
.append(!Settings.UUID.OFFLINE).append('\n');
b.append("plugins:");
@ -55,40 +67,42 @@ import java.util.List;
b.append("memory.max: ").append(runtime.maxMemory()).append('\n');
b.append("java.specification.version: '")
.append(System.getProperty("java.specification.version")).append("'\n");
b.append("java.vendor: '").append(System.getProperty("java.vendor"))
.append("'\n");
b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n");
b.append("java.version: '").append(System.getProperty("java.version"))
.append("'\n");
b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n");
b.append("os.name: '").append(System.getProperty("os.name")).append("'\n");
b.append("os.version: '").append(System.getProperty("os.version"))
.append("'\n\n");
b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n");
b.append("# Okay :D Great. You are now ready to create your bug report!");
b.append(
"\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues");
b.append("\n# or via our Discord at https://discord.gg/ngZCzbU");
final IncendoPaster incendoPaster = new IncendoPaster("plotsquared");
incendoPaster.addFile(new IncendoPaster.PasteFile("information", b.toString()));
try {
final File logFile = new File(PlotSquared.get().IMP.getDirectory(),
"../../logs/latest.log");
final File logFile =
new File(PlotSquared.get().IMP.getDirectory(), "../../logs/latest.log");
if (Files.size(logFile.toPath()) > 14_000_000) {
throw new IOException("Too big...");
}
incendoPaster.addFile(new IncendoPaster.PasteFile("latest.log", readFile(logFile)));
incendoPaster
.addFile(new IncendoPaster.PasteFile("latest.log", readFile(logFile)));
} catch (IOException ignored) {
MainUtil.sendMessage(player,
"&clatest.log is too big to be pasted, will ignore");
MainUtil
.sendMessage(player, "&clatest.log is too big to be pasted, will ignore");
}
try {
incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml", readFile(PlotSquared.get().configFile)));
incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml",
readFile(PlotSquared.get().configFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping settings.yml because it's empty");
}
try {
incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml", readFile(PlotSquared.get().worldsFile)));
incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml",
readFile(PlotSquared.get().worldsFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping worlds.yml because it's empty");
}
@ -96,25 +110,30 @@ import java.util.List;
incendoPaster.addFile(new IncendoPaster.PasteFile("PlotSquared.use_THIS.yml",
readFile(PlotSquared.get().translationFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping PlotSquared.use_THIS.yml because it's empty");
MainUtil.sendMessage(player,
"&cSkipping PlotSquared.use_THIS.yml because it's empty");
}
try {
final String rawResponse = incendoPaster.upload();
final JsonObject jsonObject = new JsonParser().parse(rawResponse).getAsJsonObject();
final JsonObject jsonObject =
new JsonParser().parse(rawResponse).getAsJsonObject();
if (jsonObject.has("created")) {
final String pasteId = jsonObject.get("paste_id").getAsString();
final String link = String.format("https://incendo.org/paste/view/%s", pasteId);
player.sendMessage(
C.DEBUG_REPORT_CREATED.s().replace("%url%", link));
final String link =
String.format("https://athion.net/ISPaster/paste/view/%s", pasteId);
player
.sendMessage(Captions.DEBUG_REPORT_CREATED.s().replace("%url%", link));
} else {
final String responseMessage = jsonObject.get("response").getAsString();
MainUtil.sendMessage(player, String.format("&cFailed to create the debug paste: %s", responseMessage));
MainUtil.sendMessage(player, String
.format("&cFailed to create the debug paste: %s", responseMessage));
}
} catch (final Throwable throwable) {
throwable.printStackTrace();
MainUtil.sendMessage(player, "&cFailed to create the debug paste: " + throwable.getMessage());
MainUtil.sendMessage(player,
"&cFailed to create the debug paste: " + throwable.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
@ -122,19 +141,4 @@ import java.util.List;
});
return true;
}
private static String readFile(@NonNull final File file) throws IOException {
final StringBuilder content = new StringBuilder();
final List<String> lines = new ArrayList<>();
try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) {
content.append(lines.get(i)).append("\n");
}
return content.toString();
}
}

View File

@ -1,41 +1,109 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotManager;
import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotManager;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
@CommandDeclaration(command = "debugroadregen", usage = "/plot debugroadregen",
import java.util.Arrays;
@CommandDeclaration(command = "debugroadregen", usage = DebugRoadRegen.USAGE,
requiredType = RequiredType.NONE,
description = "Regenerate all roads based on the road schematic",
description = "Regenerate roads in the plot or region the user is, based on the road schematic",
category = CommandCategory.DEBUG, permission = "plots.debugroadregen")
public class DebugRoadRegen extends SubCommand {
public static final String USAGE = "/plot debugroadregen <plot|region [height]>";
@Override public boolean onCommand(PlotPlayer player, String[] args) {
if (args.length < 1) {
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
DebugRoadRegen.USAGE);
return false;
}
String kind = args[0].toLowerCase();
switch (kind) {
case "plot":
return regenPlot(player);
case "region":
return regenRegion(player, Arrays.copyOfRange(args, 1, args.length));
default:
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
DebugRoadRegen.USAGE);
return false;
}
}
public boolean regenPlot(PlotPlayer player) {
Location loc = player.getLocation();
PlotArea plotArea = loc.getPlotArea();
if (!(plotArea instanceof HybridPlotWorld)) {
return sendMessage(player, C.NOT_IN_PLOT_WORLD);
PlotArea area = loc.getPlotArea();
if (area == null) {
return sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
Plot plot = player.getCurrentPlot();
if (plot == null) {
C.NOT_IN_PLOT.send(player);
Captions.NOT_IN_PLOT.send(player);
} else if (plot.isMerged()) {
C.REQUIRES_UNMERGED.send(player);
Captions.REQUIRES_UNMERGED.send(player);
} else {
HybridPlotManager manager = (HybridPlotManager) plotArea.getPlotManager();
manager.createRoadEast(plotArea, plot);
manager.createRoadSouth(plotArea, plot);
manager.createRoadSouthEast(plotArea, plot);
PlotManager manager = area.getPlotManager();
manager.createRoadEast(plot);
manager.createRoadSouth(plot);
manager.createRoadSouthEast(plot);
MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId()
+ "\n&6 - Result: &aSuccess");
MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads");
}
return true;
}
public boolean regenRegion(PlotPlayer player, String[] args) {
int height = 0;
if (args.length == 1) {
try {
height = Integer.parseInt(args[0]);
} catch (NumberFormatException ignored) {
MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, "(0, 256)");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
DebugRoadRegen.USAGE);
return false;
}
} else if (args.length != 0) {
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
DebugRoadRegen.USAGE);
return false;
}
Location loc = player.getLocation();
PlotArea area = loc.getPlotArea();
if (area == null) {
return sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
Plot plot = player.getCurrentPlot();
PlotManager manager = area.getPlotManager();
if (!(manager instanceof HybridPlotManager)) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD);
return true;
}
MainUtil
.sendMessage(player, "&cIf no schematic is set, the following will not do anything");
MainUtil.sendMessage(player,
"&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic");
MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads");
boolean result = HybridUtils.manager.scheduleSingleRegionRoadUpdate(plot, height);
if (!result) {
MainUtil.sendMessage(player,
"&cCannot schedule mass schematic update! (Is one already in progress?)");
return false;
}
return true;
}
}

View File

@ -16,14 +16,10 @@ import java.util.ArrayList;
public class DebugSaveTest extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotSquared.get().getPlots());
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots());
MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Database sync finished!");
}
});
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&6Database sync finished!"));
return true;
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.*;
@ -16,18 +16,17 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
// The syntax also works with any command: /plot <plot> <command>
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
Location loc = player.getLocation();
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(player, C.NOT_IN_PLOT);
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot.hasOwner()) {
return !sendMessage(player, C.PLOT_UNOWNED);
return !sendMessage(player, Captions.PLOT_UNOWNED);
}
if (!plot.isOwner(player.getUUID()) && !Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DELETE)) {
return !sendMessage(player, C.NO_PLOT_PERMS);
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DELETE)) {
return !sendMessage(player, Captions.NO_PLOT_PERMS);
}
final PlotArea plotArea = plot.getArea();
final java.util.Set<Plot> plots = plot.getConnectedPlots();
@ -36,7 +35,7 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
Runnable run = new Runnable() {
@Override public void run() {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
return;
}
final long start = System.currentTimeMillis();
@ -48,17 +47,17 @@ import com.github.intellectualsites.plotsquared.plot.util.*;
double value = plots.size() * valueExr.evaluate((double) currentPlots);
if (value > 0d) {
EconHandler.manager.depositMoney(player, value);
sendMessage(player, C.ADDED_BALANCE, String.valueOf(value));
sendMessage(player, Captions.ADDED_BALANCE, String.valueOf(value));
}
}
MainUtil.sendMessage(player, C.DELETING_DONE,
MainUtil.sendMessage(player, Captions.DELETING_DONE,
System.currentTimeMillis() - start);
}
});
if (result) {
plot.addRunning();
} else {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
}
}
};

View File

@ -3,20 +3,24 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Argument;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.github.intellectualsites.plotsquared.plot.util.PlotGameMode;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.plot.util.WorldUtil;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
@CommandDeclaration(command = "deny", aliases = {"d", "ban"},
description = "Deny a user from a plot", usage = "/plot deny <player>",
category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Deny
category = CommandCategory.SETTINGS, requiredType = RequiredType.PLAYER) public class Deny
extends SubCommand {
public Deny() {
@ -28,38 +32,36 @@ import java.util.UUID;
Location location = player.getLocation();
Plot plot = location.getPlotAbs();
if (plot == null) {
return !sendMessage(player, C.NOT_IN_PLOT);
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot.hasOwner()) {
MainUtil.sendMessage(player, C.PLOT_UNOWNED);
MainUtil.sendMessage(player, Captions.PLOT_UNOWNED);
return false;
}
if (!plot.isOwner(player.getUUID()) && !Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY)) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY)) {
MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS);
return true;
}
Set<UUID> uuids = MainUtil.getUUIDsFromString(args[0]);
if (uuids.isEmpty()) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]);
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]);
return false;
}
Iterator<UUID> iter = uuids.iterator();
while (iter.hasNext()) {
UUID uuid = iter.next();
for (UUID uuid : uuids) {
if (uuid == DBFunc.EVERYONE && !(
Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, MainUtil.getName(uuid));
Permissions.hasPermission(player, Captions.PERMISSION_DENY_EVERYONE) || Permissions
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY))) {
MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid));
continue;
}
if (plot.isOwner(uuid)) {
MainUtil.sendMessage(player, C.ALREADY_OWNER, MainUtil.getName(uuid));
MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid));
return false;
}
if (plot.getDenied().contains(uuid)) {
MainUtil.sendMessage(player, C.ALREADY_ADDED, MainUtil.getName(uuid));
MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid));
return false;
}
if (uuid != DBFunc.EVERYONE) {
@ -77,7 +79,7 @@ import java.util.UUID;
}
}
if (!uuids.isEmpty()) {
MainUtil.sendMessage(player, C.DENIED_ADDED);
MainUtil.sendMessage(player, Captions.DENIED_ADDED);
}
return true;
}
@ -97,13 +99,13 @@ import java.util.UUID;
}
Location loc = player.getLocation();
Location spawn = WorldUtil.IMP.getSpawn(loc.getWorld());
MainUtil.sendMessage(player, C.YOU_GOT_DENIED);
MainUtil.sendMessage(player, Captions.YOU_GOT_DENIED);
if (plot.equals(spawn.getPlot())) {
Location newSpawn =
WorldUtil.IMP.getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]);
if (plot.equals(newSpawn.getPlot())) {
// Kick from server if you can't be teleported to spawn
player.kick(C.YOU_GOT_DENIED.s());
player.kick(Captions.YOU_GOT_DENIED.s());
} else {
player.teleport(newSpawn);
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.flag.FlagManager;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -11,20 +11,20 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
@CommandDeclaration(command = "setdescription", permission = "plots.set.desc",
description = "Set the plot description", usage = "/plot desc <description>",
aliases = {"desc", "setdesc", "setd", "description"}, category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE) public class Desc extends SetCommand {
requiredType = RequiredType.PLAYER) public class Desc extends SetCommand {
@Override public boolean set(PlotPlayer player, Plot plot, String desc) {
if (desc.isEmpty()) {
plot.removeFlag(Flags.DESCRIPTION);
MainUtil.sendMessage(player, C.DESC_UNSET);
MainUtil.sendMessage(player, Captions.DESC_UNSET);
return true;
}
boolean result = FlagManager.addPlotFlag(plot, Flags.DESCRIPTION, desc);
if (!result) {
MainUtil.sendMessage(player, C.FLAG_NOT_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED);
return false;
}
MainUtil.sendMessage(player, C.DESC_SET);
MainUtil.sendMessage(player, Captions.DESC_SET);
return true;
}
}

View File

@ -0,0 +1,15 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@CommandDeclaration(command = "dislike", permission = "plots.dislike",
description = "Dislike the plot", usage = "/plot dislike [next|purge]",
category = CommandCategory.INFO, requiredType = RequiredType.PLAYER) public class Dislike
extends SubCommand {
@Override public boolean onCommand(PlotPlayer player, String[] args) {
return Like.handleLike(player, args, false);
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
@ -22,23 +22,23 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis;
Location loc = player.getLocation();
final Plot plot = loc.getPlotAbs();
if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(player, C.NOT_IN_PLOT);
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot.isOwner(player.getUUID()) && !Permissions
.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DONE)) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DONE)) {
MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS);
return false;
}
if (plot.hasFlag(Flags.DONE)) {
MainUtil.sendMessage(player, C.DONE_ALREADY_DONE);
MainUtil.sendMessage(player, Captions.DONE_ALREADY_DONE);
return false;
}
if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
return false;
}
plot.addRunning();
MainUtil.sendMessage(player, C.GENERATING_LINK);
MainUtil.sendMessage(player, Captions.GENERATING_LINK);
final Settings.Auto_Clear doneRequirements = Settings.AUTO_CLEAR.get("done");
if (ExpireManager.IMP == null || doneRequirements == null) {
finish(plot, player, true);
@ -60,9 +60,9 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis;
if (success) {
long flagValue = System.currentTimeMillis() / 1000;
plot.setFlag(Flags.DONE, flagValue);
MainUtil.sendMessage(pp, C.DONE_SUCCESS);
MainUtil.sendMessage(pp, Captions.DONE_SUCCESS);
} else {
MainUtil.sendMessage(pp, C.DONE_INSUFFICIENT_COMPLEXITY);
MainUtil.sendMessage(pp, Captions.DONE_INSUFFICIENT_COMPLEXITY);
}
}
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
@ -21,34 +21,34 @@ import java.net.URL;
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
String world = player.getLocation().getWorld();
if (!PlotSquared.get().hasPlotArea(world)) {
return !sendMessage(player, C.NOT_IN_PLOT_WORLD);
return !sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
final Plot plot = player.getCurrentPlot();
if (plot == null) {
return !sendMessage(player, C.NOT_IN_PLOT);
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
if (!plot.hasOwner()) {
MainUtil.sendMessage(player, C.PLOT_UNOWNED);
MainUtil.sendMessage(player, Captions.PLOT_UNOWNED);
return false;
}
if ((Settings.Done.REQUIRED_FOR_DOWNLOAD && (!plot.getFlag(Flags.DONE).isPresent()))
&& !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) {
MainUtil.sendMessage(player, C.DONE_NOT_DONE);
&& !Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) {
MainUtil.sendMessage(player, Captions.DONE_NOT_DONE);
return false;
}
if ((!plot.isOwner(player.getUUID())) && !Permissions
.hasPermission(player, C.PERMISSION_ADMIN.s())) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
.hasPermission(player, Captions.PERMISSION_ADMIN.s())) {
MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS);
return false;
}
if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
return false;
}
if (args.length == 0 || (args.length == 1 && StringMan
.isEqualIgnoreCaseToAny(args[0], "sch", "schem", "schematic"))) {
if (plot.getVolume() > Integer.MAX_VALUE) {
C.SCHEMATIC_TOO_LARGE.send(player);
Captions.SCHEMATIC_TOO_LARGE.send(player);
return false;
}
plot.addRunning();
@ -58,7 +58,7 @@ import java.net.URL;
SchematicHandler.manager.upload(value, null, null, new RunnableVal<URL>() {
@Override public void run(URL url) {
if (url == null) {
MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED);
MainUtil.sendMessage(player, Captions.GENERATING_LINK_FAILED);
return;
}
MainUtil.sendMessage(player, url.toString());
@ -68,8 +68,8 @@ import java.net.URL;
});
} else if (args.length == 1 && StringMan
.isEqualIgnoreCaseToAny(args[0], "mcr", "world", "mca")) {
if (!Permissions.hasPermission(player, C.PERMISSION_DOWNLOAD_WORLD)) {
C.NO_PERMISSION.send(player, C.PERMISSION_DOWNLOAD_WORLD);
if (!Permissions.hasPermission(player, Captions.PERMISSION_DOWNLOAD_WORLD)) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_DOWNLOAD_WORLD);
return false;
}
MainUtil.sendMessage(player, "&cNote: The `.mca` files are 512x512");
@ -79,17 +79,17 @@ import java.net.URL;
@Override public void run(URL url) {
plot.removeRunning();
if (url == null) {
MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED);
MainUtil.sendMessage(player, Captions.GENERATING_LINK_FAILED);
return;
}
MainUtil.sendMessage(player, url.toString());
}
});
} else {
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
return false;
}
MainUtil.sendMessage(player, C.GENERATING_LINK);
MainUtil.sendMessage(player, Captions.GENERATING_LINK);
return true;
}
}

View File

@ -2,14 +2,25 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
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.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.flag.*;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.flag.FlagManager;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.flag.IntegerFlag;
import com.github.intellectualsites.plotsquared.plot.flag.ListFlag;
import com.github.intellectualsites.plotsquared.plot.flag.PlotBlockListFlag;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.MathMan;
import com.github.intellectualsites.plotsquared.plot.util.Permissions;
import com.github.intellectualsites.plotsquared.plot.util.PlotWeather;
import com.github.intellectualsites.plotsquared.plot.util.StringComparison;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import java.util.*;
@ -21,7 +32,8 @@ import java.util.*;
private boolean checkPermValue(PlotPlayer player, Flag flag, String key, String value) {
key = key.toLowerCase();
value = value.toLowerCase();
String perm = C.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase());
String perm =
Captions.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase());
if (flag instanceof IntegerFlag && MathMan.isInteger(value)) {
try {
int numeric = Integer.parseInt(value);
@ -30,13 +42,39 @@ import java.util.*;
int checkRange = PlotSquared.get().getPlatform().equalsIgnoreCase("bukkit") ?
numeric :
Settings.Limit.MAX_PLOTS;
return player.hasPermissionRange(perm, checkRange) >= numeric;
final boolean result = player.hasPermissionRange(perm, checkRange) >= numeric;
if (!result) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), value.toLowerCase()));
}
return result;
}
} catch (NumberFormatException ignore) {
}
} else if (flag instanceof PlotBlockListFlag) {
final PlotBlockListFlag blockListFlag = (PlotBlockListFlag) flag;
final HashSet<PlotBlock> parsedBlocks = blockListFlag.parseValue(value);
for (final PlotBlock block : parsedBlocks) {
final String permission = Captions.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), block.getRawId().toString().toLowerCase());
final boolean result = Permissions.hasPermission(player, permission);
if (!result) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_SET_FLAG_KEY_VALUE
.f(key.toLowerCase(), value.toLowerCase()));
return false;
}
return Permissions.hasPermission(player, perm);
}
return true;
}
final boolean result = Permissions.hasPermission(player, perm);
if (!result) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase()));
}
return result;
}
@Override public boolean onCommand(PlotPlayer player, String[] args) {
@ -49,22 +87,24 @@ import java.util.*;
* plot flag list
*/
if (args.length == 0) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot flag <set|remove|add|list|info>");
return false;
}
Location loc = player.getLocation();
Plot plot = loc.getPlotAbs();
if (plot == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT);
MainUtil.sendMessage(player, Captions.NOT_IN_PLOT);
return false;
}
if (!plot.hasOwner()) {
sendMessage(player, C.PLOT_NOT_CLAIMED);
sendMessage(player, Captions.PLOT_NOT_CLAIMED);
return false;
}
if (!plot.isOwner(player.getUUID()) && !Permissions
.hasPermission(player, C.PERMISSION_SET_FLAG_OTHER)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_OTHER);
.hasPermission(player, Captions.PERMISSION_SET_FLAG_OTHER)) {
MainUtil
.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_SET_FLAG_OTHER);
return false;
}
Flag<?> flag = null;
@ -77,47 +117,47 @@ import java.util.*;
new StringComparison<>(args[1], Flags.getFlags());
String best = stringComparison.getBestMatch();
if (best != null) {
MainUtil.sendMessage(player, C.NOT_VALID_FLAG_SUGGESTED, best);
MainUtil.sendMessage(player, Captions.NOT_VALID_FLAG_SUGGESTED, best);
suggested = true;
}
} catch (final Exception ignored) { /* Happens sometimes because of mean code */ }
if (!suggested) {
MainUtil.sendMessage(player, C.NOT_VALID_FLAG);
MainUtil.sendMessage(player, Captions.NOT_VALID_FLAG);
}
return false;
}
}
switch (args[0].toLowerCase()) {
case "info": {
if (!Permissions.hasPermission(player, C.PERMISSION_SET_FLAG)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.info");
if (!Permissions.hasPermission(player, Captions.PERMISSION_SET_FLAG)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION, "plots.flag.info");
return false;
}
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info <flag>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag info <flag>");
return false;
}
// flag key
MainUtil.sendMessage(player, C.FLAG_KEY, flag.getName());
MainUtil.sendMessage(player, Captions.FLAG_KEY, flag.getName());
// flag type
MainUtil.sendMessage(player, C.FLAG_TYPE, flag.getClass().getSimpleName());
MainUtil.sendMessage(player, Captions.FLAG_TYPE, flag.getClass().getSimpleName());
// Flag type description
MainUtil.sendMessage(player, C.FLAG_DESC, flag.getValueDescription());
MainUtil.sendMessage(player, Captions.FLAG_DESC, flag.getValueDescription());
return true;
}
case "set": {
if (!Permissions.hasPermission(player, C.PERMISSION_SET_FLAG)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG);
if (!Permissions.hasPermission(player, Captions.PERMISSION_SET_FLAG)) {
MainUtil
.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_SET_FLAG);
return false;
}
if (args.length < 3) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag set <flag> <value>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot flag set <flag> <value>");
return false;
}
String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ");
if (!checkPermValue(player, flag, args[1], value)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE
.f(args[1].toLowerCase(), value.toLowerCase()));
return false;
}
Object parsed = flag.parseValue(value);
@ -127,33 +167,32 @@ import java.util.*;
}
boolean result = plot.setFlag(flag, parsed);
if (!result) {
MainUtil.sendMessage(player, C.FLAG_NOT_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED);
return false;
}
MainUtil.sendMessage(player, C.FLAG_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_ADDED);
return true;
}
case "remove": {
if (!Permissions.hasPermission(player, C.PERMISSION_FLAG_REMOVE)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_FLAG_REMOVE);
if (!Permissions.hasPermission(player, Captions.PERMISSION_FLAG_REMOVE)) {
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_FLAG_REMOVE);
return false;
}
if (args.length != 2 && args.length != 3) {
MainUtil
.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove <flag> [values]");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot flag remove <flag> [values]");
return false;
}
if (!Permissions
.hasPermission(player, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) {
if (!Permissions.hasPermission(player,
Captions.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) {
if (args.length != 3) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()));
MainUtil.sendMessage(player, Captions.NO_PERMISSION,
Captions.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()));
return false;
}
for (String entry : args[2].split(",")) {
if (!checkPermValue(player, flag, args[1], entry)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry));
return false;
}
}
@ -165,9 +204,19 @@ import java.util.*;
if (flag1.isPresent()) {
boolean o = flag1.get().removeAll((Collection) flag.parseValue(value));
if (o) {
MainUtil.sendMessage(player, C.FLAG_REMOVED);
if (flag1.get().isEmpty()) {
final boolean result = plot.removeFlag(flag);
if (result) {
MainUtil.sendMessage(player, Captions.FLAG_REMOVED);
} else {
MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED);
MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED);
}
return true;
} else {
MainUtil.sendMessage(player, Captions.FLAG_REMOVED);
}
} else {
MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED);
return false;
}
}
@ -176,7 +225,7 @@ import java.util.*;
} else {
boolean result = plot.removeFlag(flag);
if (!result) {
MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED);
MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED);
return false;
}
}
@ -185,23 +234,22 @@ import java.util.*;
} else if (flag == Flags.WEATHER) {
player.setWeather(PlotWeather.RESET);
}
MainUtil.sendMessage(player, C.FLAG_REMOVED);
MainUtil.sendMessage(player, Captions.FLAG_REMOVED);
return true;
}
case "add":
if (!Permissions.hasPermission(player, C.PERMISSION_FLAG_ADD)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_FLAG_ADD);
if (!Permissions.hasPermission(player, Captions.PERMISSION_FLAG_ADD)) {
MainUtil
.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_FLAG_ADD);
return false;
}
if (args.length < 3) {
MainUtil
.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add <flag> <values>");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX,
"/plot flag add <flag> <values>");
return false;
}
for (String entry : args[2].split(",")) {
if (!checkPermValue(player, flag, args[1], entry)) {
MainUtil.sendMessage(player, C.NO_PERMISSION,
C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry));
return false;
}
}
@ -218,51 +266,52 @@ import java.util.*;
if (flag1.isPresent()) {
boolean o = flag1.get().addAll((Collection) parsed);
if (o) {
MainUtil.sendMessage(player, C.FLAG_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_ADDED);
val = flag1.get();
} else {
MainUtil.sendMessage(player, C.FLAG_NOT_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED);
return false;
}
}
}
boolean result = plot.setFlag(flag, val);
if (!result) {
MainUtil.sendMessage(player, C.FLAG_NOT_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED);
return false;
}
MainUtil.sendMessage(player, C.FLAG_ADDED);
MainUtil.sendMessage(player, Captions.FLAG_ADDED);
return true;
case "list":
if (!Permissions.hasPermission(player, C.PERMISSION_FLAG_LIST)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_FLAG_LIST);
if (!Permissions.hasPermission(player, Captions.PERMISSION_FLAG_LIST)) {
MainUtil
.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_FLAG_LIST);
return false;
}
if (args.length > 1) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag list");
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag list");
return false;
}
HashMap<String, ArrayList<String>> flags = new HashMap<>();
for (Flag<?> flag1 : Flags.getFlags()) {
String type = flag1.getClass().getSimpleName();
if (!flags.containsKey(type)) {
flags.put(type, new ArrayList<String>());
}
flags.computeIfAbsent(type, k -> new ArrayList<>());
flags.get(type).add(flag1.getName());
}
String message = "";
StringBuilder message = new StringBuilder();
String prefix = "";
for (Map.Entry<String, ArrayList<String>> entry : flags.entrySet()) {
String category = entry.getKey();
List<String> flagNames = entry.getValue();
Collections.sort(flagNames);
message += prefix + "&6" + category + ": &7" + StringMan.join(flagNames, ", ");
message.append(prefix).append("&6").append(category).append(": &7")
.append(StringMan.join(flagNames, ", "));
prefix = "\n";
}
MainUtil.sendMessage(player, message);
MainUtil.sendMessage(player, message.toString());
return true;
}
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>");
MainUtil
.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>");
return false;
}
}

View File

@ -1,7 +1,7 @@
package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Command;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import java.io.File;
@ -142,7 +142,7 @@ public class GenerateDocs {
Matcher m2 = p2.matcher(line);
while (m2.find()) {
perms.add(C.valueOf("PERMISSION_" + m2.group(1)).s());
perms.add(Captions.valueOf("PERMISSION_" + m2.group(1)).s());
}
if (line.contains("Permissions.hasPermission(")) {
String[] split = line.split("Permissions.hasPermission");
@ -151,7 +151,7 @@ public class GenerateDocs {
String perm = method.split("[,|)]")[1].trim();
if (!perm.equalsIgnoreCase(perm)) {
if (perm.startsWith("C.")) {
perm = C.valueOf(perm.split("\\.")[1]).s();
perm = Captions.valueOf(perm.split("\\.")[1]).s();
} else {
continue;
}
@ -181,7 +181,7 @@ public class GenerateDocs {
String perm = method.split("[,|)]")[1].trim();
if (!perm.equalsIgnoreCase(perm)) {
if (perm.startsWith("C.")) {
perm = C.valueOf(perm.split("\\.")[1]).s();
perm = Captions.valueOf(perm.split("\\.")[1]).s();
} else {
continue;
}

View File

@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.plot.commands;
import com.github.intellectualsites.plotsquared.commands.Command;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
@ -27,33 +27,45 @@ import java.util.concurrent.CompletableFuture;
@Override public CompletableFuture<Boolean> execute(final PlotPlayer player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
checkTrue(args.length >= 1 && args.length <= 2, C.COMMAND_SYNTAX, getUsage());
checkTrue(args.length >= 1 && args.length <= 2, Captions.COMMAND_SYNTAX, getUsage());
final String arg0 = args[0].toLowerCase();
switch (arg0) {
case "add":
case "check":
if (!Permissions.hasPermission(player, C.PERMISSION_GRANT.f(arg0))) {
C.NO_PERMISSION.send(player, C.PERMISSION_GRANT.f(arg0));
if (!Permissions.hasPermission(player, Captions.PERMISSION_GRANT.f(arg0))) {
Captions.NO_PERMISSION.send(player, Captions.PERMISSION_GRANT.f(arg0));
return CompletableFuture.completedFuture(false);
}
if (args.length > 2) {
break;
}
final UUID uuid =
args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : player.getUUID();
final UUID uuid;
if (args.length == 2) {
uuid = UUIDHandler.getUUIDFromString(args[1]);
} else {
uuid = player.getUUID();
}
if (uuid == null) {
C.INVALID_PLAYER.send(player, args[1]);
Captions.INVALID_PLAYER.send(player, args[1]);
return CompletableFuture.completedFuture(false);
}
MainUtil.getPersistentMeta(uuid, "grantedPlots", new RunnableVal<byte[]>() {
@Override public void run(byte[] array) {
if (arg0.equals("check")) { // check
int granted =
array == null ? 0 : ByteArrayUtilities.bytesToInteger(array);
C.GRANTED_PLOTS.send(player, granted);
int granted;
if (array == null) {
granted = 0;
} else {
granted = ByteArrayUtilities.bytesToInteger(array);
}
Captions.GRANTED_PLOTS.send(player, granted);
} else { // add
int amount =
1 + (array == null ? 0 : ByteArrayUtilities.bytesToInteger(array));
int amount;
if (array == null) {
amount = 1;
} else {
amount = 1 + ByteArrayUtilities.bytesToInteger(array);
}
boolean replace = array != null;
String key = "grantedPlots";
byte[] rawData = ByteArrayUtilities.integerToBytes(amount);
@ -68,7 +80,7 @@ import java.util.concurrent.CompletableFuture;
});
return CompletableFuture.completedFuture(true);
}
C.COMMAND_SYNTAX.send(player, getUsage());
Captions.COMMAND_SYNTAX.send(player, getUsage());
return CompletableFuture.completedFuture(true);
}
}

Some files were not shown because too many files have changed in this diff Show More