Compare commits

...

121 Commits

Author SHA1 Message Date
005e13a216 Maybe #1239 2016-08-17 18:30:58 +10:00
3558105789 Fix default flags NPE 2016-08-17 15:08:01 +10:00
f651607d2f Might work? 2016-08-17 12:22:45 +10:00
6b95e57d9e Merge pull request #1313 from MinelinkNetwork/blocked-cmds
Only show blocked-cmds message when event is cancelled
2016-08-17 12:13:27 +10:00
98d0819383 Only show blocked-cmds message when event is cancelled 2016-08-16 19:09:02 -07:00
30da060f83 Potential fix for schematic placement on clear 2016-08-16 15:53:26 +10:00
e4408d56ec *And this 2016-08-16 14:32:31 +10:00
f07ac646f3 Possible fix for greeting spam 2016-08-15 09:31:03 +10:00
ef3380dc0a Merge remote-tracking branch 'origin/master' 2016-08-12 15:04:18 -04:00
749ab83e5d Move permission check out of loop
See #1307
2016-08-12 15:04:11 -04:00
daea9cf60d Allow teleportation for console 2016-08-10 12:33:18 +10:00
2f74368879 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-08-09 12:45:45 -04:00
63d4476d97 Fix #1181 2016-08-09 12:40:38 -04:00
db69da5b07 *Wrong runnable 2016-08-09 08:52:31 +10:00
d22f7b8781 Merge remote-tracking branch 'origin/master' 2016-08-08 14:03:17 -04:00
112da17614 Squashed commit of the following:
commit 91c78407cd
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 11:29:59 2016 +1000

    Use a queue for expiry

commit 395d6364be
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 04:43:41 2016 +1000

    Cache on fail as well

commit facd43700d
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 04:00:50 2016 +1000

    Cache entity count every second

commit 1ae694ff5b
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 03:52:37 2016 +1000

    Tweak entity counting

commit c99dd1e74a
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sat Aug 6 00:10:11 2016 +1000

    Needs sponge builds

commit f408ac82be
Author: Alexander Söderberg <Sauilitired@users.noreply.github.com>
Date:   Fri Aug 5 12:13:39 2016 +0200

    Update README.md

commit 9b95990ba6
Author: Alexander Söderberg <Sauilitired@users.noreply.github.com>
Date:   Thu Aug 4 16:50:37 2016 +0200

    Update this here as well
2016-08-08 14:02:25 -04:00
91c78407cd Use a queue for expiry 2016-08-07 11:29:59 +10:00
395d6364be Cache on fail as well 2016-08-07 04:43:41 +10:00
facd43700d Cache entity count every second 2016-08-07 04:00:50 +10:00
1ae694ff5b Tweak entity counting 2016-08-07 03:52:37 +10:00
c99dd1e74a Needs sponge builds 2016-08-06 00:10:11 +10:00
f408ac82be Update README.md 2016-08-05 12:13:39 +02:00
9b95990ba6 Update this here as well 2016-08-04 16:50:37 +02:00
77fb329c9e Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-07-31 21:26:18 -04:00
a13b9fb31b flag tix 2016-08-01 11:20:06 +10:00
ea3306d070 Fix #1034 2016-07-31 20:17:35 -04:00
bcbcd6d916 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-07-31 18:14:12 +10:00
415c6fb0d4 Fixes #1283 2016-07-31 18:14:06 +10:00
e801c6d7e8 Merge branch '3.4.5' 2016-07-31 00:16:37 -04:00
409456e895 Minor sponge fix 2016-07-31 09:16:58 +10:00
e8f4eae6f7 Merge remote-tracking branch 'origin/3.4.5' into 3.4.5
# Conflicts:
#	Sponge/build.gradle
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java
2016-07-29 21:45:34 -04:00
c8419f4a4a Added more Java 8 warnings 2016-07-29 21:40:23 -04:00
09994724db Fix #1277 2016-07-29 21:40:02 -04:00
610e204d12 Fix #1281 , Fix #1282 , and Sponge gradle 2016-07-29 12:47:42 -04:00
1f341e6ba9 Merge remote-tracking branch 'origin/master' into 3.4.5
# Conflicts:
#	Sponge/src/main/java/com/plotsquared/sponge/SpongeMain.java
#	Sponge/src/main/java/com/plotsquared/sponge/generator/SpongeAugmentedGenerator.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java
#	build.gradle
2016-07-29 12:25:11 -04:00
ffddf5c187 Fix sponge generator cast 2016-07-29 12:12:28 +10:00
b5ec6232f9 Sponge Fixes and minor changes. 2016-07-25 22:25:15 -04:00
34c2da55ca Change Sponge method behavior 2016-07-25 22:25:15 -04:00
33ec80c2cb Fix Sponge generation casting 2016-07-25 22:25:15 -04:00
48064da1ee Fixed deny-teleport flag 2016-07-25 22:25:15 -04:00
adc021109f Added Polar Bear where missing 2016-07-25 22:25:15 -04:00
d23d8c2fd8 *should use this cause instead 2016-07-25 22:25:15 -04:00
3498f309e8 Minor sponge fixes 2016-07-25 22:24:31 -04:00
0b5177f192 Minor uuid cache changes 2016-07-25 22:23:49 -04:00
07dc6a46fb Remove metrics depend 2016-07-25 22:23:19 -04:00
0b19cc7d9d Possible fix + add guest-gamemode flag 2016-07-25 22:23:19 -04:00
4e019ab796 UUID cache changes 2016-07-25 22:23:19 -04:00
b2fdcad317 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared into 3.4.5
# Conflicts:
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java
2016-07-25 22:08:54 -04:00
80ea3e9ce7 Sponge Fixes and minor changes. 2016-07-25 20:00:59 -04:00
5f8c77a6cd Change Sponge method behavior 2016-07-25 18:43:11 -04:00
290e5c68dc Fix Sponge generation casting 2016-07-25 18:42:31 -04:00
5d92701100 Fixed deny-teleport flag 2016-07-25 18:04:17 -04:00
1a86d5fb9e Added Polar Bear where missing 2016-07-25 01:19:29 -04:00
30d18c917d *should use this cause instead 2016-07-25 09:54:35 +10:00
b91eab2f0c Minor sponge fixes 2016-07-25 09:47:49 +10:00
770b9be160 Minor uuid cache changes 2016-07-25 09:23:20 +10:00
14b2b11bf3 Remove metrics depend 2016-07-25 08:09:57 +10:00
975a5765c1 Possible fix + add guest-gamemode flag 2016-07-25 08:02:17 +10:00
2b9c2959cf Merge branch '3.4.5' of https://github.com/IntellectualSites/PlotSquared into 3.5.0 2016-07-24 17:45:34 -04:00
07977ac2ce UUID cache changes 2016-07-25 07:44:47 +10:00
9e5ac80435 Merge remote-tracking branch 'origin/3.4.5' into 3.4.5 2016-07-24 17:42:21 -04:00
dda6849412 Fix sponge compile 2016-07-24 17:42:03 -04:00
85d6e42462 Merge branch '3.4.5' of https://github.com/IntellectualSites/PlotSquared into 3.5.0 2016-07-24 17:27:41 -04:00
b1ee223b0a Merge pull request #1271 from manuelgu/patch-1
Make debug output useful
2016-07-24 07:51:45 +02:00
98e865cdf0 Make debug output useful 2016-07-23 12:50:39 +02:00
8b084839fd Fix #1261 2016-07-19 10:22:50 -04:00
c1d4c481fb Fix #1244 2016-07-17 23:20:31 -04:00
269e409e3e Version Bump 2016-07-17 23:19:37 -04:00
8538170cba Metrics 2016-07-16 22:51:49 -04:00
76bce7c0ef Catch CommandException 2016-07-14 20:29:11 +10:00
ba568a3f60 Recover from invalid flag value 2016-07-14 00:28:46 +10:00
a43430b722 Fix NPE for null arg 2016-07-13 00:14:26 +10:00
e2c57cea52 . 2016-07-12 23:56:59 +10:00
ca776b2912 Fixes #1226 2016-07-12 22:12:14 +10:00
e859a7f56c Change to interact perm, not build 2016-07-11 20:27:25 +10:00
ad2db9b836 Merge pull request #1245 from manuelgu/fix/CentreCenterName
Add additional alias for /p middle
2016-07-10 22:58:54 +10:00
279084b043 Add additional alias for /p middle
http://grammarist.com/spelling/center-centre/
2016-07-09 09:18:55 +02:00
8b0e59209c Remove getServerName() 2016-07-05 23:43:08 -04:00
ca8b82dcbe Version Bump 2016-07-05 23:39:38 -04:00
cf5d2a5e86 Entity Fix and Gradle changes 2016-07-01 17:13:49 -04:00
b9ad75ad84 Add teleport flag 2016-06-29 21:22:55 +10:00
185352d3cf Fixes #1229 2016-06-29 15:23:10 +10:00
f4fe762135 * 2016-06-28 20:21:50 +10:00
06682b18a5 Fix compile
Recover on unknown command error
Fixes #1224
Close #1213 (fixed elsewhere)
Fixes #1212
2016-06-28 19:55:51 +10:00
f8e97f14d6 Fix end crystal spawn cap 2016-06-28 02:03:23 +10:00
a579df00db Merge remote-tracking branch 'origin/master' 2016-06-27 10:14:28 -04:00
29a0b68dcb Fix currently online for seen info. 2016-06-27 23:59:38 +10:00
d2581bf38b Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-06-27 09:58:17 -04:00
817a5bc16e Various
Fix compatibility with bukkit 1.5
Recover on failed fancy message initialization
Fix /2 remove *
2016-06-27 18:38:14 +10:00
047f9a75b9 Fix #1222 2016-06-27 17:45:19 +10:00
96d0bb0e5e bump pom version 2016-06-26 17:08:54 +10:00
7da0b9877f Fixes #1221 (the NPE at least) 2016-06-26 17:07:46 +10:00
f20ef15774 Revert creature spawn message + change expire to seen 2016-06-26 04:30:12 +10:00
3a973342ae Merge remote-tracking branch 'origin/master' 2016-06-24 10:59:18 -04:00
6e25aab51f Cleanup some docs. 2016-06-24 10:56:38 -04:00
a49492aae3 Fix roadregen 2016-06-24 16:16:22 +10:00
dbe965e901 init script engine on get 2016-06-24 15:41:34 +10:00
2c82d1106a Fixed kick message 2016-06-23 23:19:02 -04:00
5b9dc59abf Updates to docs, code style tweaks, and some code optimizations 2016-06-23 20:12:17 -04:00
b587b430b8 #1211 2016-06-24 05:30:26 +10:00
8fd2599686 Fixes #1211 2016-06-24 02:20:21 +10:00
56000d60e7 Just in case 2016-06-23 13:14:29 +10:00
1643399fc6 Alternatives for setowner none if the username is taken 2016-06-23 13:11:26 +10:00
532fd09800 Merge remote-tracking branch 'origin/master' 2016-06-22 23:10:15 -04:00
e6387419f7 Potential fix for plot biome (untested) 2016-06-23 13:09:56 +10:00
30d49880b6 Fix #1208 NPE 2016-06-22 16:31:04 -04:00
16d191db2c Fixes /plot kick * 2016-06-23 04:08:06 +10:00
7dc7714261 Update Gradle to 2.14 2016-06-22 12:31:25 -04:00
9e1f6d8748 Closes #1209 2016-06-22 13:33:32 +10:00
7fb2631421 Cast to string if necessary 2016-06-21 14:23:04 +10:00
718831e8e0 * 2016-06-21 14:10:20 +10:00
df4585a847 Check args for grant 2016-06-21 13:38:08 +10:00
88d8339cfd fix other NPE 2016-06-21 13:32:28 +10:00
e08db3d12b Check teleportation on command location prefix 2016-06-21 03:02:41 +10:00
2ff4e07919 Setup border on world creation 2016-06-21 01:13:09 +10:00
f6fec56677 Potential fix for terrain 3 worlds. 2016-06-21 00:29:39 +10:00
3fabfa10d7 Add liquid-flow flag 2016-06-20 22:48:04 +10:00
a2ca9a52ea Merge pull request #1205 from manuelgu/fix/deadlink
Remove dead link
2016-06-20 18:52:35 +10:00
e5e3600206 Why were these restricted to players? 2016-06-20 18:52:00 +10:00
7ad50b6314 Remove dead link 2016-06-20 10:49:40 +02:00
01d508edf4 Fix remove * 2016-06-20 15:08:56 +10:00
111 changed files with 2131 additions and 1950 deletions

View File

@ -1,7 +1,12 @@
repositories {
maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"}
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/"}
maven {url "http://nexus.hc.to/content/repositories/pub_releases"}
}
dependencies {
compile project(':Core')
compile 'org.bukkit:bukkit:1.10-R0.1-SNAPSHOT'
compile 'org.mcstats.bukkit:metrics:R7'
compile 'org.spigotmc:spigot-api:1.10.2-R0.1-SNAPSHOT'
compile 'net.milkbowl.vault:VaultAPI:1.6'
}
@ -17,19 +22,18 @@ processResources {
)
}
}
apply plugin: 'com.github.johnrengelman.shadow'
// We only want the shadow jar produced
jar.enabled = false
shadowJar {
dependencies {
include(dependency(':Core'))
include(dependency('org.mcstats.bukkit:metrics:R7'))
}
relocate 'org.mcstats', 'com.plotsquared.stats'
relocate('org.mcstats', 'com.plotsquared.stats')
archiveName = "${parent.name}-${project.name}-${parent.version}.jar"
destinationDir = file '../target'
}
shadowJar.doLast {
task ->
ant.checksum file: task.archivePath

View File

@ -20,17 +20,18 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
/**
* PlotSquared API.
@ -378,9 +379,9 @@ public class PlotAPI {
}
/**
* Register a flag for use in plots.
* Registers a flag for use in plots.
*
* @param flag the flag being registered
* @param flag the flag to register
*
*/
public void addFlag(Flag<?> flag) {
@ -388,7 +389,7 @@ public class PlotAPI {
}
/**
* Get a plot based on the ID.
* Gets a plot based on the ID.
*
* @param world the world the plot is located in
* @param x The PlotID x coordinate
@ -617,7 +618,7 @@ public class PlotAPI {
}
/**
* Get the PlotSquared class.
* Gets the PlotSquared class.
*
* @return PlotSquared Class
*
@ -628,7 +629,7 @@ public class PlotAPI {
}
/**
* Get the player plot count.
* Gets the player plot count.
*
* @param world Specify the world we want to select the plots from
* @param player Player, for whom we're getting the plot count
@ -644,7 +645,7 @@ public class PlotAPI {
}
/**
* Get a collection containing the players plots.
* Gets a collection containing the players plots.
*
* @param world Specify the world we want to select the plots from
* @param player Player, for whom we're getting the plots
@ -663,7 +664,7 @@ public class PlotAPI {
}
/**
* Get the numbers of plots, which the player is able to build in.
* Gets the number of plots, which the player is able to build in.
*
* @param player player, for whom we're getting the plots
*
@ -676,7 +677,7 @@ public class PlotAPI {
}
/**
* Get the PlotPlayer for a player. The PlotPlayer is usually cached and
* Gets the PlotPlayer for a player. The PlotPlayer is usually cached and
* will provide useful functions relating to players.
*
* @see PlotPlayer#wrap(Object)

View File

@ -15,6 +15,7 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.object.chat.PlainChatManager;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.ChatManager;
import com.intellectualcrafters.plot.util.ChunkManager;
@ -37,7 +38,7 @@ import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter;
import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.bukkit.listeners.ChunkListener;
import com.plotsquared.bukkit.listeners.ForceFieldListener;
import com.plotsquared.bukkit.listeners.EntitySpawnListener;
import com.plotsquared.bukkit.listeners.PlayerEvents;
import com.plotsquared.bukkit.listeners.PlayerEvents183;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_8;
@ -52,7 +53,6 @@ import com.plotsquared.bukkit.util.BukkitEconHandler;
import com.plotsquared.bukkit.util.BukkitEventUtil;
import com.plotsquared.bukkit.util.BukkitHybridUtils;
import com.plotsquared.bukkit.util.BukkitInventoryUtil;
import com.plotsquared.bukkit.util.BukkitPlainChatManager;
import com.plotsquared.bukkit.util.BukkitSchematicHandler;
import com.plotsquared.bukkit.util.BukkitSetupUtils;
import com.plotsquared.bukkit.util.BukkitTaskManager;
@ -71,12 +71,6 @@ import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.sk89q.worldedit.WorldEdit;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -92,6 +86,13 @@ import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public static WorldEdit worldEdit;
@ -113,7 +114,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
return new int[]{1, 9, 2};
return new int[]{1, 10, 0};
}
}
return this.version;
@ -121,7 +122,14 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override
public void onEnable() {
getServer().getName();
new PS(this, "Bukkit");
if (Settings.Enabled_Components.METRICS) {
new Metrics(this).start();
PS.log(C.PREFIX + "&6Metrics enabled.");
} else {
PS.log(C.CONSOLE_PLEASE_ENABLE_METRICS);
}
}
@Override
@ -158,6 +166,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return getDescription().getVersion();
}
@Override
public void registerCommands() {
BukkitCommand bukkitCommand = new BukkitCommand();
@ -202,7 +214,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
Entity entity = iterator.next();
switch (entity.getType()) {
case EGG:
case ENDER_CRYSTAL:
case COMPLEX_PART:
case FISHING_HOOK:
case ENDER_SIGNAL:
@ -233,18 +244,17 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
// Not vehicles
continue;
case ARMOR_STAND:
// Tempirarily classify as vehicle
// Temporarily classify as vehicle
case MINECART:
case MINECART_CHEST:
case MINECART_COMMAND:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case ENDER_CRYSTAL:
case MINECART_TNT:
case BOAT: {
if (!Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
continue;
}
if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation());
Plot plot = location.getPlot();
if (plot == null) {
@ -264,6 +274,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
entity.remove();
}
continue;
} else {
continue;
}
}
case SMALL_FIREBALL:
case FIREBALL:
@ -275,6 +288,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case FALLING_BLOCK:
// managed elsewhere
continue;
case POLAR_BEAR:
case BAT:
case BLAZE:
case CAVE_SPIDER:
@ -309,9 +323,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
case ZOMBIE:
case SHULKER:
default:
if (!Settings.Enabled_Components.KILL_ROAD_MOBS) {
continue;
}
if (Settings.Enabled_Components.KILL_ROAD_MOBS) {
Location location = entity.getLocation();
if (BukkitUtil.getLocation(location).isPlotRoad()) {
if (entity instanceof LivingEntity) {
@ -333,6 +345,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
}
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
@ -355,6 +368,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
public void registerPlayerEvents() {
PlayerEvents main = new PlayerEvents();
getServer().getPluginManager().registerEvents(main, this);
try {
getServer().getClass().getMethod("spigot");
getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this);
} catch (NoSuchMethodException ignored) {
PS.debug("Not running Spigot. Skipping EntitySpawnListener event.");
}
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
try {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
@ -391,7 +410,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override
public void registerForceFieldEvents() {
getServer().getPluginManager().registerEvents(new ForceFieldListener(), this);
}
@Override
@ -422,7 +440,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
new SendChunk();
MainUtil.canSendChunk = true;
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
e.printStackTrace();
PS.debug(SendChunk.class + " does not support " + StringMan.getString(getServerVersion()));
MainUtil.canSendChunk = false;
}
if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) {
@ -560,15 +578,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return new BukkitInventoryUtil();
}
@Override
public String getServerName() {
return Bukkit.getServerName();
}
@Override
public void startMetrics() {
Metrics metrics = new Metrics(this);
metrics.start();
new Metrics(this).start();
PS.log(C.PREFIX + "&6Metrics enabled.");
}
@ -647,7 +659,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
if (Settings.Chat.INTERACTIVE) {
return new BukkitChatManager();
} else {
return new BukkitPlainChatManager();
return new PlainChatManager();
}
}

View File

@ -1,10 +1,25 @@
package com.plotsquared.bukkit.chat;
import static com.plotsquared.bukkit.chat.TextualComponent.rawText;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import org.bukkit.Achievement;
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;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
@ -19,21 +34,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.bukkit.Achievement;
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;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import static com.plotsquared.bukkit.chat.TextualComponent.rawText;
/**
* Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features provided by the vanilla Minecraft <a href="http://minecraft.gamepedia.com/Tellraw#Raw_JSON_Text">JSON message formatter</a>.
@ -60,7 +60,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
@Override
public FancyMessage clone() throws CloneNotSupportedException {
FancyMessage instance = (FancyMessage) super.clone();
instance.messageParts = new ArrayList<MessagePart>(messageParts.size());
instance.messageParts = new ArrayList<>(messageParts.size());
for (int i = 0; i < messageParts.size(); i++) {
instance.messageParts.add(i, messageParts.get(i).clone());
}
@ -78,15 +78,15 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
this(rawText(firstPartText));
}
public FancyMessage(final com.plotsquared.bukkit.chat.TextualComponent firstPartText) {
messageParts = new ArrayList<MessagePart>();
public FancyMessage(final TextualComponent firstPartText) {
messageParts = new ArrayList<>();
messageParts.add(new MessagePart(firstPartText));
jsonString = null;
dirty = false;
if (nmsPacketPlayOutChatConstructor == null) {
try {
nmsPacketPlayOutChatConstructor = com.plotsquared.bukkit.chat.Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(com.plotsquared.bukkit.chat.Reflection.getNMSClass("IChatBaseComponent"));
nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent"));
nmsPacketPlayOutChatConstructor.setAccessible(true);
} catch (NoSuchMethodException e) {
Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e);
@ -100,7 +100,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* Creates a JSON message without text.
*/
public FancyMessage() {
this((com.plotsquared.bukkit.chat.TextualComponent) null);
this((TextualComponent) null);
}
/**
@ -122,7 +122,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param text The new text of the current editing component.
* @return This builder instance.
*/
public FancyMessage text(com.plotsquared.bukkit.chat.TextualComponent text) {
public FancyMessage text(TextualComponent text) {
MessagePart latest = latest();
latest.text = text;
dirty = true;
@ -243,8 +243,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
*/
public FancyMessage achievementTooltip(final Achievement which) {
try {
Object achievement = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Achievement"), "name").get(achievement));
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;
@ -252,7 +252,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -271,8 +271,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!");
}
try {
Object statistic = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which);
return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Statistic"), "name").get(statistic));
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -280,7 +280,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -303,8 +303,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
}
try {
Object statistic = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item);
return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Statistic"), "name").get(statistic));
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -312,7 +312,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -335,8 +335,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!");
}
try {
Object statistic = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity);
return achievementTooltip((String) com.plotsquared.bukkit.chat.Reflection.getField(com.plotsquared.bukkit.chat.Reflection.getNMSClass("Statistic"), "name").get(statistic));
Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity);
return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
@ -344,7 +344,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
@ -370,8 +370,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
*/
public FancyMessage itemTooltip(final ItemStack itemStack) {
try {
Object nmsItem = com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack);
return itemTooltip(com.plotsquared.bukkit.chat.Reflection.getMethod(com.plotsquared.bukkit.chat.Reflection.getNMSClass("ItemStack"), "save", com.plotsquared.bukkit.chat.Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, com.plotsquared.bukkit.chat.Reflection.getNMSClass("NBTTagCompound").newInstance()).toString());
Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack);
return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString());
} catch (Exception e) {
e.printStackTrace();
return this;
@ -565,7 +565,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
* @param text The text which will populate the new message component.
* @return This builder instance.
*/
public FancyMessage then(final com.plotsquared.bukkit.chat.TextualComponent text) {
public FancyMessage then(final TextualComponent text) {
if (!latest().hasText()) {
throw new IllegalStateException("previous message part has no text");
}
@ -641,9 +641,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
}
Player player = (Player) sender;
try {
Object handle = com.plotsquared.bukkit.chat.Reflection.getHandle(player);
Object connection = com.plotsquared.bukkit.chat.Reflection.getField(handle.getClass(), "playerConnection").get(handle);
com.plotsquared.bukkit.chat.Reflection.getMethod(connection.getClass(), "sendPacket", com.plotsquared.bukkit.chat.Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString));
Object handle = Reflection.getHandle(player);
Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle);
Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString));
} catch (IllegalArgumentException e) {
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
} catch (IllegalAccessException e) {
@ -651,7 +651,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
} catch (InstantiationException e) {
Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e);
} catch (InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "A error has occured durring invoking of method.", e);
Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e);
} catch (NoSuchMethodException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e);
} catch (ClassNotFoundException e) {
@ -673,16 +673,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
// X = major
// Y = minor
// Z = revision
final String version = com.plotsquared.bukkit.chat.Reflection.getVersion();
final String version = Reflection.getVersion();
String[] split = version.substring(1, version.length() - 1).split("_"); // Remove trailing dot
//int majorVersion = Integer.parseInt(split[0]);
int minorVersion = Integer.parseInt(split[1]);
int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R
if (minorVersion < 8 || (minorVersion == 8 && revisionVersion == 1)) {
chatSerializerClazz = com.plotsquared.bukkit.chat.Reflection.getNMSClass("ChatSerializer");
chatSerializerClazz = Reflection.getNMSClass("ChatSerializer");
} else {
chatSerializerClazz = com.plotsquared.bukkit.chat.Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
chatSerializerClazz = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
}
if (chatSerializerClazz == null) {
@ -702,7 +702,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
// Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
// Of course, the implementation may change, but fuzzy matches might break with signature changes
Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, com.plotsquared.bukkit.chat.Reflection.getNMSClass("IChatBaseComponent"));
Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent"));
return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
}
@ -781,7 +781,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
// Doc copied from interface
public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, Object> map = new HashMap<>();
map.put("messageParts", messageParts);
// map.put("JSON", toJSONString());
return map;
@ -829,9 +829,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
JsonObject messagePart = mPrt.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
// Deserialize text
if (com.plotsquared.bukkit.chat.TextualComponent.isTextKey(entry.getKey())) {
if (TextualComponent.isTextKey(entry.getKey())) {
// The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
Map<String, Object> serializedMapForm = new HashMap<String, Object>(); // Must be object due to Bukkit serializer API compliance
Map<String, Object> serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance
serializedMapForm.put("key", entry.getKey());
if (entry.getValue().isJsonPrimitive()) {
// Assume string
@ -842,7 +842,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable<
serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString());
}
}
component.text = com.plotsquared.bukkit.chat.TextualComponent.deserialize(serializedMapForm);
component.text = TextualComponent.deserialize(serializedMapForm);
} else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
if (entry.getValue().getAsBoolean()) {
component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));

View File

@ -20,12 +20,14 @@ import java.util.logging.Level;
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<ChatColor>();
String clickActionName = null, clickActionData = null, hoverActionName = null;
ArrayList<ChatColor> styles = new ArrayList<>();
String clickActionName = null;
String clickActionData = null;
String hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<JsonRepresentedObject>();
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
MessagePart(final TextualComponent text) {
this.text = text;
@ -121,7 +123,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
}
public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, Object> map = new HashMap<>();
map.put("text", text);
map.put("styles", styles);
map.put("color", color.getChar());

View File

@ -3,6 +3,7 @@ package com.plotsquared.bukkit.chat;
import org.bukkit.Bukkit;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
@ -14,6 +15,20 @@ import java.util.Map;
*/
public final class Reflection {
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
private static final Map<String, Class<?>> _loadedNMSClasses = new HashMap<>();
/**
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<>();
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<>();
/**
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<>();
private static String _versionString;
private Reflection() { }
@ -37,16 +52,6 @@ public final class Reflection {
return _versionString;
}
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
private static final Map<String, Class<?>> _loadedNMSClasses = new HashMap<String, Class<?>>();
/**
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<String, Class<?>>();
/**
* Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
@ -60,13 +65,12 @@ public final class Reflection {
}
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
Class<?> clazz;
try {
clazz = Class.forName(fullName);
} catch (Exception e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
_loadedNMSClasses.put(className, null);
return null;
throw new RuntimeException(e);
}
_loadedNMSClasses.put(className, clazz);
return clazz;
@ -85,13 +89,12 @@ public final class Reflection {
}
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null;
Class<?> clazz;
try {
clazz = Class.forName(fullName);
} catch (Exception e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
_loadedOBCClasses.put(className, null);
return null;
throw new RuntimeException(e);
}
_loadedOBCClasses.put(className, clazz);
return clazz;
@ -106,16 +109,9 @@ public final class Reflection {
* @param obj The object for which to retrieve an NMS handle.
* @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
*/
public synchronized static Object getHandle(Object obj) {
try {
public synchronized static Object getHandle(Object obj) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException {
return getMethod(obj.getClass(), "getHandle").invoke(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<Class<?>, Map<String, Field>>();
/**
* Retrieves a {@link Field} instance declared by the specified class with the specified name.
@ -138,7 +134,7 @@ public final class Reflection {
public synchronized static Field getField(Class<?> clazz, String name) {
Map<String, Field> loaded;
if (!_loadedFields.containsKey(clazz)) {
loaded = new HashMap<String, Field>();
loaded = new HashMap<>();
_loadedFields.put(clazz, loaded);
} else {
loaded = _loadedFields.get(clazz);
@ -152,7 +148,7 @@ public final class Reflection {
field.setAccessible(true);
loaded.put(name, field);
return field;
} catch (Exception e) {
} catch (NoSuchFieldException | SecurityException e) {
// Error loading
e.printStackTrace();
// Cache field as not existing
@ -161,12 +157,6 @@ public final class Reflection {
}
}
/**
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>>();
/**
* Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
@ -174,11 +164,9 @@ public final class Reflection {
* <p>
* A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that
* no method will be reflectively looked up twice.
* </p>
* <p>
* If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
* <p>
* This method does <em>not</em> search superclasses of the specified type for methods with the specified signature.
* Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
@ -199,7 +187,7 @@ public final class Reflection {
}
Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<Class<?>>(args);
ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args);
if (loadedSignatures.containsKey(wrappedArg)) {
return loadedSignatures.get(wrappedArg);
}

View File

@ -23,6 +23,119 @@ public abstract class TextualComponent implements Cloneable {
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
}
static TextualComponent deserialize(Map<String, Object> map) {
if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
// Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map);
} else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
return null;
}
static boolean isTextKey(String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
static boolean isTranslatableText(TextualComponent component) {
return component instanceof ComplexTextTypeComponent && component.getKey().equals("translate");
}
/**
* Create a textual component representing a string literal.
*
* <p>This is the default type of textual component when a single string
* literal is given to a method.
*
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(String textValue) {
return new ArbitraryTextTypeComponent("text", textValue);
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a
* resource pack.
* <p>
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to
* the client.
* </p>
*
* @param translateKey The string key which maps to localized text.
* @return The text component representing the specified localized text.
*/
public static TextualComponent localizedText(String translateKey) {
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during
* JSON serialization.
*/
public static TextualComponent objectiveScore(String scoreboardObjective) {
return objectiveScore("*", scoreboardObjective);
}
/**
* Create a textual component representing a scoreboard value.
* The client will see the score of the specified player for the specified objective as the text represented by this component.
*
* <p><b>This method is currently guaranteed to throw an {@code UnsupportedOperationException}
* as it is only supported on snapshot clients.</b>
*
* @param playerName The name of the player whos score will be shown. If
* this string represents the single-character sequence
* "*", the viewing player's score will be displayed.
* Standard minecraft selectors (@a, @p, etc)
* are <em>not</em> supported.
* @param scoreboardObjective The name of the objective for
* which to display the score.
* @return The text component representing the specified scoreboard score
* for the specified player, or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
// OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder()
.put("name", playerName)
.put("objective", scoreboardObjective)
.build());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in
* the place of this text component.
* @return The text component representing the name of the entities captured by the selector.
*/
public static TextualComponent selector(String selector) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
// OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
@Override
public String toString() {
return getReadableString();
@ -54,59 +167,43 @@ public abstract class TextualComponent implements Cloneable {
*/
public abstract void writeJson(JsonWriter writer) throws IOException;
static TextualComponent deserialize(Map<String, Object> map) {
if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
// Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map);
} else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
return null;
}
static boolean isTextKey(String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
static boolean isTranslatableText(TextualComponent component) {
return component instanceof ComplexTextTypeComponent && ((ComplexTextTypeComponent) component).getKey().equals("translate");
}
/**
* Internal class used to represent all types of text components.
* Exception validating done is on keys and values.
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private String key;
private String value;
public ArbitraryTextTypeComponent(String key, String value) {
setKey(key);
setValue(value);
}
public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
@Override
public String getKey() {
return _key;
return key;
}
public void setKey(String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
_key = key;
this.key = key;
}
public String getValue() {
return _value;
return value;
}
public void setValue(String value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
this.value = value;
}
private String _key;
private String _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
@ -118,16 +215,15 @@ public abstract class TextualComponent implements Cloneable {
writer.name(getKey()).value(getValue());
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new HashMap<String, Object>() {{
return new HashMap<String, Object>() {
{
put("key", getKey());
put("value", getValue());
}};
}
public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
};
}
@Override
@ -137,40 +233,55 @@ public abstract class TextualComponent implements Cloneable {
}
/**
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
* Internal class used to represent a text component with a nested JSON
* value.
*
* <p>Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private String key;
private Map<String, String> value;
public ComplexTextTypeComponent(String key, Map<String, String> values) {
setKey(key);
setValue(values);
}
public static ComplexTextTypeComponent deserialize(Map<String, Object> map) {
String key = null;
Map<String, String> value = new HashMap<>();
for (Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getKey() {
return _key;
return key;
}
public void setKey(String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
_key = key;
this.key = key;
}
public Map<String, String> getValue() {
return _value;
return value;
}
public void setValue(Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
this.value = value;
}
private String _key;
private Map<String, String> _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException {
public TextualComponent clone() {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
@ -179,33 +290,23 @@ public abstract class TextualComponent implements Cloneable {
public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for (Map.Entry<String, String> jsonPair : _value.entrySet()) {
for (Map.Entry<String, String> jsonPair : value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>() {{
return new java.util.HashMap<String, Object>() {
{
put("key", getKey());
for (Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue());
}
}};
}
public static ComplexTextTypeComponent deserialize(Map<String, Object> map) {
String key = null;
Map<String, String> value = new HashMap<String, String>();
for (Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(((String) valEntry.getKey()).substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
};
}
@Override
@ -213,85 +314,4 @@ public abstract class TextualComponent implements Cloneable {
return getKey();
}
}
/**
* Create a textual component representing a string literal.
* This is the default type of textual component when a single string literal is given to a method.
*
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(String textValue) {
return new ArbitraryTextTypeComponent("text", textValue);
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack.
* <p>
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client.
* </p>
*
* @param translateKey The string key which maps to localized text.
* @return The text component representing the specified localized text.
*/
public static TextualComponent localizedText(String translateKey) {
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(String scoreboardObjective) {
return objectiveScore("*", scoreboardObjective);
}
/**
* Create a textual component representing a scoreboard value.
* The client will see the score of the specified player for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing player's score will be displayed.
* Standard minecraft selectors (@a, @p, etc) are <em>not</em> supported.
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder()
.put("name", playerName)
.put("objective", scoreboardObjective)
.build());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component.
* @return The text component representing the name of the entities captured by the selector.
*/
public static TextualComponent selector(String selector) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
}

View File

@ -13,7 +13,7 @@ import java.util.HashMap;
public abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(FileConfiguration plotConfig, String dataFolder);
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException;

View File

@ -26,12 +26,12 @@ import java.util.UUID;
public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin;
private String plugin = "PlotMe";
private String prefix;
@Override
public Connection getPlotMeConnection(FileConfiguration plotConfig, String dataFolder) {
this.plugin = this.plugin.toLowerCase();
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
this.prefix = plotConfig.getString("mySQLprefix", this.plugin.toLowerCase());
try {
if (plotConfig.getBoolean("usemySQL")) {

View File

@ -123,7 +123,7 @@ public class LikePlotMeConverter {
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
Connection connection = connector.getPlotMeConnection(plotConfig, dataFolder);
Connection connection = connector.getPlotMeConnection(plugin,plotConfig, dataFolder);
if (!connector.isValidConnection(connection)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");

View File

@ -26,8 +26,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin;
@Override
public Connection getPlotMeConnection(FileConfiguration plotConfig, String dataFolder) {
this.plugin = this.plugin.toLowerCase();
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
try {
if (plotConfig.getBoolean("usemySQL")) {
String user = plotConfig.getString("mySQLuname");

View File

@ -20,17 +20,18 @@ import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
private final GenChunk chunkSetter;
@ -255,7 +256,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override
public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter;
GenChunk result = this.chunkSetter;
// Set the chunk location
result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data
@ -303,7 +304,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override
public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter;
GenChunk result = this.chunkSetter;
// Set the chunk location
result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data

View File

@ -1,7 +1,5 @@
package com.plotsquared.bukkit.listeners;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
@ -10,6 +8,8 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import java.lang.reflect.Method;
import java.util.HashSet;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
@ -28,8 +28,8 @@ import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import java.lang.reflect.Method;
import java.util.HashSet;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class ChunkListener implements Listener {
@ -100,14 +100,21 @@ public class ChunkListener implements Listener {
}, 1);
}
private boolean ignoreUnload = false;
public boolean unloadChunk(String world, Chunk chunk, boolean safe) {
if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) {
return false;
}
Object c = this.methodGetHandleChunk.of(chunk).call();
this.mustSave.of(c).set(false);
RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get() == true) {
field.set(false);
if (chunk.isLoaded()) {
ignoreUnload = true;
chunk.unload(false, false);
ignoreUnload = false;
}
}
return true;
}
@ -139,6 +146,9 @@ public class ChunkListener implements Listener {
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
if (ignoreUnload) {
return;
}
if (Settings.Chunk_Processor.AUTO_TRIM) {
Chunk chunk = event.getChunk();
String world = chunk.getWorld().getName();

View File

@ -0,0 +1,41 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
public class EntitySpawnListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void creatureSpawnEvent(EntitySpawnEvent event) {
Entity entity = event.getEntity();
Location location = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getOwnedPlotAbs(location);
if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) {
event.setCancelled(true);
}
switch (entity.getType()) {
case ENDER_CRYSTAL:
if (plot == null) {
if (!area.MOB_SPAWNING) {
event.setCancelled(true);
}
return;
}
if (PlayerEvents.checkEntity(entity, plot)) {
event.setCancelled(true);
}
}
}
}

View File

@ -1,27 +1,26 @@
package com.plotsquared.bukkit.listeners;
import com.google.common.collect.Iterables;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class ForceFieldListener implements Listener {
public class ForceFieldListener {
private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer> players = new HashSet<>();
for (Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) {
PlotPlayer plotPlayer;
if (!(entity instanceof Player) || ((plotPlayer = BukkitUtil.getPlayer((Player) entity)) == null) || !plot.equals(plotPlayer.getCurrentPlot())) {
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (!plot.isAdded(plotPlayer.getUUID())) {
@ -32,15 +31,9 @@ public class ForceFieldListener implements Listener {
}
private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) {
for (Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
if (!(entity instanceof Player)) {
continue;
}
for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) {
PlotPlayer plotPlayer;
if ((plotPlayer = BukkitUtil.getPlayer((Player) entity)) == null) {
continue;
}
if (!plot.equals(plotPlayer.getCurrentPlot())) {
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (plot.isAdded(plotPlayer.getUUID())) {

View File

@ -28,16 +28,6 @@ import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlayerBlockEventType;
import com.plotsquared.listener.PlotListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@ -86,7 +76,9 @@ import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustByEntityEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.PotionSplashEvent;
@ -121,6 +113,17 @@ import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* Player Events involving plots.
*
@ -279,8 +282,7 @@ public class PlayerEvents extends PlotListener implements Listener {
if (!(shooter instanceof Player)) {
return;
}
ThrownPotion potion = (ThrownPotion) entity;
Location l = BukkitUtil.getLocation(potion);
Location l = BukkitUtil.getLocation(entity);
if (!PS.get().hasPlotArea(l.getWorld())) {
return;
}
@ -410,7 +412,6 @@ public class PlayerEvents extends PlotListener implements Listener {
pattern = RegExUtil.compiledPatterns.get(s);
}
if (pattern.matcher(msg).matches()) {
MainUtil.sendMessage(pp, C.COMMAND_BLOCKED);
String perm;
if (plot.isAdded(pp.getUUID())) {
perm = "plots.admin.command.blocked-cmds.shared";
@ -418,6 +419,7 @@ public class PlayerEvents extends PlotListener implements Listener {
perm = "plots.admin.command.blocked-cmds.other";
}
if (!Permissions.hasPermission(pp, perm)) {
MainUtil.sendMessage(pp, C.COMMAND_BLOCKED);
event.setCancelled(true);
}
return;
@ -699,7 +701,7 @@ public class PlayerEvents extends PlotListener implements Listener {
if (this.lastRadius != 0) {
List<Entity> nearby = event.getEntity().getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius);
for (Entity near : nearby) {
if (near instanceof TNTPrimed || near.getType() == EntityType.MINECART_TNT) {
if (near instanceof TNTPrimed || near.getType().equals(EntityType.MINECART_TNT)) {
if (!near.hasMetadata("plot")) {
near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot));
}
@ -898,8 +900,19 @@ public class PlayerEvents extends PlotListener implements Listener {
if (plot != null) {
if (Flags.DISABLE_PHYSICS.isFalse(plot)) {
event.setCancelled(true);
return;
} else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) {
event.setCancelled(true);
return;
}
if (Flags.LIQUID_FLOW.isFalse(plot)) {
switch (to.getType()) {
case WATER:
case STATIONARY_WATER:
case LAVA:
case STATIONARY_LAVA:
event.setCancelled(true);
}
}
} else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) {
event.setCancelled(true);
@ -941,12 +954,12 @@ public class PlayerEvents extends PlotListener implements Listener {
}
List<Block> blocks = event.getBlocks();
for (Block b : blocks) {
Location bloc = BukkitUtil.getLocation(b.getLocation().add(relative));
if (!area.contains(bloc.getX(), bloc.getZ())) {
Location bloc = BukkitUtil.getLocation(b.getLocation());
if (!area.contains(bloc.getX(), bloc.getZ()) || !area.contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) {
event.setCancelled(true);
return;
}
if (!plot.equals(area.getOwnedPlot(bloc))) {
if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot(bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) {
event.setCancelled(true);
return;
}
@ -1087,7 +1100,7 @@ public class PlayerEvents extends PlotListener implements Listener {
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
@ -1174,14 +1187,13 @@ public class PlayerEvents extends PlotListener implements Listener {
}
lb = new BukkitLazyBlock(blockId, block);
ItemStack hand = player.getItemInHand();
if (eventType != null) {
if (eventType != null && (eventType != PlayerBlockEventType.INTERACT_BLOCK || !player.isSneaking())) {
break;
}
Material type = (hand == null) ? null : hand.getType();
int id = (type == null) ? 0 : type.getId();
if (id == 0) {
eventType = PlayerBlockEventType.INTERACT_BLOCK;
lb = new BukkitLazyBlock(0, block);
break;
}
if (id < 198) {
@ -1272,7 +1284,7 @@ public class PlayerEvents extends PlotListener implements Listener {
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void MobSpawn(CreatureSpawnEvent event) {
public void creatureSpawnEvent(CreatureSpawnEvent event) {
Entity entity = event.getEntity();
Location location = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = location.getPlotArea();
@ -1318,10 +1330,6 @@ public class PlayerEvents extends PlotListener implements Listener {
return;
}
if (checkEntity(entity, plot)) {
PlotPlayer owner = UUIDHandler.getPlayer(plot.owner);
if (owner != null) {
C.ENTITY_CAP.send(owner);
}
event.setCancelled(true);
}
}
@ -1368,7 +1376,10 @@ public class PlayerEvents extends PlotListener implements Listener {
this.lastRadius = event.getRadius() + 1;
}
public boolean checkEntity(Plot plot, IntegerFlag... flags) {
public static boolean checkEntity(Plot plot, IntegerFlag... flags) {
if (Settings.Done.RESTRICT_BUILDING && Flags.DONE.isSet(plot)) {
return true;
}
int[] mobs = null;
for (IntegerFlag flag : flags) {
int i;
@ -1398,17 +1409,52 @@ public class PlayerEvents extends PlotListener implements Listener {
if (cap == Integer.MAX_VALUE) {
continue;
}
if (cap == 0) {
return true;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[i] >= cap) {
plot.setMeta("EntityCount", mobs);
plot.setMeta("EntityCountTime", System.currentTimeMillis());
return true;
}
}
if (mobs != null) {
for (IntegerFlag flag : flags) {
int i;
switch (flag.getName()) {
case "entity-cap":
i = 0;
break;
case "mob-cap":
i = 3;
break;
case "hostile-cap":
i = 2;
break;
case "animal-cap":
i = 1;
break;
case "vehicle-cap":
i = 4;
break;
case "misc-cap":
i = 5;
break;
default:
i = 0;
}
mobs[i]++;
}
plot.setMeta("EntityCount", mobs);
plot.setMeta("EntityCountTime", System.currentTimeMillis());
}
return false;
}
public boolean checkEntity(Entity entity, Plot plot) {
public static boolean checkEntity(Entity entity, Plot plot) {
if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS.isEmpty()) {
return false;
}
@ -1461,6 +1507,7 @@ public class PlayerEvents extends PlotListener implements Listener {
case MINECART_TNT:
case BOAT:
return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP);
case POLAR_BEAR:
case RABBIT:
case SHEEP:
case MUSHROOM_COW:
@ -1641,7 +1688,7 @@ public class PlayerEvents extends PlotListener implements Listener {
if (area == null) {
return;
}
Plot now = area.getPlotAbs(loc);
Plot now = area.getPlot(loc);
Plot lastPlot = pp.getMeta("lastplot");
if (now == null) {
if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport) {
@ -1662,6 +1709,9 @@ public class PlayerEvents extends PlotListener implements Listener {
return;
}
} else if (lastPlot != null && now.equals(lastPlot)) {
if (!Flags.DENY_TELEPORT.allowsTeleport(pp, lastPlot)) {
event.setTo(BukkitUtil.getLocation(lastPlot.getSide()));
}
return;
} else if (!plotEntry(pp, now) && this.tmpTeleport) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
@ -1711,7 +1761,7 @@ public class PlayerEvents extends PlotListener implements Listener {
if (area == null) {
return;
}
Plot now = area.getPlotAbs(loc);
Plot now = area.getPlot(loc);
Plot lastPlot = pp.getMeta("lastplot");
if (now == null) {
if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport) {
@ -1732,6 +1782,9 @@ public class PlayerEvents extends PlotListener implements Listener {
return;
}
} else if (lastPlot != null && now.equals(lastPlot)) {
if (!Flags.DENY_TELEPORT.allowsTeleport(pp, lastPlot)) {
event.setTo(BukkitUtil.getLocation(lastPlot.getSide()));
}
return;
} else if (!plotEntry(pp, now) && this.tmpTeleport) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
@ -1833,6 +1886,9 @@ public class PlayerEvents extends PlotListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onLeave(PlayerQuitEvent event) {
if (TaskManager.TELEPORT_QUEUE.contains(event.getPlayer().getName())) {
TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName());
}
PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer());
pp.unregister();
}
@ -2097,6 +2153,13 @@ public class PlayerEvents extends PlotListener implements Listener {
}
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration());
onEntityDamageByEntityEvent(eventChange);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();

View File

@ -12,9 +12,12 @@ import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.UUID;
import org.bukkit.plugin.RegisteredListener;
public class BukkitPlayer extends PlotPlayer {
@ -57,6 +60,39 @@ public class BukkitPlayer extends PlotPlayer {
return this.player.getLastPlayed();
}
@Override
public boolean canTeleport(Location loc) {
org.bukkit.Location to = BukkitUtil.getLocation(loc);
org.bukkit.Location from = player.getLocation();
PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to);
RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals("PlotSquared")) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
if (event.isCancelled() || !event.getTo().equals(to)) {
return false;
}
event = new PlayerTeleportEvent(player, to, from);
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals("PlotSquared")) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
return true;
}
@Override
public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) {

View File

@ -366,7 +366,11 @@ public class EntityWrapper {
}
private void restoreInventory(InventoryHolder entity) {
try {
entity.getInventory().setContents(this.inventory);
} catch (IllegalArgumentException e) {
PS.debug("&c[WARN] Failed to restore inventory.\n Reason: " + e.getMessage());
}
}
public void storeLiving(LivingEntity lived) {

View File

@ -30,7 +30,6 @@ public class DefaultTitleManager_183 extends DefaultTitleManager {
this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent");
this.packetActions = Reflection.getNMSClass("PacketPlayOutTitle$EnumTitleAction");
this.nmsChatSerializer = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
}
@Override

View File

@ -52,7 +52,7 @@ public abstract class TitleManager {
abstract void loadClasses();
/**
* Get title text.
* Gets title text.
*
* @return Title text
*/
@ -61,7 +61,7 @@ public abstract class TitleManager {
}
/**
* Set title text.
* Sets the text for the title.
*
* @param title Title
*/
@ -70,7 +70,7 @@ public abstract class TitleManager {
}
/**
* Get subtitle text.
* Gets the subtitle text.
*
* @return Subtitle text
*/
@ -79,7 +79,7 @@ public abstract class TitleManager {
}
/**
* Set subtitle text.
* Sets subtitle text.
*
* @param subtitle Subtitle text
*/
@ -88,7 +88,7 @@ public abstract class TitleManager {
}
/**
* Set the title color.
* Sets the title color.
*
* @param color Chat color
*/
@ -97,7 +97,7 @@ public abstract class TitleManager {
}
/**
* Set the subtitle color.
* Sets the subtitle color.
*
* @param color Chat color
*/
@ -106,7 +106,7 @@ public abstract class TitleManager {
}
/**
* Set title fade in time.
* Sets title fade in time.
*
* @param time Time
*/
@ -115,7 +115,7 @@ public abstract class TitleManager {
}
/**
* Set title fade out time.
* Sets title fade out time.
*
* @param time Time
*/
@ -124,7 +124,7 @@ public abstract class TitleManager {
}
/**
* Set title stay time.
* Sets title stay time.
*
* @param time Time
*/
@ -133,21 +133,21 @@ public abstract class TitleManager {
}
/**
* Set timings to ticks.
* Sets timings to ticks.
*/
public final void setTimingsToTicks() {
this.ticks = true;
}
/**
* Set timings to seconds.
* Sets timings to seconds.
*/
public final void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Send the title to a player.
* Sends the title to a player.
*
* @param player Player
* @throws IllegalArgumentException
@ -157,18 +157,18 @@ public abstract class TitleManager {
public abstract void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Broadcast the title to all players.
* Broadcasts the title to all players.
*
* @throws Exception
*/
public final void broadcast() throws Exception {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
for (Player player : Bukkit.getOnlinePlayers()) {
send(player);
}
}
/**
* Clear the title.
* Clears the title.
*
* @param player Player
* @throws IllegalArgumentException
@ -178,7 +178,7 @@ public abstract class TitleManager {
public abstract void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Reset the title settings.
* Resets the title settings.
*
* @param player Player
* @throws IllegalArgumentException
@ -195,7 +195,7 @@ public abstract class TitleManager {
}
}
final Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a;
if (classes != null) {
a = classes.length;
@ -229,7 +229,7 @@ public abstract class TitleManager {
return null;
}
final boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
private boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}

View File

@ -17,14 +17,6 @@ import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.object.entity.EntityWrapper;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.DyeColor;
@ -57,6 +49,15 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class BukkitChunkManager extends ChunkManager {
public static boolean isIn(RegionWrapper region, int x, int z) {
@ -424,6 +425,10 @@ public class BukkitChunkManager extends ChunkManager {
@Override
public int[] countEntities(Plot plot) {
int[] existing = (int[]) plot.getMeta("EntityCount");
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") < 1000)) {
return existing;
}
PlotArea area = plot.getArea();
World world = BukkitUtil.getWorld(area.worldname);
@ -448,9 +453,9 @@ public class BukkitChunkManager extends ChunkManager {
boolean doWhole = false;
List<Entity> entities = null;
if (size > 200) {
if (size > 200 && chunks.size() > 200) {
entities = world.getEntities();
if (entities.size() < 16 + size * size / 64) {
if (entities.size() < 16 + size / 8) {
doWhole = true;
}
}
@ -534,6 +539,7 @@ public class BukkitChunkManager extends ChunkManager {
case PAINTING:
case ARMOR_STAND:
count[5]++;
break;
// misc
case MINECART:
case MINECART_CHEST:
@ -545,6 +551,7 @@ public class BukkitChunkManager extends ChunkManager {
case BOAT:
count[4]++;
break;
case POLAR_BEAR:
case RABBIT:
case SHEEP:
case MUSHROOM_COW:

View File

@ -1,6 +1,5 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.PS;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
@ -9,71 +8,38 @@ import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public class Metrics {
/**
* The current revision number.
*/
/** The current revision number. */
private static final int REVISION = 7;
/**
* The base url of the metrics domain.
*/
/** The base url of the metrics domain.*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status.
*/
/** The url used to report a server's status. */
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes).
*/
/** Interval of time to ping (in minutes). */
private static final int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for.
*/
/** The plugin this metrics submits for. */
private final Plugin plugin;
/**
* All of the custom graphs to submit to metrics.
*/
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/**
* Unique server id.
*/
/** Unique server id. */
private final String guid;
/**
* Debug mode.
*/
private final boolean debug;
/**
* The scheduled task.
*/
/** The scheduled task. */
private volatile BukkitTask task = null;
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
this.guid = UUID.randomUUID().toString();
this.debug = false;
}
/**
@ -186,38 +152,6 @@ public class Metrics {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned.
*
* @param name The name of the graph
*
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
Graph graph = new Graph(name);
// Now we can add our graph
this.graphs.add(graph);
// and return back
return graph;
}
/**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
*
* @param graph The name of the graph
*/
public void addGraph(Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
this.graphs.add(graph);
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
@ -244,54 +178,12 @@ public class Metrics {
this.firstPost = false;
} catch (IOException e) {
e.printStackTrace();
if (Metrics.this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*/
public void enable() {
// Enable Task, if it is not running
if (this.task == null) {
start();
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*/
public void disable() {
// Disable Task, if it is running
if (this.task != null) {
this.task.cancel();
this.task = null;
}
}
/**
* Gets the File object of the config file that should be used to store
* data such as the GUID and opt-out status.
*
* @return the File object for the config file
*/
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website.
*/
@ -342,46 +234,12 @@ public class Metrics {
if (isPing) {
appendJSONPair(json, "ping", "1");
}
if (!this.graphs.isEmpty()) {
synchronized (this.graphs) {
json.append(',');
json.append('"');
json.append("graphs");
json.append('"');
json.append(':');
json.append('{');
boolean firstGraph = true;
for (Graph graph : this.graphs) {
StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
json.append(',');
}
json.append(escapeJSON(graph.getName()));
json.append(':');
json.append(graphJson);
firstGraph = false;
}
json.append('}');
}
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
URLConnection connection = url.openConnection();
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
@ -392,9 +250,6 @@ public class Metrics {
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (this.debug) {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
try {
try (OutputStream os = connection.getOutputStream()) {
os.write(compressed);
@ -403,9 +258,6 @@ public class Metrics {
String response;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
response = reader.readLine();
if (this.debug) {
PS.debug("[Metrics] Response for " + pluginName + ": " + response);
}
}
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
@ -414,171 +266,7 @@ public class Metrics {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
// Is this the first update this hour?
if ("1".equals(response) || response.contains("This is your first update this hour")) {
synchronized (this.graphs) {
for (Graph graph : this.graphs) {
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
} catch (Exception e) {
if (this.debug) {
e.printStackTrace();
}
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (ClassNotFoundException ignored) {
return false;
}
}
/**
* Represents a custom graph on the website
*/
public static class Graph {
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
*/
private final String name;
/**
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<>();
private Graph(String name) {
this.name = name;
}
/**
* Gets the graph's name
*
* @return the Graph's name
*/
public String getName() {
return this.name;
}
/**
* Add a plotter to the graph, which will be used to plot entries
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(Plotter plotter) {
this.plotters.add(plotter);
}
/**
* Remove a plotter from the graph
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(Plotter plotter) {
this.plotters.remove(plotter);
}
/**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph
*
* @return an unmodifiable {@link Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(this.plotters);
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Graph)) {
return false;
}
Graph graph = (Graph) object;
return graph.name.equals(this.name);
}
}
/**
* Interface used to collect custom data for a plugin
*/
public abstract static class Plotter {
/**
* The plot's name
*/
private final String name;
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
this("Default");
}
/**
* Construct a plotter with a specific plot name
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(String name) {
this.name = name;
}
/**
* Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
* from any thread so care should be taken when accessing resources that need to be synchronized.
*
* @return the current value for the point to be plotted.
*/
public abstract int getValue();
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public String getColumnName() {
return this.name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {}
@Override
public int hashCode() {
return getColumnName().hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Plotter)) {
return false;
}
Plotter plotter = (Plotter) object;
return plotter.name.equals(this.name) && plotter.getValue() == getValue();
}
} catch (IOException ignored) {}
}
}

View File

@ -26,9 +26,8 @@ import java.util.HashSet;
import java.util.Map.Entry;
/**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS)
*
* An utility that can be used to send chunks, rather than using bukkit code
* to do so (uses heavy NMS).
*/
public class SendChunk {
@ -40,7 +39,7 @@ public class SendChunk {
private final RefMethod methodInitLighting;
/**
* Constructor
* Constructor.
*/
public SendChunk() throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {
RefConstructor tempMapChunk;

View File

@ -82,9 +82,10 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
if (blocksLayer != null) {
for (int j = 0; j < blocksLayer.length; j++) {
PlotBlock block = blocksLayer[j];
if (block != null) {
int x = MainUtil.x_loc[layer][j];
int y = MainUtil.y_loc[layer][j];
int z = MainUtil.y_loc[layer][j];
int z = MainUtil.z_loc[layer][j];
Block existing = chunk.getBlock(x, y, z);
int existingId = existing.getTypeId();
if (existingId == block.id) {
@ -100,6 +101,7 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
}
}
}
}
public void setBiomes(LocalChunk<T> lc) {
if (lc.biomes != null) {

View File

@ -80,8 +80,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
}
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PS.debug("&aFast mode UUID caching enabled!");
File playerDataFolder = new File(container, world + File.separator + "playerdata");
@ -97,7 +97,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
ByteSource is = com.google.common.io.Files.asByteSource(file);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PS.debug("ERROR: Player data does not contain the the key \"bukkit\"");
PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
@ -108,7 +108,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
toAdd.put(new StringWrapper(name), uuid);
}
}
} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
PS.debug(C.PREFIX + "Invalid playerdata: " + current);
}
@ -124,7 +124,6 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files");
}
}
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
HashSet<String> worlds = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
@ -164,10 +163,12 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
ByteSource is = com.google.common.io.Files.asByteSource(file);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PS.debug("ERROR: Player data does not contain the the key \"bukkit\"");
PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase().equals(name)) {
@ -181,7 +182,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
toAdd.put(new StringWrapper(name), uuid);
toAdd.put(wrap, uuid);
}
}
} catch (Exception ignored) {
PS.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
@ -199,6 +201,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
@ -207,6 +210,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
}
}
}
add(toAdd);
if (whenDone != null) {
whenDone.run();

View File

@ -2,14 +2,14 @@ package com.intellectualcrafters.configuration;
/**
* Various settings for controlling the input and output of a {@link
* Configuration}
* Configuration}.
*/
class ConfigurationOptions {
private final Configuration configuration;
private char pathSeparator = '.';
private boolean copyDefaults = false;
protected ConfigurationOptions(final Configuration configuration) {
protected ConfigurationOptions(Configuration configuration) {
this.configuration = configuration;
}
@ -24,9 +24,9 @@ class ConfigurationOptions {
/**
* Gets the char that will be used to separate {@link
* ConfigurationSection}s
* <p>
* This value does not affect how the {@link Configuration} is stored,
* ConfigurationSection}s.
*
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
*
* @return Path separator
@ -37,15 +37,15 @@ class ConfigurationOptions {
/**
* Sets the char that will be used to separate {@link
* ConfigurationSection}s
* <p>
* This value does not affect how the {@link Configuration} is stored,
* ConfigurationSection}s.
*
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
*
* @param value Path separator
* @return This object, for chaining
*/
public ConfigurationOptions pathSeparator(final char value) {
public ConfigurationOptions pathSeparator(char value) {
pathSeparator = value;
return this;
}
@ -53,8 +53,8 @@ class ConfigurationOptions {
/**
* Checks if the {@link Configuration} should copy values from its default
* {@link Configuration} directly.
* <p>
* If this is true, all values in the default Configuration will be
*
* <p>If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result,
* {@link ConfigurationSection#contains(String)} will always
@ -71,8 +71,8 @@ class ConfigurationOptions {
/**
* Sets if the {@link Configuration} should copy values from its default
* {@link Configuration} directly.
* <p>
* If this is true, all values in the default Configuration will be
*
* <p>If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result,
* {@link ConfigurationSection#contains(String)} will always
@ -83,7 +83,7 @@ class ConfigurationOptions {
* @param value Whether or not defaults are directly copied
* @return This object, for chaining
*/
public ConfigurationOptions copyDefaults(final boolean value) {
public ConfigurationOptions copyDefaults(boolean value) {
copyDefaults = value;
return this;
}

View File

@ -5,18 +5,18 @@ import java.util.Map;
import java.util.Set;
/**
* Represents a section of a {@link Configuration}
* Represents a section of a {@link Configuration}.
*/
public interface ConfigurationSection {
/**
* Gets a set containing all keys in this section.
* <p>
* If deep is set to true, then this will contain all the keys within any
*
* <p>If deep is set to true, then this will contain all the keys within any
* child {@link ConfigurationSection}s (and their children, etc). These
* will be in a valid path notation for you to use.
* <p>
* If deep is set to false, then this will contain only the keys of any
*
* <p>If deep is set to false, then this will contain only the keys of any
* direct children, and not their own children.
*
* @param deep Whether or not to get a deep list, as opposed to a shallow
@ -27,12 +27,12 @@ public interface ConfigurationSection {
/**
* Gets a Map containing all keys and their values for this section.
* <p>
* If deep is set to true, then this will contain all the keys and values
*
* <p>If deep is set to true, then this will contain all the keys and values
* within any child {@link ConfigurationSection}s (and their children,
* etc). These keys will be in a valid path notation for you to use.
* <p>
* If deep is set to false, then this will contain only the keys and
*
* <p>If deep is set to false, then this will contain only the keys and
* values of any direct children, and not their own children.
*
* @param deep Whether or not to get a deep list, as opposed to a shallow
@ -43,43 +43,44 @@ public interface ConfigurationSection {
/**
* Checks if this {@link ConfigurationSection} contains the given path.
* <p>
* If the value for the requested path does not exist but a default value
*
* <p>If the value for the requested path does not exist but a default value
* has been specified, this will return true.
*
* @param path Path to check for existence.
* @return True if this section contains the requested path, either via
* default or being set.
* @throws IllegalArgumentException Thrown when path is null.
* @throws IllegalArgumentException Thrown when path is {@code null}.
*/
boolean contains(String path);
/**
* Checks if this {@link ConfigurationSection} has a value set for the
* given path.
* <p>
* If the value for the requested path does not exist but a default value
*
* <p>If the value for the requested path does not exist but a default value
* has been specified, this will still return false.
*
* @param path Path to check for existence.
* @return True if this section contains the requested path, regardless of
* having a default.
* @throws IllegalArgumentException Thrown when path is null.
* @throws IllegalArgumentException Thrown when path is {@code null}.
*/
boolean isSet(String path);
/**
* Gets the path of this {@link ConfigurationSection} from its root {@link
* Configuration}
* <p>
* For any {@link Configuration} themselves, this will return an empty
* Configuration}.
*
* <p>For any {@link Configuration} themselves, this will return an empty
* string.
* <p>
* If the section is no longer contained within its root for any reason,
* such as being replaced with a different value, this may return null.
* <p>
* To retrieve the single name of this section, that is, the final part of
* the path returned by this method, you may use {@link #getName()}.
*
* <p>If the section is no longer contained within its root for any reason,
* such as being replaced with a different value,
* this may return {@code null}.
*
* <p>To retrieve the single name of this section, that is, the final part
* of the path returned by this method, you may use {@link #getName()}.
*
* @return Path of this section relative to its root
*/
@ -88,8 +89,8 @@ public interface ConfigurationSection {
/**
* Gets the name of this individual {@link ConfigurationSection}, in the
* path.
* <p>
* This will always be the final part of {@link #getCurrentPath()}, unless
*
* <p>This will always be the final part of {@link #getCurrentPath()}, unless
* the section is orphaned.
*
* @return Name of this section
@ -99,12 +100,13 @@ public interface ConfigurationSection {
/**
* Gets the root {@link Configuration} that contains this {@link
* ConfigurationSection}
* <p>
* For any {@link Configuration} themselves, this will return its own
*
* <p>For any {@link Configuration} themselves, this will return its own
* object.
* <p>
* If the section is no longer contained within its root for any reason,
* such as being replaced with a different value, this may return null.
*
* <p>If the section is no longer contained within its root for any reason,
* such as being replaced with a different value,
* this may return {@code null}.
*
* @return Root configuration containing this section.
*/
@ -113,11 +115,13 @@ public interface ConfigurationSection {
/**
* Gets the parent {@link ConfigurationSection} that directly contains
* this {@link ConfigurationSection}.
* <p>
* For any {@link Configuration} themselves, this will return null.
* <p>
* If the section is no longer contained within its parent for any reason,
* such as being replaced with a different value, this may return null.
*
* <p>For any {@link Configuration} themselves, this will return
* {@code null}.
*
* <p>If the section is no longer contained within its parent for any
* reason, such as being replaced with a different value, this may
* return {@code null}.
*
* @return Parent section containing this section.
*/
@ -125,10 +129,10 @@ public interface ConfigurationSection {
/**
* Gets the requested Object by path.
* <p>
* If the Object does not exist but a default value has been specified,
*
* <p>If the Object does not exist but a default value has been specified,
* this will return the default value. If the Object does not exist and no
* default value was specified, this will return null.
* default value was specified, this will return {@code null}.
*
* @param path Path of the Object to get.
* @return Requested Object.
@ -138,8 +142,8 @@ public interface ConfigurationSection {
/**
* Gets the requested Object by path, returning a default value if not
* found.
* <p>
* If the Object does not exist then the specified default value will
*
* <p>If the Object does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -151,11 +155,11 @@ public interface ConfigurationSection {
/**
* Sets the specified path to the given value.
* <p>
* If value is null, the entry will be removed. Any existing entry will be
* replaced, regardless of what the new value is.
* <p>
* Some implementations may have limitations on what you may store. See
*
* <p>If value is {@code null}, the entry will be removed. Any
* existing entry will be replaced, regardless of what the new value is.
*
* <p>Some implementations may have limitations on what you may store. See
* their individual javadoc for details. No implementations should allow
* you to store {@link Configuration}s or {@link ConfigurationSection}s,
* please use {@link #createSection(String)} for that.
@ -167,8 +171,8 @@ public interface ConfigurationSection {
/**
* Creates an empty {@link ConfigurationSection} at the specified path.
* <p>
* Any value that was previously set at this path will be overwritten. If
*
* <p>Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link ConfigurationSection}, it will
* be orphaned.
*
@ -180,8 +184,8 @@ public interface ConfigurationSection {
/**
* Creates a {@link ConfigurationSection} at the specified path, with
* specified values.
* <p>
* Any value that was previously set at this path will be overwritten. If
*
* <p>Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link ConfigurationSection}, it will
* be orphaned.
*
@ -195,10 +199,10 @@ public interface ConfigurationSection {
/**
* Gets the requested String by path.
* <p>
* If the String does not exist but a default value has been specified,
*
* <p>If the String does not exist but a default value has been specified,
* this will return the default value. If the String does not exist and no
* default value was specified, this will return null.
* default value was specified, this will return {@code null}.
*
* @param path Path of the String to get.
* @return Requested String.
@ -208,8 +212,8 @@ public interface ConfigurationSection {
/**
* Gets the requested String by path, returning a default value if not
* found.
* <p>
* If the String does not exist then the specified default value will
*
* <p>If the String does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -223,10 +227,10 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a String.
*
* <p> If the path exists but is not a String, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a String and return appropriately.</p>
* <p>If the path exists but is not a String, this will return false. If
* the path does not exist, this will return false. If the path does not
* exist but a default value has been specified, this will check if that
* defaultvalue is a String and return appropriately.
*
* @param path Path of the String to check.
* @return Whether or not the specified path is a String.
@ -238,7 +242,7 @@ public interface ConfigurationSection {
*
* <p>If the int does not exist but a default value has been specified, this
* will return the default value. If the int does not exist and no default
* value was specified, this will return 0.</p>
* value was specified, this will return 0.
*
* @param path Path of the int to get.
* @return Requested int.
@ -250,7 +254,7 @@ public interface ConfigurationSection {
*
* <p>If the int does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.</p>
* {@link Configuration}.
*
* @param path Path of the int to get.
* @param def The default value to return if the path is not found or is
@ -265,7 +269,7 @@ public interface ConfigurationSection {
* <p>If the path exists but is not a int, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a int and return appropriately.</p>
* value is a int and return appropriately.
*
* @param path Path of the int to check.
* @return Whether or not the specified path is an int.
@ -274,8 +278,8 @@ public interface ConfigurationSection {
/**
* Gets the requested boolean by path.
* <p>
* If the boolean does not exist but a default value has been specified,
*
* <p>If the boolean does not exist but a default value has been specified,
* this will return the default value. If the boolean does not exist and
* no default value was specified, this will return false.
*
@ -287,8 +291,8 @@ public interface ConfigurationSection {
/**
* Gets the requested boolean by path, returning a default value if not
* found.
* <p>
* If the boolean does not exist then the specified default value will
*
* <p>If the boolean does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -301,8 +305,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a boolean.
* <p>
* If the path exists but is not a boolean, this will return false. If the
*
* <p>If the path exists but is not a boolean, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a boolean and return appropriately.
@ -314,8 +318,8 @@ public interface ConfigurationSection {
/**
* Gets the requested double by path.
* <p>
* If the double does not exist but a default value has been specified,
*
* <p>If the double does not exist but a default value has been specified,
* this will return the default value. If the double does not exist and no
* default value was specified, this will return 0.
*
@ -327,8 +331,8 @@ public interface ConfigurationSection {
/**
* Gets the requested double by path, returning a default value if not
* found.
* <p>
* If the double does not exist then the specified default value will
*
* <p>If the double does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -341,8 +345,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a double.
* <p>
* If the path exists but is not a double, this will return false. If the
*
* <p>If the path exists but is not a double, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a double and return appropriately.
@ -354,8 +358,8 @@ public interface ConfigurationSection {
/**
* Gets the requested long by path.
* <p>
* If the long does not exist but a default value has been specified, this
*
* <p>If the long does not exist but a default value has been specified, this
* will return the default value. If the long does not exist and no
* default value was specified, this will return 0.
*
@ -367,8 +371,8 @@ public interface ConfigurationSection {
/**
* Gets the requested long by path, returning a default value if not
* found.
* <p>
* If the long does not exist then the specified default value will
*
* <p>If the long does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -381,8 +385,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a long.
* <p>
* If the path exists but is not a long, this will return false. If the
*
* <p>If the path exists but is not a long, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a long and return appropriately.
@ -396,8 +400,8 @@ public interface ConfigurationSection {
/**
* Gets the requested List by path.
* <p>
* If the List does not exist but a default value has been specified, this
*
* <p>If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return null.
*
@ -409,8 +413,8 @@ public interface ConfigurationSection {
/**
* Gets the requested List by path, returning a default value if not
* found.
* <p>
* If the List does not exist then the specified default value will
*
* <p>If the List does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -423,8 +427,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a List.
* <p>
* If the path exists but is not a List, this will return false. If the
*
* <p>If the path exists but is not a List, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a List and return appropriately.
@ -436,12 +440,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of String by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a String if possible,
*
* <p>This method will attempt to cast any values into a String if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -451,13 +455,13 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Integer by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Integer if possible,
* but may miss any values out if they are not compatible.
*
* <p>This method will attempt to cast any values into a Integer if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Integer.
@ -466,13 +470,13 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Boolean by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Boolean if possible,
* but may miss any values out if they are not compatible.
*
* <p>This method will attempt to cast any values into a Boolean if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Boolean.
@ -481,12 +485,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Double by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Double if possible,
*
* <p>This method will attempt to cast any values into a Double if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -496,12 +500,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Float by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Float if possible,
*
* <p>This method will attempt to cast any values into a Float if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -511,12 +515,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Long by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Long if possible,
*
* <p>This method will attempt to cast any values into a Long if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -526,12 +530,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Byte by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Byte if possible,
*
* <p>This method will attempt to cast any values into a Byte if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -541,12 +545,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Character by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Character if
*
* <p>This method will attempt to cast any values into a Character if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -556,13 +560,13 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Short by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Short if possible,
* but may miss any values out if they are not compatible.
*
* <p>This method will attempt to cast any values into a Short if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Short.
@ -571,13 +575,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Maps by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Map if possible, but
* may miss any values out if they are not compatible.
* <p>This method will attempt to cast any values into a Map if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Maps.
@ -586,11 +589,11 @@ public interface ConfigurationSection {
/**
* Gets the requested ConfigurationSection by path.
* <p>
* If the ConfigurationSection does not exist but a default value has been
* specified, this will return the default value. If the
*
* <p>If the ConfigurationSection does not exist but a default value has
* been specified, this will return the default value. If the
* ConfigurationSection does not exist and no default value was specified,
* this will return null.
* this will return {@code null}.
*
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection.
@ -599,8 +602,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a ConfigurationSection.
* <p>
* If the path exists but is not a ConfigurationSection, this will return
*
* <p>If the path exists but is not a ConfigurationSection, this will return
* false. If the path does not exist, this will return false. If the path
* does not exist but a default value has been specified, this will check
* if that default value is a ConfigurationSection and return
@ -614,10 +617,10 @@ public interface ConfigurationSection {
/**
* Gets the equivalent {@link ConfigurationSection} from the default
* {@link Configuration} defined in {@link #getRoot()}.
* <p>
* If the root contains no defaults, or the defaults doesn't contain a
*
* <p>If the root contains no defaults, or the defaults doesn't contain a
* value for this path, or the value at this path is not a {@link
* ConfigurationSection} then this will return null.
* ConfigurationSection} then this will return {@code null}.
*
* @return Equivalent section in root configuration
*/
@ -625,21 +628,21 @@ public interface ConfigurationSection {
/**
* Sets the default value in the root at the given path as provided.
* <p>
* If no source {@link Configuration} was provided as a default
*
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
* <p>
* If value is null, the value will be removed from the default
* Configuration source.
* <p>
* If the value as returned by {@link #getDefaultSection()} is null, then
* this will create a new section at the path, replacing anything that may
* have existed there previously.
*
* @param path Path of the value to set.
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
* <p>If value is {@code null}, the value will be removed from the
* default Configuration source.
*
* <p>If the value as returned by {@link #getDefaultSection()} is
* {@code null}, then this will create a new section at the path,
* replacing anything that may have existed there previously.
*
* @param path Path of the value to set
* @param value Value to set the default to
* @throws IllegalArgumentException Thrown if path is {@code null}
*/
void addDefault(String path, Object value);
}

View File

@ -1,7 +1,7 @@
package com.intellectualcrafters.configuration;
/**
* Exception thrown when attempting to load an invalid {@link Configuration}
* Exception thrown when attempting to load an invalid {@link Configuration}.
*/
@SuppressWarnings("serial")
public class InvalidConfigurationException extends Exception {
@ -18,7 +18,7 @@ public class InvalidConfigurationException extends Exception {
*
* @param msg The details of the exception.
*/
public InvalidConfigurationException(final String msg) {
public InvalidConfigurationException(String msg) {
super(msg);
}
@ -28,7 +28,7 @@ public class InvalidConfigurationException extends Exception {
*
* @param cause The cause of the exception.
*/
public InvalidConfigurationException(final Throwable cause) {
public InvalidConfigurationException(Throwable cause) {
super(cause);
}
@ -39,7 +39,7 @@ public class InvalidConfigurationException extends Exception {
* @param cause The cause of the exception.
* @param msg The details of the exception.
*/
public InvalidConfigurationException(final String msg, final Throwable cause) {
public InvalidConfigurationException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -2,10 +2,10 @@ package com.intellectualcrafters.configuration;
/**
* Various settings for controlling the input and output of a {@link
* MemoryConfiguration}
* MemoryConfiguration}.
*/
public class MemoryConfigurationOptions extends ConfigurationOptions {
protected MemoryConfigurationOptions(final MemoryConfiguration configuration) {
protected MemoryConfigurationOptions(MemoryConfiguration configuration) {
super(configuration);
}
@ -15,13 +15,13 @@ public class MemoryConfigurationOptions extends ConfigurationOptions {
}
@Override
public MemoryConfigurationOptions copyDefaults(final boolean value) {
public MemoryConfigurationOptions copyDefaults(boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public MemoryConfigurationOptions pathSeparator(final char value) {
public MemoryConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}

View File

@ -21,8 +21,8 @@ public class MemorySection implements ConfigurationSection {
/**
* Creates an empty MemorySection for use as a root {@link Configuration}
* section.
* <p>
* Note that calling this without being yourself a {@link Configuration}
*
* <p>Note that calling this without being yourself a {@link Configuration}
* will throw an exception!
*
* @throws IllegalStateException Thrown if this is not a {@link
@ -74,7 +74,8 @@ public class MemorySection implements ConfigurationSection {
if (obj instanceof String) {
try {
return Double.parseDouble((String) obj);
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (obj instanceof List) {
List<?> val = (List<?>) obj;
if (!val.isEmpty()) {
@ -91,7 +92,8 @@ public class MemorySection implements ConfigurationSection {
if (obj instanceof String) {
try {
return Integer.parseInt((String) obj);
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (obj instanceof List) {
List<?> val = (List<?>) obj;
if (!val.isEmpty()) {
@ -108,7 +110,8 @@ public class MemorySection implements ConfigurationSection {
if (obj instanceof String) {
try {
return Long.parseLong((String) obj);
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (obj instanceof List) {
List<?> val = (List<?>) obj;
if (!val.isEmpty()) {
@ -121,8 +124,8 @@ public class MemorySection implements ConfigurationSection {
/**
* Creates a full path to the given {@link ConfigurationSection} from its
* root {@link Configuration}.
* <p>
* You may use this method for any given {@link ConfigurationSection}, not
*
* <p>You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}.
*
* @param section Section to create a path for.
@ -136,8 +139,8 @@ public class MemorySection implements ConfigurationSection {
/**
* Creates a relative path to the given {@link ConfigurationSection} from
* the given relative section.
* <p>
* You may use this method for any given {@link ConfigurationSection}, not
*
* <p>You may use this method for any given {@link ConfigurationSection}, not
* only {@link MemorySection}.
*
* @param section Section to create a path for.
@ -292,7 +295,8 @@ public class MemorySection implements ConfigurationSection {
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
int i1 = -1;
int i2;
ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
String node = path.substring(i2, i1);
@ -374,7 +378,8 @@ public class MemorySection implements ConfigurationSection {
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
int i1 = -1;
int i2;
ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
String node = path.substring(i2, i1);
@ -563,7 +568,8 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) {
try {
result.add(Integer.valueOf((String) object));
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (object instanceof Character) {
result.add((int) (Character) object);
} else if (object instanceof Number) {
@ -607,7 +613,8 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) {
try {
result.add(Double.valueOf((String) object));
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (object instanceof Character) {
result.add((double) (Character) object);
} else if (object instanceof Number) {
@ -630,7 +637,8 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) {
try {
result.add(Float.valueOf((String) object));
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (object instanceof Character) {
result.add((float) (Character) object);
} else if (object instanceof Number) {
@ -653,7 +661,8 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) {
try {
result.add(Long.valueOf((String) object));
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (object instanceof Character) {
result.add((long) (Character) object);
} else if (object instanceof Number) {
@ -676,7 +685,8 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) {
try {
result.add(Byte.valueOf((String) object));
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (object instanceof Character) {
result.add((byte) ((Character) object).charValue());
} else if (object instanceof Number) {
@ -722,7 +732,8 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) {
try {
result.add(Short.valueOf((String) object));
} catch (NumberFormatException ignored) {}
} catch (NumberFormatException ignored) {
}
} else if (object instanceof Character) {
result.add((short) ((Character) object).charValue());
} else if (object instanceof Number) {
@ -831,7 +842,10 @@ public class MemorySection implements ConfigurationSection {
@Override
public String toString() {
Configuration root = getRoot();
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + (root == null ? null : root.getClass().getSimpleName()) +
"']";
if (root == null) {
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null + "']";
} else {
return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root.getClass().getSimpleName() + "']";
}
}
}

View File

@ -18,7 +18,7 @@ import java.nio.charset.StandardCharsets;
/**
* This is a base class for all File based implementations of {@link
* Configuration}
* Configuration}.
*/
public abstract class FileConfiguration extends MemoryConfiguration {
@ -39,18 +39,17 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Saves this {@link FileConfiguration} to the specified location.
* <p>
* If the file does not exist, it will be created. If already exists, it
*
* <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
* exception will be thrown.
* <p>
* This method will save using the system default encoding, or possibly
*
* <p>This method will save using the system default encoding, or possibly
* using UTF8.
*
* @param file File to save to.
* @throws IOException Thrown when the given file cannot be written to for
* any reason.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void save(File file) throws IOException {
file.getParentFile().mkdirs();
@ -71,14 +70,13 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified location.
* <p>
* All the values contained within this configuration will be removed,
*
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given file.
* <p>
* If the file cannot be loaded for any reason, an exception will be
*
* <p>If the file cannot be loaded for any reason, an exception will be
* thrown.
* <p>
*
* @param file File to load from.
* @throws FileNotFoundException Thrown when the given file cannot be
@ -100,8 +98,8 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified reader.
* <p>
* All the values contained within this configuration will be removed,
*
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given stream.
*
@ -109,7 +107,6 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* @throws IOException thrown when underlying reader throws an IOException
* @throws InvalidConfigurationException thrown when the reader does not
* represent a valid Configuration
* @throws IllegalArgumentException thrown when reader is null
*/
public void load(Reader reader) throws IOException, InvalidConfigurationException {
@ -129,12 +126,12 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified location.
* <p>
* All the values contained within this configuration will be removed,
*
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given file.
* <p>
* If the file cannot be loaded for any reason, an exception will be
*
* <p>If the file cannot be loaded for any reason, an exception will be
* thrown.
*
* @param file File to load from.
@ -156,25 +153,24 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/**
* Loads this {@link FileConfiguration} from the specified string, as
* opposed to from file.
* <p>
* All the values contained within this configuration will be removed,
*
* <p>All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given string.
* <p>
* If the string is invalid in any way, an exception will be thrown.
*
* <p>If the string is invalid in any way, an exception will be thrown.
*
* @param contents Contents of a Configuration to load.
* @throws InvalidConfigurationException Thrown if the specified string is
* invalid.
* @throws IllegalArgumentException Thrown if contents is null.
*/
public abstract void loadFromString(String contents) throws InvalidConfigurationException;
/**
* Compiles the header for this {@link FileConfiguration} and returns the
* result.
* <p>
* This will use the header from {@link #options()} -> {@link
*
* <p>This will use the header from {@link #options()} -> {@link
* FileConfigurationOptions#header()}, respecting the rules of {@link
* FileConfigurationOptions#copyHeader()} if set.
*

View File

@ -6,13 +6,13 @@ import com.intellectualcrafters.configuration.MemoryConfigurationOptions;
/**
* Various settings for controlling the input and output of a {@link
* FileConfiguration}
* FileConfiguration}.
*/
public class FileConfigurationOptions extends MemoryConfigurationOptions {
private String header = null;
private boolean copyHeader = true;
protected FileConfigurationOptions(final MemoryConfiguration configuration) {
protected FileConfigurationOptions(MemoryConfiguration configuration) {
super(configuration);
}
@ -22,28 +22,28 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
}
@Override
public FileConfigurationOptions copyDefaults(final boolean value) {
public FileConfigurationOptions copyDefaults(boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public FileConfigurationOptions pathSeparator(final char value) {
public FileConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}
/**
* Gets the header that will be applied to the top of the saved output.
* <p>
* This header will be commented out and applied directly at the top of
*
* <p>This header will be commented out and applied directly at the top of
* the generated output of the {@link FileConfiguration}. It is not
* required to include a newline at the end of the header as it will
* automatically be applied, but you may include one if you wish for extra
* spacing.
* <p>
* Null is a valid value which will indicate that no header is to be
* applied. The default value is null.
*
* <p>{@code null} is a valid value which will indicate that no header]
* is to be applied. The default value is {@code null}.
*
* @return Header
*/
@ -53,39 +53,38 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
/**
* Sets the header that will be applied to the top of the saved output.
* <p>
* This header will be commented out and applied directly at the top of
*
* <p>This header will be commented out and applied directly at the top of
* the generated output of the {@link FileConfiguration}. It is not
* required to include a newline at the end of the header as it will
* automatically be applied, but you may include one if you wish for extra
* spacing.
* <p>
* Null is a valid value which will indicate that no header is to be
* applied.
*
* <p>{@code null} is a valid value which will indicate that no header
* is to be applied.
*
* @param value New header
* @return This object, for chaining
*/
public FileConfigurationOptions header(final String value) {
public FileConfigurationOptions header(String value) {
header = value;
return this;
}
/**
* Gets whether or not the header should be copied from a default source.
* <p>
* If this is true, if a default {@link FileConfiguration} is passed to
* {@link
* FileConfiguration#setDefaults(Configuration)}
*
* <p>If this is true, if a default {@link FileConfiguration} is passed to
* {@link FileConfiguration#setDefaults(Configuration)}
* then upon saving it will use the header from that config, instead of
* the one provided here.
* <p>
* If no default is set on the configuration, or the default is not of
*
* <p>If no default is set on the configuration, or the default is not of
* type FileConfiguration, or that config has no header ({@link #header()}
* returns null) then the header specified in this configuration will be
* used.
* <p>
* Defaults to true.
*
* <p>Defaults to true.
*
* @return Whether or not to copy the header
*/
@ -95,24 +94,23 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
/**
* Sets whether or not the header should be copied from a default source.
* <p>
* If this is true, if a default {@link FileConfiguration} is passed to
* {@link
* FileConfiguration#setDefaults(Configuration)}
*
* <p>If this is true, if a default {@link FileConfiguration} is passed to
* {@link FileConfiguration#setDefaults(Configuration)}
* then upon saving it will use the header from that config, instead of
* the one provided here.
* <p>
* If no default is set on the configuration, or the default is not of
*
* <p>If no default is set on the configuration, or the default is not of
* type FileConfiguration, or that config has no header ({@link #header()}
* returns null) then the header specified in this configuration will be
* used.
* <p>
* Defaults to true.
*
* <p>Defaults to true.
*
* @param value Whether or not to copy the header
* @return This object, for chaining
*/
public FileConfigurationOptions copyHeader(final boolean value) {
public FileConfigurationOptions copyHeader(boolean value) {
copyHeader = value;
return this;

View File

@ -29,12 +29,12 @@ public class YamlConfiguration extends FileConfiguration {
/**
* Creates a new {@link YamlConfiguration}, loading from the given file.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
*
* <p>Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
* <p>
* The encoding used may follow the system dependent default.
*
* <p>The encoding used may follow the system dependent default.
*
* @param file Input file
* @return Resulting configuration
@ -45,7 +45,7 @@ public class YamlConfiguration extends FileConfiguration {
throw new NullPointerException("File cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
YamlConfiguration config = new YamlConfiguration();
try {
config.load(file);
@ -62,7 +62,7 @@ public class YamlConfiguration extends FileConfiguration {
PS.debug("&c============ Full stacktrace ============");
ex.printStackTrace();
PS.debug("&c=========================================");
} catch (final IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
@ -72,8 +72,8 @@ public class YamlConfiguration extends FileConfiguration {
/**
* Creates a new {@link YamlConfiguration}, loading from the given reader.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
*
* <p>Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
*
@ -81,16 +81,16 @@ public class YamlConfiguration extends FileConfiguration {
* @return resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
*/
public static YamlConfiguration loadConfiguration(final Reader reader) {
public static YamlConfiguration loadConfiguration(Reader reader) {
if (reader == null) {
throw new NullPointerException("Reader cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
YamlConfiguration config = new YamlConfiguration();
try {
config.load(reader);
} catch (final IOException | InvalidConfigurationException ex) {
} catch (IOException | InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
}
@ -104,7 +104,7 @@ public class YamlConfiguration extends FileConfiguration {
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final String header = buildHeader();
String header = buildHeader();
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
@ -115,7 +115,7 @@ public class YamlConfiguration extends FileConfiguration {
}
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
public void loadFromString(String contents) throws InvalidConfigurationException {
if (contents == null) {
throw new NullPointerException("Contents cannot be null");
}
@ -123,13 +123,13 @@ public class YamlConfiguration extends FileConfiguration {
Map<?, ?> input;
try {
input = (Map<?, ?>) yaml.load(contents);
} catch (final YAMLException e) {
} catch (YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (final ClassCastException ignored) {
} catch (ClassCastException ignored) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
final String header = parseHeader(contents);
String header = parseHeader(contents);
if (!header.isEmpty()) {
options().header(header);
}
@ -139,10 +139,10 @@ public class YamlConfiguration extends FileConfiguration {
}
}
protected void convertMapsToSections(final Map<?, ?> input, final ConfigurationSection section) {
for (final Map.Entry<?, ?> entry : input.entrySet()) {
final String key = entry.getKey().toString();
final Object value = entry.getValue();
protected void convertMapsToSections(Map<?, ?> input, ConfigurationSection section) {
for (Map.Entry<?, ?> entry : input.entrySet()) {
String key = entry.getKey().toString();
Object value = entry.getValue();
if (value instanceof Map) {
convertMapsToSections((Map<?, ?>) value, section.createSection(key));
@ -152,14 +152,14 @@ public class YamlConfiguration extends FileConfiguration {
}
}
protected String parseHeader(final String input) {
final String[] lines = input.split("\r?\n", -1);
final StringBuilder result = new StringBuilder();
protected String parseHeader(String input) {
String[] lines = input.split("\r?\n", -1);
StringBuilder result = new StringBuilder();
boolean readingHeader = true;
boolean foundHeader = false;
for (int i = 0; (i < lines.length) && readingHeader; i++) {
final String line = lines[i];
String line = lines[i];
if (line.startsWith(COMMENT_PREFIX)) {
if (i > 0) {
@ -183,14 +183,14 @@ public class YamlConfiguration extends FileConfiguration {
@Override
protected String buildHeader() {
final String header = options().header();
String header = options().header();
if (options().copyHeader()) {
final Configuration def = getDefaults();
Configuration def = getDefaults();
if (def instanceof FileConfiguration) {
final FileConfiguration fileDefaults = (FileConfiguration) def;
final String defaultsHeader = fileDefaults.buildHeader();
FileConfiguration fileDefaults = (FileConfiguration) def;
String defaultsHeader = fileDefaults.buildHeader();
if ((defaultsHeader != null) && !defaultsHeader.isEmpty()) {
return defaultsHeader;
@ -202,8 +202,8 @@ public class YamlConfiguration extends FileConfiguration {
return "";
}
final StringBuilder builder = new StringBuilder();
final String[] lines = header.split("\r?\n", -1);
StringBuilder builder = new StringBuilder();
String[] lines = header.split("\r?\n", -1);
boolean startedHeader = false;
for (int i = lines.length - 1; i >= 0; i--) {

View File

@ -2,12 +2,12 @@ package com.intellectualcrafters.configuration.file;
/**
* Various settings for controlling the input and output of a {@link
* YamlConfiguration}
* YamlConfiguration}.
*/
public class YamlConfigurationOptions extends FileConfigurationOptions {
private int indent = 2;
YamlConfigurationOptions(final YamlConfiguration configuration) {
YamlConfigurationOptions(YamlConfiguration configuration) {
super(configuration);
}
@ -17,33 +17,33 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
}
@Override
public YamlConfigurationOptions copyDefaults(final boolean value) {
public YamlConfigurationOptions copyDefaults(boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public YamlConfigurationOptions pathSeparator(final char value) {
public YamlConfigurationOptions pathSeparator(char value) {
super.pathSeparator(value);
return this;
}
@Override
public YamlConfigurationOptions header(final String value) {
public YamlConfigurationOptions header(String value) {
super.header(value);
return this;
}
@Override
public YamlConfigurationOptions copyHeader(final boolean value) {
public YamlConfigurationOptions copyHeader(boolean value) {
super.copyHeader(value);
return this;
}
/**
* Gets how much spaces should be used to indent each line.
* <p>
* The minimum value this may be is 2, and the maximum is 9.
*
* <p>The minimum value this may be is 2, and the maximum is 9.
*
* @return How much to indent by
*/
@ -53,13 +53,13 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
/**
* Sets how much spaces should be used to indent each line.
* <p>
* The minimum value this may be is 2, and the maximum is 9.
*
* <p>The minimum value this may be is 2, and the maximum is 9.
*
* @param value New indent
* @return This object, for chaining
*/
public YamlConfigurationOptions indent(final int value) {
public YamlConfigurationOptions indent(int value) {
if (value < 2) {
throw new IllegalArgumentException("Indent must be at least 2 characters");
}

View File

@ -11,7 +11,7 @@ import java.util.Map;
class YamlRepresenter extends Representer {
public YamlRepresenter() {
YamlRepresenter() {
this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection());
this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
}

View File

@ -4,9 +4,8 @@ import java.util.Map;
/**
* Represents an object that may be serialized.
* <p>
* These objects MUST implement one of the following, in addition to the
* methods as defined by this interface:
* <p>These objects MUST implement one of the following, in addition to
* the methods as defined by this interface:
* <ul>
* <li>A static method "deserialize" that accepts a single {@link Map}&lt;
* {@link String}, {@link Object}> and returns the class.</li>
@ -25,8 +24,8 @@ public interface ConfigurationSerializable {
/**
* Creates a Map representation of this class.
* <p>
* This class must provide a method to restore this class, as defined in
*
* <p>This class must provide a method to restore this class, as defined in
* the {@link ConfigurationSerializable} interface javadoc.
*
* @return Map containing the current state of this class

View File

@ -7,10 +7,11 @@ import java.io.OutputStream;
import java.util.List;
/**
* <p> This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong> <code>Tag</code> objects to an
* underlying <code>OutputStream</code>. </p> <p> The NBT format was created by Markus Persson, and the
* specification may be found at
* @linktourl http://www.minecraft.net/docs/NBT.txt
* This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* {@code Tag} objects to an underlying {@code OutputStream}.
*
* <p> The NBT format was created by Markus Persson, and the specification may
* be found at @linktourl http://www.minecraft.net/docs/NBT.txt
* </p>
*
* @author Graham Edgecombe
@ -23,7 +24,8 @@ public final class NBTOutputStream implements Closeable {
private final DataOutputStream os;
/**
* Creates a new <code>NBTOutputStream</code>, which will write data to the specified underlying output stream.
* Creates a new {@code NBTOutputStream}, which will write data to the
* specified underlying output stream.
*
* @param os The output stream.
*
@ -105,7 +107,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Byte</code> tag.
* Writes a {@code TAG_Byte} tag.
*
* @param tag The tag.
*
@ -116,7 +118,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Byte_Array</code> tag.
* Writes a {@code TAG_Byte_Array} tag.
*
* @param tag The tag.
*
@ -129,7 +131,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Compound</code> tag.
* Writes a {@code TAG_Compound} tag.
*
* @param tag The tag.
*
@ -143,7 +145,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_List</code> tag.
* Writes a {@code TAG_List} tag.
*
* @param tag The tag.
*
@ -161,7 +163,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_String</code> tag.
* Writes a {@code TAG_String} tag.
*
* @param tag The tag.
*
@ -174,7 +176,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Double</code> tag.
* Writes a {@code TAG_Double} tag.
*
* @param tag The tag.
*
@ -185,7 +187,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Float</code> tag.
* Writes a {@code TAG_Float} tag.
*
* @param tag The tag.
*
@ -196,7 +198,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Long</code> tag.
* Writes a {@code TAG_Long} tag.
*
* @param tag The tag.
*
@ -207,7 +209,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Int</code> tag.
* Writes a {@code TAG_Int} tag.
*
* @param tag The tag.
*
@ -218,7 +220,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Short</code> tag.
* Writes a {@code TAG_Short} tag.
*
* @param tag The tag.
*
@ -229,7 +231,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Writes a <code>TAG_Empty</code> tag.
* Writes a {@code TAG_Empty} tag.
*
* @param tag The tag.
*/
@ -251,7 +253,7 @@ public final class NBTOutputStream implements Closeable {
}
/**
* Flush output
* Flush output.
* @throws IOException
*/
public void flush() throws IOException {

View File

@ -107,9 +107,9 @@ public class Cookie {
}
/**
* Convert <code>%</code><i>hh</i> sequences to single characters, and convert plus to space.
* Convert {@code %}<i>hh</i> sequences to single characters, and convert plus to space.
*
* @param string A string that may contain <code>+</code> &nbsp;<small>(plus)</small> and <code>%</code><i>hh</i>
* @param string A string that may contain {@code +} &nbsp;<small>(plus)</small> and <code>%</code><i>hh</i>
* sequences.
*
* @return The unescaped string.

View File

@ -10,28 +10,28 @@ import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with
* commas separating the values. The internal form is an object having <code>get</code> and <code>opt</code> methods for
* accessing the values by index, and <code>put</code> methods for adding or replacing values. The values can be any of
* these types: <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>,
* <code>String</code>, or the <code>JSONObject.NULL object</code>.
* commas separating the values. The internal form is an object having {@code get} and {@code opt} methods for
* accessing the values by index, and {@code put} methods for adding or replacing values. The values can be any of
* these types: {@code Boolean}, {@code JSONArray}, {@code JSONObject}, {@code Number},
* {@code String}, or the {@code JSONObject.NULL object}.
*
* The constructor can convert a JSON text into a Java object. The <code>toString</code> method converts to JSON text.
* <p>The constructor can convert a JSON text into a Java object. The {@code toString} method converts to JSON text.
*
* A <code>get</code> method returns a value if one can be found, and throws an exception if one cannot be found. An
* <code>opt</code> method returns a default value instead of throwing an exception, and so is useful for obtaining
* <p>A {@code get} method returns a value if one can be found, and throws an exception if one cannot be found. An
* {@code opt} method returns a default value instead of throwing an exception, and so is useful for obtaining
* optional values.
*
* The generic <code>get()</code> and <code>opt()</code> methods return an object which you can cast or query for type.
* There are also typed <code>get</code> and <code>opt</code> methods that do type checking and type coercion for you.
* <p>The generic {@code get()} and {@code opt()} methods return an object which you can cast or query for type.
* There are also typed {@code get} and {@code opt} methods that do type checking and type coercion for you.
*
* The texts produced by the <code>toString</code> methods strictly conform to JSON syntax rules. The constructors are
* more forgiving in the texts they will accept: <ul> <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear
* just before the closing bracket.</li> <li>The <code>null</code> value will be inserted when there is <code>,</code>
* &nbsp;<small>(comma)</small> elision.</li> <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
* <p>The texts produced by the {@code toString} methods strictly conform to JSON syntax rules. The constructors are
* more forgiving in the texts they will accept: <ul> <li>An extra {@code ,}&nbsp;<small>(comma)</small> may appear
* just before the closing bracket.</li> <li>The {@code null} value will be inserted when there is {@code ,}
* &nbsp;<small>(comma)</small> elision.</li> <li>Strings may be quoted with {@code '}&nbsp;<small>(single
* quote)</small>.</li> <li>Strings do not need to be quoted at all if they do not begin with a quote or single quote,
* and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: <code>{ }
* [ ] / \ : , #</code> and if they do not look like numbers and if they are not the reserved words <code>true</code>,
* <code>false</code>, or <code>null</code>.</li> </ul>
* and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: {@code { }
* [ ] / \ : , #} and if they do not look like numbers and if they are not the reserved words {@code true},
* {@code false}, or {@code null}.</li> </ul>
*
* @author JSON.org
* @version 2014-05-03
@ -90,8 +90,8 @@ public class JSONArray {
/**
* Construct a JSONArray from a source JSON text.
*
* @param source A string that begins with <code>[</code>&nbsp;<small>(left bracket)</small> and ends with
* <code>]</code> &nbsp;<small>(right bracket)</small>.
* @param source A string that begins with {@code [}&nbsp;<small>(left bracket)</small> and ends with
* {@code ]} &nbsp;<small>(right bracket)</small>.
*
* @throws JSONException If there is a syntax error.
*/
@ -283,7 +283,7 @@ public class JSONArray {
}
/**
* Make a string from the contents of this JSONArray. The <code>separator</code> string is inserted between each
* Make a string from the contents of this JSONArray. The {@code separator} string is inserted between each
* element. Warning: This method assumes that the data structure is acyclical.
*
* @param separator A string that will be inserted between the elements.
@ -449,8 +449,9 @@ public class JSONArray {
}
/**
* Get the optional long value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number.
* Get the optional long value associated with an index. The defaultValue
* is returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
@ -466,8 +467,9 @@ public class JSONArray {
}
/**
* Get the optional string value associated with an index. It returns an empty string if there is no value at that
* index. If the value is not a string and is not null, then it is converted to a string.
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value is not a
* string and is not null, then it is converted to a string.
*
* @param index The index must be between 0 and length() - 1.
*
@ -478,7 +480,8 @@ public class JSONArray {
}
/**
* Get the optional string associated with an index. The defaultValue is returned if the key is not found.
* Get the optional string associated with an index. The defaultValue is
* returned if the key is not found.
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
@ -503,7 +506,8 @@ public class JSONArray {
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param value A Collection value.
*
@ -555,7 +559,8 @@ public class JSONArray {
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param value A Map value.
*
@ -569,8 +574,8 @@ public class JSONArray {
/**
* Append an object value. This increases the array's length by one.
*
* @param value An object value. The value should be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or
* String, or the JSONObject.NULL object.
* @param value An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
*
* @return this.
*/
@ -596,14 +601,16 @@ public class JSONArray {
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param index The subscript.
* @param value A Collection value.
*
* @return this.
*
* @throws JSONException If the index is negative or if the value is not finite.
* @throws JSONException If the index is negative or if the value is not
* finite.
*/
public JSONArray put(int index, Collection<Object> value) throws JSONException {
this.put(index, new JSONArray(value));
@ -611,15 +618,17 @@ public class JSONArray {
}
/**
* Put or replace a double value. If the index is greater than the length of the JSONArray, then null elements will
* be added as necessary to pad it out.
* Put or replace a double value. If the index is greater than the length
* of the JSONArray, then null elements will be added as necessary to pad
* it out.
*
* @param index The subscript.
* @param value A double value.
*
* @return this.
*
* @throws JSONException If the index is negative or if the value is not finite.
* @throws JSONException If the index is negative or if the value is not
* finite.
*/
public JSONArray put(int index, double value) throws JSONException {
this.put(index, new Double(value));
@ -659,14 +668,16 @@ public class JSONArray {
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject that is produced from a Map.
* Put a value in the JSONArray, where the value will be a JSONObject that
* is produced from a Map.
*
* @param index The subscript.
* @param value The Map value.
*
* @return this.
*
* @throws JSONException If the index is negative or if the the value is an invalid number.
* @throws JSONException If the index is negative or if the the value is an
* invalid number.
*/
public JSONArray put(int index, Map<String, Object> value) throws JSONException {
this.put(index, new JSONObject(value));
@ -790,7 +801,7 @@ public class JSONArray {
* @param indentFactor The number of spaces to add to each level of indentation.
*
* @return a printable, displayable, transmittable representation of the object, beginning with
* <code>[</code>&nbsp;<small>(left bracket)</small> and ending with <code>]</code> &nbsp;<small>(right
* {@code [}&nbsp;<small>(left bracket)</small> and ending with {@code ]} &nbsp;<small>(right
* bracket)</small>.
*
* @throws JSONException

View File

@ -17,6 +17,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.block.QueueProvider;
import java.io.File;
import java.util.List;
@ -51,17 +52,23 @@ public interface IPlotMain extends ILogger {
* Disable the implementation.
*
* <ul>
* <li>If a full disable isn't feasibly, just disable what it can.</li>
* <li>If a full disable isn't feasibly, just disable what it can.
* </ul>
*/
void disable();
/**
* Get the version of the PlotSquared being used.
* @return
* @return the plugin version
*/
int[] getPluginVersion();
/**
* Get the version of the PlotSquared being used as a string.
* @return the plugin version as a string
*/
String getPluginVersionString();
/**
* Get the version of Minecraft that is running.
* @return
@ -229,12 +236,6 @@ public interface IPlotMain extends ILogger {
*/
void registerWorldEvents();
/**
* Get the name of the server.
* @return The server name
*/
String getServerName();
/**
* Get the class that will manage player titles.
* @return

View File

@ -171,7 +171,6 @@ public class PS {
this.IMP.registerPlayerEvents();
this.IMP.registerInventoryEvents();
this.IMP.registerPlotPlusEvents();
this.IMP.registerForceFieldEvents();
}
// Required
this.IMP.registerWorldEvents();
@ -370,13 +369,16 @@ public class PS {
@Override
public void run() {
UUIDHandler.add(new StringWrapper("*"), DBFunc.everyone);
for (Plot plot : getPlots()) {
foreachPlotRaw(new RunnableVal<Plot>() {
@Override
public void run(Plot plot) {
if (plot.hasOwner() && plot.temp != -1) {
if (UUIDHandler.getName(plot.owner) == null) {
UUIDHandler.implementation.unknown.add(plot.owner);
}
}
}
});
startExpiryTasks();
startPlotMeConversion();
}
@ -726,6 +728,7 @@ public class PS {
this.plotAreaGrid.put(plotArea.worldname, map);
}
map.add(plotArea);
plotArea.setupBorder();
}
/**
@ -1077,14 +1080,15 @@ public class PS {
public void run(PlotArea value) {
for (PlotFilter filter : filters) {
if (!filter.allowsArea(value)) {
continue;
return;
}
}
loop:
for (Entry<PlotId, Plot> entry2 : value.getPlotEntries()) {
Plot plot = entry2.getValue();
for (PlotFilter filter : filters) {
if (!filter.allowsPlot(plot)) {
continue;
continue loop;
}
}
set.add(plot);
@ -1445,7 +1449,6 @@ public class PS {
// Now add it
addPlotArea(plotArea);
plotGenerator.initialize(plotArea);
plotArea.setupBorder();
} else {
if (!worlds.contains(world)) {
return;

View File

@ -0,0 +1,9 @@
package com.intellectualcrafters.plot;
public enum Platform {
Bukkit,
Sponge,
Spigot,
Cauldron
}

View File

@ -1,5 +1,7 @@
package com.intellectualcrafters.plot;
import static com.intellectualcrafters.plot.PS.log;
import com.intellectualcrafters.json.JSONArray;
import com.intellectualcrafters.json.JSONObject;
import com.intellectualcrafters.plot.util.HttpUtil;
@ -7,8 +9,7 @@ import com.intellectualcrafters.plot.util.StringMan;
import java.net.MalformedURLException;
import java.net.URL;
import static com.intellectualcrafters.plot.PS.log;
import java.util.Arrays;
public class Updater {
@ -31,9 +32,11 @@ public class Updater {
}
// If current version >= update
if (PS.get().checkVersion(PS.get().getVersion(), version)) {
if (!PS.get().IMP.getPluginVersionString().contains("-SNAPSHOT") || !Arrays.equals(PS.get().getVersion(), version)) {
PS.debug("&7PlotSquared is already up to date!");
return null;
}
}
log("&6PlotSquared " + StringMan.join(split, ".") + " is available:");
log("&8 - &3Use: &7/plot update");
log("&8 - &3Or: &7" + downloadURL);

View File

@ -23,7 +23,7 @@ import java.util.UUID;
usage = "/plot add <player>",
category = CommandCategory.SETTINGS,
permission = "plots.add",
requiredType = RequiredType.PLAYER)
requiredType = RequiredType.NONE)
public class Add extends Command {
public Add() {

View File

@ -118,7 +118,7 @@ public class Auto extends SubCommand {
}
if (EconHandler.manager != null && plotarea.USE_ECONOMY) {
Expression<Double> costExp = plotarea.PRICES.get("claim");
double cost = costExp.evalute((double) currentPlots);
double cost = costExp.evaluate((double) currentPlots);
cost = (size_x * size_z) * cost;
if (cost > 0d) {
if (EconHandler.manager.getMoney(player) < cost) {

View File

@ -12,6 +12,7 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.Set;
@CommandDeclaration(
@ -43,7 +44,9 @@ public class Buy extends Command {
Set<Plot> plots = plot.getConnectedPlots();
checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(), C.CANT_CLAIM_MORE_PLOTS);
Optional<Double> flag = plot.getFlag(Flags.PRICE);
checkTrue(flag.isPresent(), C.NOT_FOR_SALE);
if (!flag.isPresent()) {
throw new CommandException(C.NOT_FOR_SALE);
}
final double price = flag.get();
checkTrue(player.getMoney() >= price, C.CANNOT_AFFORD_PLOT);
player.withdraw(price);

View File

@ -16,7 +16,7 @@ import com.plotsquared.general.commands.CommandDeclaration;
aliases = "c",
description = "Claim the current plot you're standing on",
category = CommandCategory.CLAIMING,
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
permission = "plots.claim", usage = "/plot claim")
public class Claim extends SubCommand {
@ -50,7 +50,7 @@ public class Claim extends SubCommand {
PlotArea world = plot.getArea();
if ((EconHandler.manager != null) && world.USE_ECONOMY) {
Expression<Double> costExr = world.PRICES.get("claim");
double cost = costExr.evalute((double) currentPlots);
double cost = costExr.evaluate((double) currentPlots);
if (cost > 0d) {
if (EconHandler.manager.getMoney(player) < cost) {
return sendMessage(player, C.CANNOT_AFFORD_PLOT, "" + cost);

View File

@ -84,6 +84,9 @@ public class DebugExec extends SubCommand {
}
public ScriptEngine getEngine() {
if (this.engine == null) {
init();
}
return this.engine;
}

View File

@ -56,7 +56,7 @@ public class Delete extends SubCommand {
plot.removeRunning();
if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) {
Expression<Double> valueExr = plotArea.PRICES.get("sell");
double value = plots.size() * valueExr.evalute((double) currentPlots);
double value = plots.size() * valueExr.evaluate((double) currentPlots);
if (value > 0d) {
EconHandler.manager.depositMoney(player, value);
sendMessage(player, C.ADDED_BALANCE, String.valueOf(value));

View File

@ -23,7 +23,7 @@ import java.util.UUID;
description = "Deny a user from a plot",
usage = "/plot deny <player>",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.PLAYER)
requiredType = RequiredType.NONE)
public class Deny extends SubCommand {
public Deny() {

View File

@ -19,7 +19,7 @@ import com.plotsquared.general.commands.CommandDeclaration;
description = "Mark a plot as done",
permission = "plots.done",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.PLAYER)
requiredType = RequiredType.NONE)
public class Done extends SubCommand {
@Override

View File

@ -22,7 +22,7 @@ import java.net.URL;
command = "download",
aliases = {"dl"},
category = CommandCategory.SCHEMATIC,
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
description = "Download your plot",
permission = "plots.download")
public class Download extends SubCommand {

View File

@ -28,7 +28,7 @@ import java.util.Map;
usage = "/plot flag <set|remove|add|list|info> <flag> <value>",
description = "Set plot flags",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
permission = "plots.flag")
public class FlagCmd extends SubCommand {
@ -166,6 +166,9 @@ public class FlagCmd extends SubCommand {
return false;
}
}
if(flag == Flags.TIME) {
player.setTime(Long.MAX_VALUE);
}
MainUtil.sendMessage(player, C.FLAG_REMOVED);
return true;
}

View File

@ -4,12 +4,14 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.RunnableVal2;
import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.util.ByteArrayUtilities;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.UUID;
@CommandDeclaration(
@ -18,17 +20,22 @@ import java.util.UUID;
usage = "/plot grant <check|add> [player]",
permission = "plots.grant",
requiredType = RequiredType.NONE)
public class Grant extends SubCommand {
public class Grant extends Command {
public Grant() {
super(MainCommand.getInstance(), true);
}
@Override
public boolean onCommand(final PlotPlayer player, String[] args) {
public void 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());
final String arg0 = args[0].toLowerCase();
switch (arg0) {
case "add":
case "check":
if (Permissions.hasPermission(player, "plots.grant." + arg0)) {
C.NO_PERMISSION.send(player, "plots.grant." + arg0);
return false;
return;
}
if (args.length > 2) {
break;
@ -36,7 +43,7 @@ public class Grant extends SubCommand {
final UUID uuid = args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : player.getUUID();
if (uuid == null) {
C.INVALID_PLAYER.send(player, args[1]);
return false;
return;
}
MainUtil.getPersistentMeta(uuid, "grantedPlots", new RunnableVal<byte[]>() {
@Override
@ -51,10 +58,7 @@ public class Grant extends SubCommand {
}
}
});
return true;
}
C.COMMAND_SYNTAX.send(player, getUsage());
return false;
}
}

View File

@ -8,6 +8,7 @@ import com.intellectualcrafters.plot.object.PlotItemStack;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.expiry.ExpireManager;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.UUID;
@ -35,6 +36,7 @@ public class Info extends SubCommand {
case "id":
case "size":
case "members":
case "seen":
case "owner":
case "rating":
plot = MainUtil.getPlotFromString(player, null, false);
@ -82,7 +84,7 @@ public class Info extends SubCommand {
"&cAlias: &6" + plot.getAlias(),
"&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(),
"&cCan Build: &6" + plot.isAdded(uuid),
"&cExpires: &6" + plot.isAdded(uuid),
"&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)),
"&cIs Denied: &6" + plot.isDenied(uuid)));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", "&cAmount: &6" + plot.getTrusted().size(),
"&8Click to view a list of the trusted users"));
@ -110,7 +112,7 @@ public class Info extends SubCommand {
info = getCaption(arg);
if (info == null) {
MainUtil.sendMessage(player,
"&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &aexpires&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, "
"&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &aseen&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, "
+ "&aowner&7, &arating");
return false;
}
@ -149,8 +151,8 @@ public class Info extends SubCommand {
return C.PLOT_INFO_OWNER.s();
case "rating":
return C.PLOT_INFO_RATING.s();
case "expires":
return C.PLOT_INFO_EXPIRES.s();
case "seen":
return C.PLOT_INFO_SEEN.s();
default:
return null;
}

View File

@ -22,7 +22,7 @@ import java.util.UUID;
permission = "plots.kick",
usage = "<player>",
category = CommandCategory.TELEPORT,
requiredType = RequiredType.PLAYER)
requiredType = RequiredType.NONE)
public class Kick extends SubCommand {
public Kick() {
@ -48,8 +48,13 @@ public class Kick extends SubCommand {
Set<PlotPlayer> players = new HashSet<>();
for (UUID uuid : uuids) {
if (uuid == DBFunc.everyone) {
players.addAll(plot.getPlayersInPlot());
break;
for (PlotPlayer pp : plot.getPlayersInPlot()) {
if (pp == player || pp.hasPermission("plots.admin.entry.denied")) {
continue;
}
players.add(pp);
}
continue;
}
PlotPlayer pp = UUIDHandler.getPlayer(uuid);
if (pp != null) {
@ -62,13 +67,12 @@ public class Kick extends SubCommand {
return false;
}
for (PlotPlayer player2 : players) {
Location location2 = player2.getLocation();
if (!player2.getLocation().getWorld().equals(location2.getWorld()) || !plot.equals(location2.getPlot())) {
MainUtil.sendMessage(player2, C.INVALID_PLAYER, args[0]);
if (!plot.equals(player2.getCurrentPlot())) {
MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]);
return false;
}
if (player2.hasPermission("plots.admin.entry.denied")) {
C.CANNOT_KICK_PLAYER.send(player2, player2.getName());
C.CANNOT_KICK_PLAYER.send(player, player2.getName());
return false;
}
Location spawn = WorldUtil.IMP.getSpawn(location.getWorld());

View File

@ -148,13 +148,7 @@ public class Load extends SubCommand {
String world = split[1];
PlotId id = PlotId.fromString(split[2] + ';' + split[3]);
String size = split[4];
String server = split[5].replaceAll(".schematic", "");
String color;
if (PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "").equals(server)) {
color = "$4";
} else {
color = "$1";
}
String color = "$4";
MainUtil.sendMessage(player,
"$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id + "$3 | " + color + size + 'x' + size);
} catch (Exception e) {
@ -191,7 +185,7 @@ public class Load extends SubCommand {
time -= minutes * 60;
toreturn.append(minutes + "m ");
}
if (toreturn.equals("") || (time > 0)) {
if (toreturn.length() == 0 || (time > 0)) {
toreturn.append(time + "s ");
}
return toreturn.toString().trim();

View File

@ -140,7 +140,8 @@ public class MainCommand extends Command {
if (EconHandler.manager != null) {
PlotArea area = player.getApplicablePlotArea();
if (area != null) {
Double price = area.PRICES.get(cmd.getFullId()).evalute(0d);
Expression<Double> priceEval = area.PRICES.get(cmd.getFullId());
Double price = priceEval != null ? priceEval.evaluate(0d) : 0d;
if (price != null && EconHandler.manager.getMoney(player) < price) {
if (failure != null) {
failure.run();
@ -160,7 +161,7 @@ public class MainCommand extends Command {
PlotArea area = player.getApplicablePlotArea();
if (area != null) {
Expression<Double> priceEval = area.PRICES.get(cmd.getFullId());
Double price = priceEval != null ? priceEval.evalute(0d) : 0d;
Double price = priceEval != null ? priceEval.evaluate(0d) : 0d;
if (price != 0d && EconHandler.manager.getMoney(player) < price) {
if (failure != null) {
failure.run();
@ -206,18 +207,35 @@ public class MainCommand extends Command {
PlotArea area = player.getApplicablePlotArea();
Plot newPlot = Plot.fromString(area, args[0]);
if (newPlot != null && (player instanceof ConsolePlayer || newPlot.getArea().equals(area) || Permissions.hasPermission(player, C.PERMISSION_ADMIN)) && !newPlot.isDenied(player.getUUID())) {
Location newLoc = newPlot.getCenter();
if (player.canTeleport(newLoc)) {
// Save meta
loc = player.getMeta("location");
plot = player.getMeta("lastplot");
tp = true;
// Set loc
player.setMeta("location", newPlot.getBottomAbs());
player.setMeta("location", newLoc);
player.setMeta("lastplot", newPlot);
} else {
C.BORDER.send(player);
}
// Trim command
args = Arrays.copyOfRange(args, 1, args.length);
}
}
try {
super.execute(player, args, confirm, whenDone);
} catch (CommandException e) {
throw e;
} catch (Throwable e) {
e.printStackTrace();
String message = e.getLocalizedMessage();
if (message != null) {
C.ERROR.send(player, message);
} else {
C.ERROR.send(player);
}
}
// Reset command scope //
if (tp && !(player instanceof ConsolePlayer)) {
if (loc == null) {

View File

@ -22,7 +22,7 @@ import java.util.UUID;
description = "Merge the plot you are standing on, with another plot",
permission = "plots.merge", usage = "/plot merge <all|n|e|s|w> [removeroads]",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
confirmation = true)
public class Merge extends SubCommand {
@ -74,7 +74,7 @@ public class Merge extends SubCommand {
final PlotArea plotArea = plot.getArea();
Expression<Double> priceExr = plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null;
final int size = plot.getConnectedPlots().size();
final double price = priceExr == null ? 0d : priceExr.evalute((double) size);
final double price = priceExr == null ? 0d : priceExr.evaluate((double) size);
if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d && EconHandler.manager.getMoney(player) < price) {
sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price));
return false;

View File

@ -7,17 +7,15 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandDeclaration;
/**
* Legally stolen from https://github.com/manuelgu/PlotSquaredMiddle
*
* @author manuelgu, altered by Citymonstret
*/
@CommandDeclaration(
command = "middle",
aliases = {"center"},
description = "Teleports you to the center of the current plot",
aliases = {"center", "centre"},
description = "Teleports you to the center of the plot",
usage = "/plot middle",
category = CommandCategory.TELEPORT,
requiredType = RequiredType.PLAYER)
requiredType = RequiredType.NONE)
public class Middle extends SubCommand {
@Override

View File

@ -40,8 +40,8 @@ public class Owner extends SetCommand {
name = UUIDHandler.getName(uuid);
name = name == null ? value : name;
}
if (uuid == null) {
if (value.equalsIgnoreCase("none")) {
if (uuid == null || value.equalsIgnoreCase("-")) {
if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("null") || value.equalsIgnoreCase("-")) {
Set<Plot> connected = plot.getConnectedPlots();
plot.unlinkPlot(false, false);
for (Plot current : connected) {

View File

@ -1,6 +1,7 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -21,7 +22,7 @@ import java.util.UUID;
description = "Remove a player from a plot",
usage = "/plot remove <player>",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
permission = "plots.remove")
public class Remove extends SubCommand {
@ -69,7 +70,12 @@ public class Remove extends SubCommand {
Set<UUID> uuids = MainUtil.getUUIDsFromString(args[0]);
if (!uuids.isEmpty()) {
for (UUID uuid : uuids) {
if (plot.getTrusted().contains(uuid)) {
if (uuid == DBFunc.everyone) {
if (plot.removeTrusted(uuid) | plot.removeMember(uuid) | plot.removeDenied(uuid)) {
count++;
}
}
else if (plot.getTrusted().contains(uuid)) {
if (plot.removeTrusted(uuid)) {
count++;
}

View File

@ -63,12 +63,11 @@ public class Save extends SubCommand {
@Override
public void run() {
String time = (System.currentTimeMillis() / 1000) + "";
String name = PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "");
Location[] corners = plot.getCorners();
int size = (corners[1].getX() - corners[0].getX()) + 1;
PlotId id = plot.getId();
String world = plot.getArea().toString().replaceAll(";", "-").replaceAll("[^A-Za-z0-9]", "");
final String file = time + '_' + world + '_' + id.x + '_' + id.y + '_' + size + '_' + name;
final String file = time + '_' + world + '_' + id.x + '_' + id.y + '_' + size;
UUID uuid = player.getUUID();
SchematicHandler.manager.upload(value, uuid, file, new RunnableVal<URL>() {
@Override

View File

@ -19,7 +19,7 @@ import java.util.UUID;
@CommandDeclaration(
command = "trust",
aliases = {"t"},
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
usage = "/plot trust <player>",
description = "Allow a player to build in a plot",
category = CommandCategory.SETTINGS)

View File

@ -4,10 +4,13 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal2;
import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.Collection;
@ -20,14 +23,23 @@ import java.util.UUID;
command = "visit",
permission = "plots.visit",
description = "Visit someones plot",
usage = "/plot visit [player|alias|world|id] [#]",
usage = "/plot visit [<player>|<alias>|<world>|<id>] [#]",
aliases = {"v", "tp", "teleport", "goto", "home", "h"},
requiredType = RequiredType.PLAYER,
requiredType = RequiredType.NONE,
category = CommandCategory.TELEPORT)
public class Visit extends SubCommand {
public class Visit extends Command {
public Visit() {
super(MainCommand.getInstance(), true);
}
@Override
public boolean onCommand(PlotPlayer player, String[] args) {
public Collection<Command> tab(PlotPlayer player, String[] args, boolean space) {
return tabOf(player, args, space, getUsage());
}
@Override
public void execute(final PlotPlayer player, String[] args, RunnableVal3<Command, Runnable, Runnable> confirm, final RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
if (args.length == 1 && args[0].contains(":")) {
args = args[0].split(":");
}
@ -36,9 +48,9 @@ public class Visit extends SubCommand {
switch (args.length) {
case 2:
if (!MathMan.isInteger(args[1])) {
sendMessage(player, C.NOT_VALID_NUMBER, "(1, ∞)");
sendMessage(player, C.COMMAND_SYNTAX, "/plot visit " + args[0] + " [#]");
return false;
C.NOT_VALID_NUMBER.send(player, "(1, ∞)");
C.COMMAND_SYNTAX.send(player, getUsage());;
return;
}
page = Integer.parseInt(args[1]);
case 1:
@ -68,8 +80,8 @@ public class Visit extends SubCommand {
page = 1;
}
if (unsorted == null || unsorted.isEmpty()) {
sendMessage(player, C.FOUND_NO_PLOTS);
return false;
C.FOUND_NO_PLOTS.send(player);
return;
}
Iterator<Plot> iterator = unsorted.iterator();
while (iterator.hasNext()) {
@ -78,34 +90,47 @@ public class Visit extends SubCommand {
}
}
if (page < 1 || page > unsorted.size()) {
sendMessage(player, C.NOT_VALID_NUMBER, "(1, " + unsorted.size() + ')');
return false;
C.NOT_VALID_NUMBER.send(player, "(1, " + unsorted.size() + ")");
return;
}
List<Plot> plots = PS.get().sortPlotsByTemp(unsorted);
Plot plot = plots.get(page - 1);
final Plot plot = plots.get(page - 1);
if (!plot.hasOwner()) {
if (!Permissions.hasPermission(player, "plots.visit.unowned")) {
sendMessage(player, C.NO_PERMISSION, "plots.visit.unowned");
return false;
C.NO_PERMISSION.send(player, "plots.visit.unowned");
return;
}
} else if (plot.isOwner(player.getUUID())) {
if (!Permissions.hasPermission(player, "plots.visit.owned") && !Permissions.hasPermission(player, "plots.home")) {
sendMessage(player, C.NO_PERMISSION, "plots.visit.owned, plots.home");
return false;
C.NO_PERMISSION.send(player, "plots.visit.owned, plots.home");
return;
}
} else if (plot.isAdded(player.getUUID())) {
if (!Permissions.hasPermission(player, "plots.visit.shared")) {
sendMessage(player, C.NO_PERMISSION, "plots.visit.shared");
return false;
C.NO_PERMISSION.send(player, "plots.visit.shared");
return;
}
} else {
if (!Permissions.hasPermission(player, "plots.visit.other")) {
sendMessage(player, C.NO_PERMISSION, "plots.visit.other");
return false;
C.NO_PERMISSION.send(player, "plots.visit.other");
return;
}
}
plot.teleportPlayer(player);
return true;
confirm.run(this, new Runnable() {
@Override
public void run() {
if (plot.teleportPlayer(player)) {
whenDone.run(Visit.this, CommandResult.SUCCESS);
} else {
whenDone.run(Visit.this, CommandResult.FAILURE);
}
}
}, new Runnable() {
@Override
public void run() {
whenDone.run(Visit.this, CommandResult.FAILURE);
}
});
}
}

View File

@ -75,7 +75,7 @@ public enum C {
*/
CONSOLE_JAVA_OUTDATED_1_8("&cYour version of java is outdated. It is highly recommended that you update to Java 8 as it increases performance "
+ "and security. PlotSquared will require Java 9 in a future update.", "static.console"),
CONSOLE_PLEASE_ENABLE_METRICS("&dPlease enable metrics for PlotSquared. Using metrics improves plugin stabability, performance, and features. "
CONSOLE_PLEASE_ENABLE_METRICS("&dPlease enable metrics for PlotSquared. Using metrics improves plugin stability, performance, and features. "
+ "Bug fixes and new features are influenced on metrics.", "static.console"),
/*
* Confirm
@ -365,6 +365,10 @@ public enum C {
INVALID_PLAYER_WAIT("$2Player not found: $1%s$2, fetching it. Try again soon.", "Errors"),
INVALID_PLAYER("$2Player not found: $1%s$2.", "Errors"),
INVALID_PLAYER_OFFLINE("$2The player must be online: $1%s.", "Errors"),
/*
* Unknown Error
*/
ERROR("$2An error occurred: %s", "Errors"),
// SETTINGS_PASTE_UPLOADED("$2settings.yml was uploaded to: $1%url%", "Paste"),
// LATEST_LOG_UPLOADED("$2latest.log was uploaded to: $1%url%", "Paste"),
DEBUG_REPORT_CREATED("$1Uploaded a full debug to: $1%url%", "Paste"),
@ -454,6 +458,7 @@ public enum C {
* Info
*/
NONE("None", "Info"),
NOW("Now", "Info"),
NEVER("Never", "Info"),
UNKNOWN("Unknown", "Info"),
EVERYONE("Everyone", "Info"),
@ -466,7 +471,7 @@ public enum C {
+ "$1Biome: $2%biome%$1&-"
+ "$1Can Build: $2%build%$1&-"
+ "$1Rating: $2%rating%&-"
+ "$1Expires: $2%expires%&-"
+ "$1Seen: $2%seen%&-"
+ "$1Trusted: $2%trusted%$1&-"
+ "$1Members: $2%members%$1&-"
+ "$1Denied: $2%denied%$1&-"
@ -482,7 +487,7 @@ public enum C {
PLOT_INFO_ID("$1ID:$2 %id%", "Info"),
PLOT_INFO_ALIAS("$1Alias:$2 %alias%", "Info"),
PLOT_INFO_SIZE("$1Size:$2 %size%", "Info"),
PLOT_INFO_EXPIRES("$1Expires:$2 %expires%", "Info"),
PLOT_INFO_SEEN("$1Seen:$2 %seen%", "Info"),
PLOT_USER_LIST(" $1%user%$2,", "Info"),
PLOT_FLAG_LIST("$1%s0:%s1$2", "Info"),
INFO_SYNTAX_CONSOLE("$2/plot info X;Y", "Info"),
@ -665,7 +670,7 @@ public enum C {
Map<String, String> map = new LinkedHashMap<>();
if (args.length > 0) {
for (int i = args.length - 1; i >= 0; i--) {
String arg = args[i].toString();
String arg = "" + args[i];
if (arg == null || arg.isEmpty()) {
map.put("%s" + i, "");
} else {
@ -682,7 +687,7 @@ public enum C {
}
public static String format(C caption, Object... args) {
if (caption.usePrefix()) {
if (caption.usePrefix() && caption.s.length() > 0) {
return C.PREFIX.s() + format(caption.s, args);
} else {
return format(caption.s, args);

View File

@ -65,9 +65,13 @@ public class Config {
if (field.getAnnotation(Final.class) != null) {
return;
}
if (field.getType() == String.class && !(value instanceof String)) {
value = value + "";
}
field.set(instance, value);
return;
} catch (IllegalAccessException e) {
} catch (Throwable e) {
PS.debug("Invalid configuration value: " + key + ": " + value + " in " + root.getSimpleName());
e.printStackTrace();
}
}

View File

@ -65,7 +65,7 @@ public class Settings extends Config {
Enabled_Components.KILL_ROAD_VEHICLES = config.getBoolean("kill_road_vehicles", Enabled_Components.KILL_ROAD_VEHICLES);
// Clearing + Expiry
// FAST_CLEAR = config.getBoolean("clear.fastmode");
//FAST_CLEAR = config.getBoolean("clear.fastmode");
Enabled_Components.PLOT_EXPIRY = config.getBoolean("clear.auto.enabled", Enabled_Components.PLOT_EXPIRY);
if (Enabled_Components.PLOT_EXPIRY) {
Enabled_Components.BAN_DELETER = config.getBoolean("clear.on.ban");
@ -119,7 +119,7 @@ public class Settings extends Config {
Teleport.ON_DEATH = config.getBoolean("teleport.on_death", Teleport.ON_DEATH);
// WorldEdit
// WE_ALLOW_HELPER = config.getBoolean("worldedit.enable-for-helpers");
//WE_ALLOW_HELPER = config.getBoolean("worldedit.enable-for-helpers");
// Chunk processor
Enabled_Components.CHUNK_PROCESSOR = config.getBoolean("chunk-processor.enabled", Enabled_Components.CHUNK_PROCESSOR);
@ -296,7 +296,7 @@ public class Settings extends Config {
public static boolean WORLDEDIT_RESTRICTIONS = true;
@Comment("Allow economy to be used")
public static boolean ECONOMY = true;
@Comment("Send anonymous usage statistics")
@Comment("Send anonymous usage statistics. Bukkit only setting.")
public static boolean METRICS = true;
@Comment("Expiry will clear old or simplistic plots")
public static boolean PLOT_EXPIRY = false;

View File

@ -1583,7 +1583,7 @@ public class SQLManager implements AbstractDB {
}
/**
* Load all plots, helpers, denied, trusted, and every setting from DB into a hashmap
* Load all plots, helpers, denied, trusted, and every setting from DB into a {@link HashMap}.
*/
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlots() {
@ -1816,14 +1816,7 @@ public class SQLManager implements AbstractDB {
String[] split = element.split(":");
try {
String flag_str = split[1].replaceAll("¯", ":").replaceAll("\u00B4", ",");
Flag<?> flag = FlagManager.getFlag(split[0],true);
if (flag == null) {
flag = new StringFlag(split[0]) {
@Override public String getValueDescription() {
return "Generic Filler Flag";
}
};
}
Flag<?> flag = FlagManager.getOrCreateFlag(split[0]);
flags.put(flag, flag.parseValue(flag_str));
} catch (Exception e) {
e.printStackTrace();
@ -1832,7 +1825,7 @@ public class SQLManager implements AbstractDB {
} else {
element = element.replaceAll("\u00AF", ":").replaceAll("\u00B4", ",");
if (StringMan.isAlpha(element.replaceAll("_", "").replaceAll("-", ""))) {
Flag flag = FlagManager.getFlag(element,true);
Flag flag = FlagManager.getOrCreateFlag(element);
if (flag == null) {
flag = new StringFlag(element) {
@Override public String getValueDescription() {
@ -2560,9 +2553,7 @@ public class SQLManager implements AbstractDB {
}
set.add(cluster);
}
/*
* Getting helpers
*/
//Getting helpers
resultSet = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + this.prefix + "cluster_helpers`");
while (resultSet.next()) {
id = resultSet.getInt("cluster_id");
@ -2579,9 +2570,7 @@ public class SQLManager implements AbstractDB {
PS.debug("&cCluster " + id + " in cluster_helpers does not exist. Please create the cluster or remove this entry.");
}
}
/*
* Getting invited
*/
// Getting invited
resultSet = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + this.prefix + "cluster_invited`");
while (resultSet.next()) {
id = resultSet.getInt("cluster_id");
@ -2638,7 +2627,7 @@ public class SQLManager implements AbstractDB {
if (element.contains(":")) {
String[] split = element.split(":");
String flag_str = split[1].replaceAll("\u00AF", ":").replaceAll("<EFBFBD>", ",");
Flag flag = FlagManager.getFlag(split[0],true);
Flag flag = FlagManager.getOrCreateFlag(split[0]);
if (flag == null) {
flag = new StringFlag(split[0]) {
@Override public String getValueDescription() {
@ -2648,7 +2637,7 @@ public class SQLManager implements AbstractDB {
}
flags.put(flag, flag.parseValue(flag_str));
} else {
Flag flag = FlagManager.getFlag(element,true);
Flag flag = FlagManager.getOrCreateFlag(element);
if (flag == null) {
flag = new StringFlag(element) {
@Override public String getValueDescription() {

View File

@ -9,11 +9,7 @@ public class BooleanFlag extends Flag<Boolean> {
}
@Override public String valueToString(Object value) {
if (((boolean) value)) {
return "true";
} else {
return "false";
}
return value + "";
}
@Override public Boolean parseValue(String value) {

View File

@ -0,0 +1,31 @@
package com.intellectualcrafters.plot.flag;
import com.intellectualcrafters.plot.util.StringMan;
import java.util.Arrays;
import java.util.HashSet;
public class EnumFlag extends Flag<String> {
private final HashSet<String> values;
public EnumFlag(String name, String... values) {
super(name);
this.values = new HashSet<>(Arrays.asList(values));
}
@Override
public String valueToString(Object value) {
return value.toString();
}
@Override public String parseValue(String value) {
value = value.toLowerCase();
if (values.contains(value)) {
return value;
}
return null;
}
@Override public String getValueDescription() {
return "Must be one of: " + StringMan.getString(values);
}
}

View File

@ -112,12 +112,17 @@ public class FlagManager {
StringBuilder flag_string = new StringBuilder();
int i = 0;
for (Map.Entry<Flag<?>, Object> entry : flags.entrySet()) {
try {
Flag flag = entry.getKey();
if (i != 0) {
flag_string.append(',');
}
flag_string.append(flag.getName() + ':' + flag.valueToString(entry.getValue()).replaceAll(":", "¯").replaceAll(",", "´"));
i++;
} catch (Exception e) {
PS.debug("Failed to parse flag: " + entry.getKey() + "->" + entry.getValue());
e.printStackTrace();
}
}
return flag_string.toString();
}
@ -213,7 +218,7 @@ public class FlagManager {
/**
* Removes a flag from a certain plot.
* @param plot the plot to remove the flag from
* @param origin the plot to remove the flag from
* @param id the flag to remove
* @return true if the plot contained the flag and was removed successfully
*/
@ -317,6 +322,19 @@ public class FlagManager {
return flag;
}
public static Flag<?> getOrCreateFlag(String string) {
Flag<?> flag = Flags.getFlag(string);
if (flag == null) {
flag = new StringFlag(string) {
@Override public String getValueDescription() {
return "Generic Filler Flag";
}
};
flag.register();
}
return flag;
}
public static Map<Flag<?>, Object> parseFlags(List<String> flagStrings) {
HashMap<Flag<?>, Object> map = new HashMap<>();
@ -328,7 +346,7 @@ public class FlagManager {
} else {
split = key.split(":");
}
Flag<?> flag = getFlag(split[0]);
Flag<?> flag = getOrCreateFlag(split[0]);
Object value = flag.parseValue(split[1]);
map.put(flag, value);
}

View File

@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
@ -22,6 +21,7 @@ public final class Flags {
public static final IntervalFlag FEED = new IntervalFlag("feed");
public static final IntervalFlag HEAL = new IntervalFlag("heal");
public static final GameModeFlag GAMEMODE = new GameModeFlag("gamemode");
public static final GameModeFlag GUEST_GAMEMODE = new GameModeFlag("guest-gamemode");
public static final StringFlag DONE = (StringFlag) new StringFlag("done").reserve();
public static final BooleanFlag REDSTONE = new BooleanFlag("redstone");
public static final BooleanFlag FLY = new BooleanFlag("fly");
@ -47,6 +47,7 @@ public final class Flags {
public static final BooleanFlag VINE_GROW = new BooleanFlag("vine-grow");
public static final BooleanFlag MYCEL_GROW = new BooleanFlag("mycel-grow");
public static final BooleanFlag DISABLE_PHYSICS = new BooleanFlag("disable-physics");
public static final BooleanFlag LIQUID_FLOW = new BooleanFlag("liquid-flow");
public static final BooleanFlag SNOW_MELT = new BooleanFlag("snow-melt");
public static final BooleanFlag ICE_MELT = new BooleanFlag("ice-melt");
public static final BooleanFlag FIRE_SPREAD = new BooleanFlag("fire-spread");
@ -113,6 +114,9 @@ public final class Flags {
}
};
public static final BooleanFlag SLEEP = new BooleanFlag("sleep");
public static final TeleportDenyFlag DENY_TELEPORT = new TeleportDenyFlag("deny-teleport");
public static final BooleanFlag DENY_EXIT = new BooleanFlag("deny-exit");
private static final HashMap<String, Flag<?>> flags;
static {
@ -150,35 +154,24 @@ public final class Flags {
public static void registerFlag(final Flag<?> flag) {
final Flag<?> duplicate = flags.put(flag.getName(), flag);
if (duplicate != null) {
PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override public void run(PlotArea value) {
if (duplicate != null) {
Object remove;
if (value.DEFAULT_FLAGS.containsKey(duplicate)) {
remove = value.DEFAULT_FLAGS.remove(duplicate);
if (!(remove instanceof String)) {
//error message? maybe?
return;
}
value.DEFAULT_FLAGS.put(flag,flag.parseValue((String) remove));
}
value.DEFAULT_FLAGS.put(flag,flag.parseValue("" + remove));
}
}
});
PS.get().foreachPlotRaw(new RunnableVal<Plot>() {
@Override public void run(Plot value) {
if (duplicate != null) {
Object remove = null;
if (value.getFlags().containsKey(duplicate)) {
remove = value.getFlags().remove(duplicate);
}
if (!(remove instanceof String)) {
//error message? maybe?
return;
}
value.getFlags().put(flag,flag.parseValue((String) remove));
Object remove = value.getFlags().remove(duplicate);
value.getFlags().put(flag,flag.parseValue("" + remove));
}
}
});
}
}
}

View File

@ -0,0 +1,38 @@
package com.intellectualcrafters.plot.flag;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
public class TeleportDenyFlag extends EnumFlag {
public TeleportDenyFlag(String name) {
super(name, "trusted", "members", "nonmembers", "nontrusted", "nonowners");
}
public boolean allowsTeleport(PlotPlayer player, Plot plot) {
String value = plot.getFlag(this, null);
if (value == null || !plot.hasOwner()) {
return true;
}
boolean result;
switch (plot.getFlag(this, null)) {
case "trusted":
result = !plot.getTrusted().contains(player.getUUID());
break;
case "members":
result =!plot.getMembers().contains(player.getUUID());
break;
case "nonmembers":
result =!plot.isAdded(player.getUUID());
break;
case "nontrusted":
result =!plot.getTrusted().contains(player.getUUID()) && !plot.isOwner(player.getUUID());
break;
case "nonowners":
result =!plot.isOwner(player.getUUID());
break;
default:
return true;
}
return result || player.hasPermission("plots.admin.entry.denied");
}
}

View File

@ -140,7 +140,9 @@ public class AugmentedUtils {
generator.generateChunk(scoped, area, r);
generator.populateChunk(scoped, area, r);
}
if (queue != null) {
queue.flush();
}
return toReturn;
}
}

View File

@ -66,13 +66,14 @@ public class HybridPlotManager extends ClassicPlotManager {
if (!hpw.ROAD_SCHEMATIC_ENABLED) {
return true;
}
createSchemAbs(hpw, pos1, pos2, true);
LocalBlockQueue queue = hpw.getQueue(false);
createSchemAbs(hpw, queue, pos1, pos2, true);
queue.enqueue();
return true;
}
private void createSchemAbs(HybridPlotWorld hpw, Location pos1, Location pos2, boolean clear) {
private void createSchemAbs(HybridPlotWorld hpw, LocalBlockQueue queue, Location pos1, Location pos2, boolean clear) {
int size = hpw.SIZE;
LocalBlockQueue queue = hpw.getQueue(false);
for (int x = pos1.getX(); x <= pos2.getX(); x++) {
short absX = (short) ((x - hpw.ROAD_OFFSET_X) % size);
if (absX < 0) {
@ -96,7 +97,6 @@ public class HybridPlotManager extends ClassicPlotManager {
}
}
}
queue.enqueue();
}
@Override
@ -113,7 +113,9 @@ public class HybridPlotManager extends ClassicPlotManager {
if (!hpw.ROAD_SCHEMATIC_ENABLED) {
return true;
}
createSchemAbs(hpw, pos1, pos2, true);
LocalBlockQueue queue = hpw.getQueue(false);
createSchemAbs(hpw, queue, pos1, pos2, true);
queue.enqueue();
return true;
}
@ -127,11 +129,12 @@ public class HybridPlotManager extends ClassicPlotManager {
Location pos2 = getPlotBottomLocAbs(hpw, id2);
pos1.setY(0);
pos2.setY(256);
createSchemAbs(hpw, pos1, pos2, true);
if (!hpw.ROAD_SCHEMATIC_ENABLED) {
return true;
LocalBlockQueue queue = hpw.getQueue(false);
createSchemAbs(hpw, queue, pos1, pos2, true);
if (hpw.ROAD_SCHEMATIC_ENABLED) {
createSchemAbs(hpw, queue, pos1, pos2, true);
}
createSchemAbs(hpw, pos1, pos2, true);
queue.enqueue();
return true;
}
@ -189,7 +192,7 @@ public class HybridPlotManager extends ClassicPlotManager {
top.setY(256);
queue.setCuboid(bot, top, air);
// And finally set the schematic, the y value is unimportant for this function
pastePlotSchematic(dpw, bot, top);
pastePlotSchematic(dpw, queue, bot, top);
}
}, new Runnable() {
@Override
@ -202,10 +205,10 @@ public class HybridPlotManager extends ClassicPlotManager {
return true;
}
public void pastePlotSchematic(HybridPlotWorld plotWorld, Location l1, Location l2) {
public void pastePlotSchematic(HybridPlotWorld plotWorld, LocalBlockQueue queue, Location l1, Location l2) {
if (!plotWorld.PLOT_SCHEMATIC) {
return;
}
createSchemAbs(plotWorld, l1, l2, false);
createSchemAbs(plotWorld, queue, l1, l2, false);
}
}

View File

@ -21,6 +21,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.expiry.PlotAnalysis;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
@ -446,10 +447,10 @@ public abstract class HybridUtils {
}
}
}
queue.enqueue();
return true;
}
}
queue.enqueue();
return false;
}
}

View File

@ -32,9 +32,14 @@ public class ConsolePlayer extends PlotPlayer {
return instance;
}
@Override
public boolean canTeleport(Location loc) {
return true;
}
@Override
public Location getLocation() {
return this.<Location>getMeta("location");
return this.getMeta("location");
}
@Override
@ -110,14 +115,14 @@ public class ConsolePlayer extends PlotPlayer {
@Override
public void setTime(long time) {}
@Override
public void setFlight(boolean fly) {}
@Override
public boolean getFlight() {
return true;
}
@Override
public void setFlight(boolean fly) {}
@Override
public void playMusic(Location location, int id) {}

View File

@ -6,12 +6,12 @@ import com.intellectualcrafters.plot.commands.MainCommand;
import javax.script.ScriptException;
public abstract class Expression<T> {
public abstract T evalute(T arg);
public abstract T evaluate(T arg);
public static <U> Expression<U> constant(final U value) {
return new Expression<U>() {
@Override
public U evalute(U arg) {
public U evaluate(U arg) {
return value;
}
};
@ -20,8 +20,8 @@ public abstract class Expression<T> {
public static Expression<Double> linearDouble(final Double value) {
return new Expression<Double>() {
@Override
public Double evalute(Double arg) {
return (arg.doubleValue() * value.doubleValue());
public Double evaluate(Double arg) {
return (arg * value);
}
};
}
@ -29,15 +29,15 @@ public abstract class Expression<T> {
public static Expression<Double> doubleExpression(final String expression) {
try {
return constant(Double.parseDouble(expression));
} catch (Exception ignore) {}
} catch (NumberFormatException ignore) {}
if (expression.endsWith("*{arg}")) {
try {
return linearDouble(Double.parseDouble(expression.substring(0, expression.length() - 6)));
} catch (Exception ignore) {}
} catch (NumberFormatException ignore) {}
}
return new Expression<Double>() {
@Override
public Double evalute(Double arg) {
public Double evaluate(Double arg) {
DebugExec exec = (DebugExec) MainCommand.getInstance().getCommand(DebugExec.class);
try {
return (Double) exec.getEngine().eval(expression.replace("{arg}", "" + arg));

View File

@ -25,6 +25,7 @@ import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.expiry.PlotAnalysis;
import com.plotsquared.listener.PlotListener;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.awt.geom.PathIterator;
@ -738,8 +739,7 @@ public class Plot {
}
/**
* Clear a plot
* @see this#clear(Runnable)
* Clear a plot.
* @see this#clear(boolean, boolean, Runnable)
* @see #deletePlot(Runnable) to clear and delete a plot
* @param whenDone A runnable to execute when clearing finishes, or null
@ -1109,6 +1109,15 @@ public class Plot {
return loc;
}
public Location getSide() {
RegionWrapper largest = getLargestRegion();
int x = (largest.maxX >> 1) - (largest.minX >> 1) + largest.minX;
int z = largest.minZ - 1;
PlotManager manager = getManager();
int y = Math.max(WorldUtil.IMP.getHighestBlock(area.worldname, x, z), manager.getSignLoc(area, this).getY());
return new Location(area.worldname, x, y + 1, z);
}
/**
* Return the home location for the plot
* @return Home location
@ -1169,12 +1178,7 @@ public class Plot {
return new Location(plot.area.worldname, x, y + 1, z);
}
// Side
RegionWrapper largest = plot.getLargestRegion();
int x = (largest.maxX >> 1) - (largest.minX >> 1) + largest.minX;
int z = largest.minZ - 1;
PlotManager manager = plot.getManager();
int y = Math.max(WorldUtil.IMP.getHighestBlock(plot.area.worldname, x, z), manager.getSignLoc(plot.area, plot).getY());
return new Location(plot.area.worldname, x, y + 1, z);
return plot.getSide();
}
public double getVolume() {
@ -1397,7 +1401,7 @@ public class Plot {
* @return the name of the biome
*/
public String getBiome() {
Location loc = this.getBottomAbs();
Location loc = this.getCenter();
return WorldUtil.IMP.getBiome(loc.getWorld(), loc.getX(), loc.getZ());
}
@ -1650,7 +1654,7 @@ public class Plot {
if (uuid == DBFunc.everyone) {
boolean result = false;
for (UUID other : new HashSet<>(getDenied())) {
result = result || rmvDenied(other);
result = rmvDenied(other) || result;
}
return result;
}
@ -1677,7 +1681,7 @@ public class Plot {
if (uuid == DBFunc.everyone) {
boolean result = false;
for (UUID other : new HashSet<>(getTrusted())) {
result = result || rmvTrusted(other);
result = rmvTrusted(other) || result;
}
return result;
}
@ -1707,7 +1711,7 @@ public class Plot {
if (uuid == DBFunc.everyone) {
boolean result = false;
for (UUID other : new HashSet<>(this.members)) {
result = result || rmvMember(other);
result = rmvMember(other) || result;
}
return result;
}
@ -2681,7 +2685,7 @@ public class Plot {
greaterPlot.setMerged(3, true);
lesserPlot.mergeData(greaterPlot);
if (removeRoads) {
Plot diagonal = greaterPlot.getRelative(1);
Plot diagonal = greaterPlot.getRelative(2);
if (diagonal.getMerged(7)) {
lesserPlot.removeRoadSouthEast();
}

View File

@ -18,6 +18,7 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.area.QuadMap;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@ -91,10 +92,6 @@ public abstract class PlotArea {
this.worldhash = worldName.hashCode();
}
public LocalBlockQueue getQueue(boolean autoQueue) {
return GlobalBlockQueue.IMP.getNewQueue(worldname, autoQueue);
}
/**
* Create a new PlotArea object with no functionality/information.
* - Mainly used during startup before worlds are created as a temporary object
@ -106,10 +103,16 @@ public abstract class PlotArea {
@Override
public void loadConfiguration(ConfigurationSection config) {}
@Override
public ConfigurationNode[] getSettingNodes() {return null;}
public ConfigurationNode[] getSettingNodes() {
return null;
}
};
}
public LocalBlockQueue getQueue(boolean autoQueue) {
return GlobalBlockQueue.IMP.getNewQueue(worldname, autoQueue);
}
/**
* Returns the region for this PlotArea or a RegionWrapper encompassing
* the whole world if none exists.
@ -142,7 +145,7 @@ public abstract class PlotArea {
/**
* Returns the minimum value of a {@link PlotId}.
* @return
* @return the minimum value for a {@link PlotId}
*/
public PlotId getMin() {
return this.min == null ? new PlotId(Integer.MIN_VALUE, Integer.MIN_VALUE) : this.min;
@ -150,7 +153,7 @@ public abstract class PlotArea {
/**
* Returns the max PlotId.
* @return
* @return the maximum value for a {@link PlotId}
*/
public PlotId getMax() {
return this.max == null ? new PlotId(Integer.MAX_VALUE, Integer.MAX_VALUE) : this.max;
@ -159,7 +162,7 @@ public abstract class PlotArea {
/**
* Get the implementation independent generator for this area.
*
* @return
* @return the {@link IndependentPlotGenerator}
*/
public IndependentPlotGenerator getGenerator() {
return this.generator;
@ -183,8 +186,8 @@ public abstract class PlotArea {
/**
* Check if a PlotArea is compatible (move/copy etc).
* @param plotArea
* @return
* @param plotArea the {@code PlotArea} to compare
* @return true if both areas are compatible
*/
public boolean isCompatible(PlotArea plotArea) {
ConfigurationSection section = PS.get().worlds.getConfigurationSection("worlds");
@ -303,7 +306,7 @@ public abstract class PlotArea {
public abstract void loadConfiguration(ConfigurationSection config);
/**
* Saving core PlotArea settings
* Saving core PlotArea settings.
*
* @param config Configuration Section
*/
@ -381,9 +384,9 @@ public abstract class PlotArea {
public abstract ConfigurationNode[] getSettingNodes();
/**
* Get the Plot at a location.
* @param location
* @return Plot
* Gets the {@code Plot} at a location.
* @param location the location
* @return the {@code Plot} or null if none exists
*/
public Plot getPlotAbs(Location location) {
PlotId pid = this.manager.getPlotId(this, location.getX(), location.getY(), location.getZ());
@ -394,8 +397,8 @@ public abstract class PlotArea {
}
/**
* Get the base plot at a location.
* @param location
* Gets the base plot at a location.
* @param location the location
* @return base Plot
*/
public Plot getPlot(Location location) {
@ -407,9 +410,9 @@ public abstract class PlotArea {
}
/**
* Get the base owned plot at a location.
* @param location
* @return base Plot or null
* Get the owned base plot at a location.
* @param location the location
* @return the base plot or null
*/
public Plot getOwnedPlot(Location location) {
PlotId pid = this.manager.getPlotId(this, location.getX(), location.getY(), location.getZ());
@ -422,7 +425,7 @@ public abstract class PlotArea {
/**
* Get the owned plot at a location.
* @param location
* @param location the location
* @return Plot or null
*/
public Plot getOwnedPlotAbs(Location location) {
@ -435,8 +438,8 @@ public abstract class PlotArea {
/**
* Get the owned Plot at a PlotId.
* @param id
* @return Plot or null
* @param id the {@code PlotId}
* @return the plot or null
*/
public Plot getOwnedPlotAbs(PlotId id) {
return this.plots.get(id);
@ -473,8 +476,8 @@ public abstract class PlotArea {
return myPlots;
}
public Set<Plot> getPlots(final UUID uuid) {
final HashSet<Plot> myplots = new HashSet<>();
public Set<Plot> getPlots(UUID uuid) {
HashSet<Plot> myplots = new HashSet<>();
for (Plot plot : getPlots()) {
if (plot.isBasePlot()) {
if (plot.isOwner(uuid)) {
@ -489,6 +492,14 @@ public abstract class PlotArea {
return getPlots(player.getUUID());
}
/**
* A collection of the claimed plots in this {@code PlotArea}.
* @return a collection of claimed plots
*/
public Collection<Plot> getPlots() {
return this.plots.values();
}
public Set<Plot> getPlotsAbs(PlotPlayer player) {
return player != null ? getPlotsAbs(player.getUUID()) : new HashSet<Plot>();
}
@ -570,7 +581,7 @@ public abstract class PlotArea {
}
/**
* Session only plot metadata (session is until the server stops)<br>
* Session only plot metadata (session is until the server stops).
* <br>
* For persistent metadata use the flag system
* @see FlagManager
@ -598,14 +609,6 @@ public abstract class PlotArea {
return null;
}
/**
* A collection of the claimed plots in this {@code PlotArea}.
* @return
*/
public Collection<Plot> getPlots() {
return this.plots.values();
}
public Set<Plot> getBasePlots() {
HashSet<Plot> myPlots = new HashSet<>(getPlots());
Iterator<Plot> iterator = myPlots.iterator();
@ -662,10 +665,10 @@ public abstract class PlotArea {
}
/**
* Check if the plots in a selection are unowned
* @param pos1
* @param pos2
* @return
* Check if the plots in a selection are unowned.
* @param pos1 first corner of selection
* @param pos2 second corner of selection
* @return are plots in selection unowned
*/
public boolean isUnowned(PlotId pos1, PlotId pos2) {
int area = (pos2.x - pos1.x + 1) * (pos2.y - pos1.y + 1);
@ -706,7 +709,7 @@ public abstract class PlotArea {
}
/**
* Setup the plot border for a world (usually done when the world is created)
* Setup the plot border for a world (usually done when the world is created).
*/
public void setupBorder() {
if (!this.WORLD_BORDER) {
@ -722,7 +725,7 @@ public abstract class PlotArea {
}
/**
* Delete the metadata for a key<br>
* Delete the metadata for a key.
* - metadata is session only
* - deleting other plugin's metadata may cause issues
* @param key
@ -819,11 +822,11 @@ public abstract class PlotArea {
}
/**
* Get a set of owned plots within a selection (chooses the best algorithm based on selection size.<br>
* Get a set of owned plots within a selection (chooses the best algorithm based on selection size.
* i.e. A selection of billions of plots will work fine
* @param pos1
* @param pos2
* @return
* @param pos1 first corner of selection
* @param pos2 second corner of selection
* @return the plots in the selection which are owned
*/
public HashSet<Plot> getPlotSelectionOwned(PlotId pos1, PlotId pos2) {
int size = (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y);

View File

@ -1,6 +1,8 @@
package com.intellectualcrafters.plot.object;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.chat.PlainChatManager;
import com.intellectualcrafters.plot.util.ChatManager;
public class PlotMessage {
@ -8,7 +10,13 @@ public class PlotMessage {
private Object builder;
public PlotMessage() {
try {
reset(ChatManager.manager);
} catch (Throwable e) {
PS.debug("PlotSquared doesn't support fancy chat for " + PS.get().IMP.getServerVersion());
ChatManager.manager = new PlainChatManager();
reset(ChatManager.manager);
}
}
public PlotMessage(String text) {

View File

@ -55,7 +55,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Set some session only metadata for the player.
* Set some session only metadata for this player.
* @param key
* @param value
*/
@ -102,7 +102,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* The player's name.
* This player's name.
*
* @return the name of the player
*/
@ -112,11 +112,11 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the player's current plot.
* Get this player's current plot.
* @return the plot the player is standing on or null if standing on a road or not in a {@link PlotArea}
*/
public Plot getCurrentPlot() {
Plot value = (Plot) getMeta("lastplot");
Plot value = getMeta("lastplot");
if (value == null && !Settings.Enabled_Components.EVENTS) {
return getLocation().getPlot();
}
@ -133,7 +133,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the number of plots the player owns.
* Get the number of plots this player owns.
*
* @see #getPlotCount(String);
* @see #getPlots()
@ -164,7 +164,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the number of plots the player owns in the world.
* Get the number of plots this player owns in the world.
* @param world the name of the plotworld to check.
* @return
*/
@ -196,7 +196,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Return the PlotArea the player is currently in, or null.
* Return the PlotArea this player is currently in, or null.
* @return
*/
public PlotArea getPlotAreaAbs() {
@ -216,7 +216,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
////////////// PARTIALLY IMPLEMENTED ///////////
/**
* Get the player's last recorded location or null if they don't any plot relevant location.
* Get this player's last recorded location or null if they don't any plot relevant location.
* @return The location
*/
public Location getLocation() {
@ -235,29 +235,40 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the player's full location (including yaw/pitch)
* Get this player's full location (including yaw/pitch)
* @return
*/
public abstract Location getLocationFull();
/**
* Get the player's UUID.
* Get this player's UUID.
* === !IMPORTANT ===<br>
* The UUID is dependent on the mode chosen in the settings.yml and may not be the same as Bukkit has
* (especially if using an old version of Bukkit that does not support UUIDs)
*
* @return UUID
*/
public abstract UUID getUUID();
@Override public abstract UUID getUUID();
public boolean canTeleport(Location loc) {
Location current = getLocationFull();
teleport(loc);
boolean result = true;
if (!getLocation().equals(loc)) {
result = false;
}
teleport(current);
return result;
}
/**
* Teleport the player to a location.
* Teleport this player to a location.
* @param location the target location
*/
public abstract void teleport(Location location);
/**
* Set the compass target.
* Set this compass target.
* @param location the target location
*/
public abstract void setCompassTarget(Location location);
@ -274,7 +285,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
/**
* Retrieves the player attribute.
* Retrieves the attribute of this player.
*
* @param key
* @return the attribute will be either true or false
@ -295,58 +306,58 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Set the player's local weather.
* Sets the local weather for this Player.
* @param weather the weather visible to the player
*/
public abstract void setWeather(PlotWeather weather);
/**
* Get the player's gamemode.
* Get this player's gamemode.
* @return the gamemode of the player.
*/
public abstract PlotGameMode getGameMode();
/**
* Set the player's gameMode.
* Set this player's gameMode.
* @param gameMode the gamemode to set
*/
public abstract void setGameMode(PlotGameMode gameMode);
/**
* Set the player's local time (ticks).
* Set this player's local time (ticks).
* @param time the time visible to the player
*/
public abstract void setTime(long time);
public abstract boolean getFlight();
/**
* Set the player's fly mode.
* Set this player's fly mode.
* @param fly if the player can fly
*/
public abstract void setFlight(boolean fly);
public abstract boolean getFlight();
/**
* Play music at a location for the player.
* Play music at a location for this player.
* @param location where to play the music
* @param id the numerical record item id
*/
public abstract void playMusic(Location location, int id);
/**
* Check if the player is banned.
* Check if this player is banned.
* @return true if the player is banned, false otherwise.
*/
public abstract boolean isBanned();
/**
* Kick the player from the game.
* Kick this player from the game.
* @param message the reason for the kick
*/
public abstract void kick(String message);
/**
* Called when the player quits.
* Called when this player quits.
*/
public void unregister() {
Plot plot = getCurrentPlot();
@ -368,7 +379,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the amount of clusters a player owns in the specific world.
* Get the amount of clusters this player owns in the specific world.
* @param world
* @return
*/
@ -384,7 +395,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Get the amount of clusters a player owns.
* Get the amount of clusters this player owns.
* @return the number of clusters this player owns
*/
public int getPlayerClusterCount() {
@ -399,9 +410,9 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
}
/**
* Return a {@code Set} of all plots a player owns in a certain world.
* Return a {@code Set} of all plots this player owns in a certain world.
* @param world the world to retrieve plots from
* @return a {@code Set} of plots the player owns in the provided world
* @return a {@code Set} of plots this player owns in the provided world
*/
public Set<Plot> getPlots(String world) {
UUID uuid = getUUID();
@ -453,7 +464,7 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
public abstract void stopSpectating();
/**
* The amount of money this player has
* The amount of money this Player has.
* @return
*/
public double getMoney() {

View File

@ -1,14 +1,14 @@
package com.plotsquared.bukkit.util;
package com.intellectualcrafters.plot.object.chat;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChatManager;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
public class PlainChatManager extends ChatManager<List<StringBuilder>> {
@Override
public List<StringBuilder> builder() {
@ -29,7 +29,7 @@ public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
@Override
public void text(PlotMessage message, String text) {
message.$(this).add(new StringBuilder(ChatColor.stripColor(text)));
message.$(this).add(new StringBuilder(C.color(text)));
}
@Override

View File

@ -68,6 +68,7 @@ public abstract class EventUtil {
}
}
if (PS.get().update != null && Permissions.hasPermission(player, C.PERMISSION_ADMIN_UPDATE) && Settings.Enabled_Components.UPDATER) {
MainUtil.sendMessage(player,C.CONSOLE_JAVA_OUTDATED_1_8.s());
MainUtil.sendMessage(player, "&6An update for PlotSquared is available: &7/plot update");
}
final Plot plot = player.getCurrentPlot();
@ -238,7 +239,7 @@ public abstract class EventUtil {
value = null;
}
if (value == null || !value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock())) {
if (Permissions.hasPermission(player, C.PERMISSION_ADMIN_BUILD_OTHER.s(), false)) {
if (Permissions.hasPermission(player, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), false)) {
return true;
}
return false;

View File

@ -16,6 +16,8 @@ import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.expiry.ExpireManager;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@ -37,7 +39,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* plot functions
@ -206,6 +207,39 @@ public class MainUtil {
return false;
}
public static String secToTime(long time) {
StringBuilder toreturn = new StringBuilder();
if (time >= 33868800) {
int years = (int) (time / 33868800);
time -= years * 33868800;
toreturn.append(years+"y ");
}
if (time >= 604800) {
int weeks = (int) (time / 604800);
time -= weeks * 604800;
toreturn.append(weeks+"w ");
}
if (time >= 86400) {
int days = (int) (time / 86400);
time -= days * 86400;
toreturn.append(days+"d ");
}
if (time >= 3600) {
int hours = (int) (time / 3600);
time -= hours * 3600;
toreturn.append(hours+"h ");
}
if (time>=60) {
int minutes = (int) (time / 60);
time -= minutes * 60;
toreturn.append(minutes+"m ");
}
if (toreturn.equals("")||time>0){
toreturn.append((time)+"s ");
}
return toreturn.toString().trim();
}
public static long timeToSec(String string) {
if (MathMan.isInteger(string)) {
return Long.parseLong(string);
@ -686,31 +720,20 @@ public class MainUtil {
String trusted = getPlayerList(plot.getTrusted());
String members = getPlayerList(plot.getMembers());
String denied = getPlayerList(plot.getDenied());
String expires = C.UNKNOWN.s();
String seen;
if (Settings.Enabled_Components.PLOT_EXPIRY) {
if (plot.hasOwner()) {
Optional<?> keep = plot.getFlag(Flags.KEEP);
if (keep.isPresent()) {
Object value = keep.get();
if (value instanceof Boolean) {
if (Boolean.TRUE.equals(value)) {
expires = C.NONE.s();
}
} else if (value instanceof Long) {
if ((Long) value > System.currentTimeMillis()) {
long l = System.currentTimeMillis() - (long) value;
expires = String.format("%d days", TimeUnit.MILLISECONDS.toDays(l));
}
}
// } else if (ExpireManager.IMP != null) {
// long timestamp = ExpireManager.IMP.getTimestamp(plot.owner);
// long compared = System.currentTimeMillis() - timestamp;
// long l = Settings.AUTO_CLEAR_DAYS - TimeUnit.MILLISECONDS.toDays(compared);
// expires = String.format("%d days", l);
if (plot.isOnline()) {
seen = C.NOW.s();
} else {
int time = (int) (ExpireManager.IMP.getAge(plot) / 1000);
if (time != 0) {
seen = MainUtil.secToTime(time);
} else {
seen = C.UNKNOWN.s();
}
}
} else {
expires = C.NEVER.s();
seen = C.NEVER.s();
}
Optional<String> descriptionFlag = plot.getFlag(Flags.DESCRIPTION);
String description = !descriptionFlag.isPresent() ? C.NONE.s() : Flags.DESCRIPTION.valueToString(descriptionFlag.get());
@ -727,9 +750,7 @@ public class MainUtil {
}
}
boolean build = plot.isAdded(player.getUUID());
String owner = plot.getOwners().isEmpty() ? "unowned" : getPlayerList(plot.getOwners());
info = info.replace("%id%", plot.getId().toString());
info = info.replace("%alias%", alias);
info = info.replace("%num%", String.valueOf(num));
@ -741,7 +762,7 @@ public class MainUtil {
info = info.replace("%trusted%", trusted);
info = info.replace("%helpers%", members);
info = info.replace("%denied%", denied);
info = info.replace("%expires%", expires);
info = info.replace("%seen%", seen);
info = info.replace("%flags%", flags);
info = info.replace("%build%", String.valueOf(build));
info = info.replace("%desc%", "No description set.");
@ -757,10 +778,6 @@ public class MainUtil {
String info;
if (full && Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) {
double[] ratings = MainUtil.getAverageRatings(plot);
for (double v : ratings) {
}
String rating = "";
String prefix = "";
for (int i = 0; i < ratings.length; i++) {

View File

@ -9,19 +9,7 @@ public class MathMan {
private static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT);
private static final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1);
private static final float[] atan2 = new float[ATAN2_COUNT];
static {
for (int i = 0; i < ATAN2_DIM; i++) {
for (int j = 0; j < ATAN2_DIM; j++) {
float x0 = (float) i / ATAN2_DIM;
float y0 = (float) j / ATAN2_DIM;
atan2[(j * ATAN2_DIM) + i] = (float) Math.atan2(y0, x0);
}
}
}
private final static int[] table = {
private static final int[] table = {
0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57,
59, 61, 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83,
84, 86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102,
@ -43,6 +31,17 @@ public class MathMan {
253, 254, 254, 255
};
static {
for (int i = 0; i < ATAN2_DIM; i++) {
for (int j = 0; j < ATAN2_DIM; j++) {
float x0 = (float) i / ATAN2_DIM;
float y0 = (float) j / ATAN2_DIM;
atan2[(j * ATAN2_DIM) + i] = (float) Math.atan2(y0, x0);
}
}
}
public static long pairInt(int x, int y) {
return (((long)x) << 32) | (y & 0xffffffffL);
}
@ -191,7 +190,8 @@ public class MathMan {
}
public static final float atan2(float y, float x) {
float add, mul;
float add;
float mul;
if (x < 0.0f) {
if (y < 0.0f) {
@ -229,7 +229,7 @@ public class MathMan {
}
public static double sqrtApprox(double d) {
return Double.longBitsToDouble(((Double.doubleToLongBits(d) - (1l << 52)) >> 1) + (1l << 61));
return Double.longBitsToDouble(((Double.doubleToLongBits(d) - (1L << 52)) >> 1) + (1L << 61));
}
public static float invSqrt(float x) {
@ -302,7 +302,7 @@ public class MathMan {
return x % y;
}
public static boolean isPowerOfTwo(int x) {
return (x & (x - 1)) == 0;
public static boolean isPowerOfTwo(int number) {
return (number & (number - 1)) == 0;
}
}

View File

@ -265,7 +265,7 @@ public class StringMan {
return sb.toString();
}
public Collection match(Collection col, String startsWith) {
public <T> Collection<T> match(Collection<T> col, String startsWith) {
if (col == null) {
return null;
}

View File

@ -59,8 +59,10 @@ public class UUIDHandler {
}
public static HashSet<UUID> getAllUUIDS() {
HashSet<UUID> uuids = new HashSet<>();
for (Plot plot : PS.get().getPlots()) {
final HashSet<UUID> uuids = new HashSet<>();
PS.get().foreachPlotRaw(new RunnableVal<Plot>() {
@Override
public void run(Plot plot) {
if (plot.hasOwner()) {
uuids.add(plot.owner);
uuids.addAll(plot.getTrusted());
@ -68,6 +70,7 @@ public class UUIDHandler {
uuids.addAll(plot.getDenied());
}
}
});
return uuids;
}

View File

@ -291,7 +291,7 @@ public class GlobalBlockQueue {
if (this.runnables.isEmpty()) {
return false;
}
final ConcurrentLinkedDeque<Runnable> tmp = new ConcurrentLinkedDeque<>(this.runnables);
final ArrayList<Runnable> tmp = new ArrayList<>(this.runnables);
this.runnables.clear();
for (final Runnable runnable : tmp) {
runnable.run();

View File

@ -18,7 +18,6 @@ import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
@ -26,9 +25,9 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
public class ExpireManager {
@ -217,23 +216,22 @@ public class ExpireManager {
return false;
}
this.running = 2;
final Set<Plot> plots = PS.get().getPlots();
final ConcurrentLinkedDeque<Plot> plots = new ConcurrentLinkedDeque<Plot>(PS.get().getPlots());
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
final Runnable task = this;
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
long start = System.currentTimeMillis();
Iterator<Plot> iterator = plots.iterator();
while (iterator.hasNext() && System.currentTimeMillis() - start < 2) {
while (!plots.isEmpty()) {
if (ExpireManager.this.running != 2) {
ExpireManager.this.running = 0;
return;
}
final Plot plot = iterator.next();
iterator.remove();
final Plot plot = plots.poll();
PlotArea area = plot.getArea();
final ArrayDeque<ExpiryTask> applicable = new ArrayDeque<>(tasks);
final Collection<ExpiryTask> expired = isExpired(applicable, plot);
@ -242,17 +240,27 @@ public class ExpireManager {
}
for (ExpiryTask expiryTask : expired) {
if (!expiryTask.needsAnalysis()) {
expiredTask.run(plot, this, expiryTask.requiresConfirmation());
expiredTask.run(plot, new Runnable() {
@Override
public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, expiryTask.requiresConfirmation());
return;
}
}
final Runnable task = this;
final RunnableVal<PlotAnalysis> handleAnalysis = new RunnableVal<PlotAnalysis>() {
@Override
public void run(final PlotAnalysis changed) {
passesComplexity(changed, expired, new RunnableVal<Boolean>() {
@Override
public void run(Boolean confirmation) {
expiredTask.run(plot, task, confirmation);
expiredTask.run(plot, new Runnable() {
@Override
public void run() {
TaskManager.IMP.taskLaterAsync(task, 1);
}
}, confirmation);
}
}, new Runnable() {
@Override
@ -280,7 +288,7 @@ public class ExpireManager {
}, new Runnable() {
@Override
public void run() {
task.run();
TaskManager.IMP.taskLaterAsync(task, 1);
}
});
} else {
@ -300,7 +308,7 @@ public class ExpireManager {
}
}, 86400000);
} else {
TaskManager.runTaskLaterAsync(this, 20);
TaskManager.runTaskLaterAsync(task, 20 * 10);
}
}
});

View File

@ -333,7 +333,11 @@ public abstract class Command {
if (!cmd.checkArgs(player, newArgs) || !cmd.canExecute(player, true)) {
return;
}
try {
cmd.execute(player, newArgs, confirm, whenDone);
} catch (CommandException e) {
e.perform(player);
}
}
public boolean checkArgs(PlotPlayer player, String[] args) {
@ -484,6 +488,25 @@ public abstract class Command {
return getCommandString() + " " + args + "]";
}
public Collection<Command> tabOf(PlotPlayer player, String[] input, boolean space, String... args) {
if (!space) {
return null;
}
List<Command> result = new ArrayList<>();
int index = input.length - (space ? 0 : 1);
for (String arg : args) {
arg = arg.replace(getCommandString() + " ", "");
String[] split = arg.split(" ");
if (split.length <= index) {
continue;
}
arg = StringMan.join(Arrays.copyOfRange(split, index, split.length), " ");
Command cmd = new Command(null, false, arg, getPermission(), getRequiredType(), null) {};
result.add(cmd);
}
return result;
}
public Collection<Command> tab(PlotPlayer player, String[] args, boolean space) {
switch (args.length) {
case 0:

View File

@ -75,11 +75,11 @@ public class PlotListener {
Optional<Boolean> flyFlag = plot.getFlag(Flags.FLY);
if (flyFlag.isPresent()) {
boolean flight = player.getFlight();
if (flyFlag.get() != player.getFlight()) {
PlotGameMode gamemode = player.getGameMode();
if (flight != (gamemode == PlotGameMode.CREATIVE || gamemode == PlotGameMode.SPECTATOR)) {
player.setPersistentMeta("flight", ByteArrayUtilities.booleanToBytes(player.getFlight()));
}
if (flyFlag.get() != player.getFlight()) {
player.setFlight(flyFlag.get());
}
}
@ -94,6 +94,17 @@ public class PlotListener {
}
}
}
Optional<PlotGameMode> guestGamemodeFlag = plot.getFlag(Flags.GUEST_GAMEMODE);
if (gamemodeFlag.isPresent()) {
if (player.getGameMode() != gamemodeFlag.get() && !plot.isAdded(player.getUUID())) {
if (!Permissions.hasPermission(player, "plots.gamemode.bypass")) {
player.setGameMode(gamemodeFlag.get());
} else {
MainUtil.sendMessage(player,
StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.getId(), "{gamemode}", gamemodeFlag.get()));
}
}
}
Optional<Long> timeFlag = plot.getFlag(Flags.TIME);
if (timeFlag.isPresent()) {
try {
@ -171,7 +182,10 @@ public class PlotListener {
if (pw == null) {
return true;
}
if (plot.getFlag(Flags.GAMEMODE).isPresent()) {
if (Flags.DENY_EXIT.isTrue(plot)) {
return false;
}
if (plot.getFlag(Flags.GAMEMODE).isPresent() || plot.getFlag(Flags.GUEST_GAMEMODE).isPresent()) {
if (player.getGameMode() != pw.GAMEMODE) {
if (!Permissions.hasPermission(player, "plots.gamemode.bypass")) {
player.setGameMode(pw.GAMEMODE);
@ -196,7 +210,8 @@ public class PlotListener {
for (UUID uuid : plot.getOwners()) {
PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if ((owner != null) && !owner.getUUID().equals(player.getUUID())) {
MainUtil.sendMessage(player, C.NOTIFY_LEAVE.s().replace("%player", player.getName()).replace("%plot", plot.getId().toString()));
MainUtil.sendMessage(owner, C.NOTIFY_LEAVE.s().replace("%player", player.getName()).replace("%plot", plot.getId()
.toString()));
}
}
}
@ -209,6 +224,8 @@ public class PlotListener {
PlotGameMode gameMode = player.getGameMode();
if (gameMode == PlotGameMode.SURVIVAL || gameMode == PlotGameMode.ADVENTURE) {
player.setFlight(false);
} else if (!player.getFlight()) {
player.setFlight(true);
}
}
}

View File

@ -48,11 +48,11 @@ public class WEManager {
if (area == null) {
return regions;
}
boolean allowMember = player.hasPermission("plots.worldedit.member");
for (Plot plot : area.getPlots()) {
if (!plot.isBasePlot() || (Settings.Done.RESTRICT_BUILDING && (plot.getFlag(Flags.DONE).isPresent()))) {
continue;
}
boolean allowMember = player.hasPermission("plots.worldedit.member");
if (allowMember && plot.isAdded(uuid) || !allowMember && (plot.isOwner(uuid) || plot.getTrusted().contains(uuid))) {
regions.addAll(plot.getRegions());
}

View File

@ -1,18 +1,15 @@
package com.intellectualcrafters.plot;
import static com.intellectualcrafters.plot.PS.log;
import com.intellectualcrafters.json.JSONArray;
import com.intellectualcrafters.json.JSONObject;
import com.intellectualcrafters.plot.util.StringMan;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import org.junit.Test;
public class UpdaterTest {
@ -30,7 +27,7 @@ public class UpdaterTest {
return buffer.toString();
} catch (IOException e) {
log("&dCould not check for updates (0)");
System.out.println("&dCould not check for updates (0)");
e.printStackTrace();
} finally {
try {

View File

@ -17,7 +17,7 @@ is to provide a lag-free and smooth experience.
### Developer Resources
* [JavaDocs] Link Temporarily Unavailable
* [Build Server] Link Temporarily Unavailable
* [Build Server] [![Build Status](http://ci.plotsquared.com/buildStatus/icon?job=PlotSquared)](http://ci.athion.net/job/PlotSquared/)
* [Maven Repo] Link Temporarily Unavailable
# Building

View File

@ -15,17 +15,22 @@ buildscript {
}
apply plugin: 'net.minecrell.vanilla.server.library'
apply plugin: 'com.github.johnrengelman.shadow'
dependencies {
compile project(':Core')
compile 'org.spongepowered:spongeapi:5.0.0-SNAPSHOT'
compile 'net.minecrell.mcstats:statslite-sponge:0.2.2'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
maven {
name = 'minecrell'
url = 'http://repo.minecrell.net/releases'
}
maven {
name = 'forge'
url = 'http://files.minecraftforge.net/maven'
@ -34,14 +39,10 @@ repositories {
name = "Sponge"
url = "https://repo.spongepowered.org/maven"
}
maven {
name = "Sponge Metrics"
url = "http://repo.mcstats.org/content/repositories/releases/"
}
}
minecraft {
version = "1.9.4"
mappings = "snapshot_20160530"
version = "1.10.2"
mappings = "snapshot_20160629"
runDir = 'run'
}
@ -56,9 +57,9 @@ processResources {
shadowJar {
dependencies {
include(dependency(':Core'))
//include(dependency('org.mcstats.sponge:metrics:R8-SNAPSHOT'))
include dependency('net.minecrell.mcstats:statslite-sponge')
}
//relocate 'org.mcstats', 'com.plotsquared.stats'
relocate 'net.minecrell.mcstats', 'com.plotsquared.util.mcstats'
archiveName = "${parent.name}-${project.name}-${parent.version}.jar"
destinationDir = file '../target'
}

View File

@ -41,7 +41,6 @@ import com.plotsquared.sponge.util.SpongeEconHandler;
import com.plotsquared.sponge.util.SpongeEventUtil;
import com.plotsquared.sponge.util.SpongeHybridUtils;
import com.plotsquared.sponge.util.SpongeInventoryUtil;
import com.plotsquared.sponge.util.SpongeMetrics;
import com.plotsquared.sponge.util.SpongeSchematicHandler;
import com.plotsquared.sponge.util.SpongeSetupUtils;
import com.plotsquared.sponge.util.SpongeTaskManager;
@ -51,13 +50,7 @@ import com.plotsquared.sponge.util.block.SpongeLocalQueue;
import com.plotsquared.sponge.uuid.SpongeLowerOfflineUUIDWrapper;
import com.plotsquared.sponge.uuid.SpongeOnlineUUIDWrapper;
import com.plotsquared.sponge.uuid.SpongeUUIDHandler;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import net.minecrell.mcstats.SpongeStatsLite;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.Server;
@ -66,6 +59,7 @@ import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameAboutToStartServerEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.profile.GameProfileManager;
@ -74,8 +68,16 @@ import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Plugin(id = "plotsquared", name = "PlotSquared", description = "Easy, yet powerful Plot World generation and management.",
url = "https://github.com/IntellectualSites/PlotSquared", version = "3.3.3")
url = "https://github.com/IntellectualSites/PlotSquared", version = "3.5.0-SNAPSHOT")
public class SpongeMain implements IPlotMain {
public static SpongeMain THIS;
@ -89,6 +91,9 @@ public class SpongeMain implements IPlotMain {
@Inject
private Game game;
@Inject
public SpongeStatsLite stats;
private Server server;
@Inject
@ -97,8 +102,7 @@ public class SpongeMain implements IPlotMain {
private GameProfileManager resolver;
// @Override
public Logger getLogger() {
private Logger getLogger() {
return this.logger;
}
@ -121,6 +125,12 @@ public class SpongeMain implements IPlotMain {
return THIS;
}
@Listener
public void onPreInitialize(GamePreInitializationEvent event) {
getLogger().info("The metrics section in PlotSquared is ignored in favor of the actual metrics reporter configurations.");
this.stats.start();
}
@Listener
public void onServerAboutToStart(GameAboutToStartServerEvent event) {
THIS = this;
@ -165,6 +175,10 @@ public class SpongeMain implements IPlotMain {
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), split.length == 3 ? Integer.parseInt(split[2]) : 0};
}
@Override public String getPluginVersionString() {
return this.plugin.getVersion().orElse("");
}
@Override
public int[] getServerVersion() {
PS.log("Checking minecraft version: Sponge: ");
@ -237,14 +251,11 @@ public class SpongeMain implements IPlotMain {
@Override
public void registerPlotPlusEvents() {
// TODO Auto-generated method stub
PS.log("registerPlotPlusEvents is not implemented!");
}
@Override
public void registerForceFieldEvents() {
// TODO Auto-generated method stub
PS.log("registerForceFieldEvents is not implemented!");
}
@Override
@ -288,16 +299,8 @@ public class SpongeMain implements IPlotMain {
Sponge.getEventManager().registerListeners(this, new WorldEvents());
}
@Override
public String getServerName() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override
public void startMetrics() {
SpongeMetrics metrics = new SpongeMetrics(this.game, this.plugin);
metrics.start();
PS.log(C.PREFIX.s() + "&6Metrics enabled.");
}
@Override
@ -328,7 +331,7 @@ public class SpongeMain implements IPlotMain {
if (gen instanceof SpongePlotGenerator) {
PS.get().loadWorld(worldName, (SpongePlotGenerator) gen);
} else {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET!");
throw new UnsupportedOperationException("NOT IMPLEMENTED YET! " + worldName + " | " + gen);
}
}
@ -341,6 +344,8 @@ public class SpongeMain implements IPlotMain {
public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) {
return SpongeUtil.getPlayer((Player) player);
} else if (UUIDHandler.implementation == null) {
return null;
} else if (player instanceof String) {
return UUIDHandler.getPlayer((String) player);
} else if (player instanceof UUID) {

View File

@ -1,81 +0,0 @@
package com.plotsquared.sponge;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.ConfigurationNode;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.PlotGenerator;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.plotsquared.sponge.generator.SpongePlotGenerator;
import com.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.gen.WorldGenerator;
import java.io.IOException;
import java.util.Map;
public class SpongeSetupUtils extends SetupUtils {
@Override
public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
return;
}
SetupUtils.generators.put("PlotSquared", new SpongePlotGenerator(new HybridGen()));
throw new UnsupportedOperationException("TODO FETCH EXTERNAL WorldGenerationModifiers");
}
@Override
public String getGenerator(final PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}
final World world = SpongeUtil.getWorld(plotArea.worldname);
if (world == null) {
return null;
}
final WorldGenerator generator = world.getWorldGenerator();
if (!(generator instanceof SpongePlotGenerator)) {
return null;
}
for (final Map.Entry<String, GeneratorWrapper<?>> entry : generators.entrySet()) {
GeneratorWrapper<?> current = entry.getValue();
if (current.equals(generator)) {
return entry.getKey();
}
}
return null;
}
@Override
public String setupWorld(final SetupObject object) {
SetupUtils.manager.updateGenerators();
final ConfigurationNode[] steps = object.step;
final String world = object.world;
for (final ConfigurationNode step : steps) {
PS.get().worlds.set("worlds." + world + "." + step.getConstant(), step.getValue());
}
if (object.type != 0) {
PS.get().worlds.set("worlds." + world + ".generator.type", object.type);
PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain);
PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager);
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager)) {
PS.get().worlds.set("worlds." + world + ".generator.init", object.setupGenerator);
}
final PlotGenerator<WorldGenerator> gen = (PlotGenerator<WorldGenerator>) generators.get(object.setupGenerator);
if ((gen != null) && (gen.generator instanceof SpongePlotGenerator)) {
object.setupGenerator = null;
}
}
try {
PS.get().worlds.save(PS.get().worldsFile);
} catch (final IOException e) {
e.printStackTrace();
}
// TODO FIXME
throw new UnsupportedOperationException("NOT IMPLEMENTED YET: Create a new world here");
// return object.world;
}
}

View File

@ -5,7 +5,6 @@ import com.intellectualcrafters.plot.generator.AugmentedUtils;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.block.DelegateLocalBlockQueue;
import com.plotsquared.sponge.util.SpongeUtil;
import java.util.List;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.ImmutableBiomeArea;
@ -13,6 +12,8 @@ import org.spongepowered.api.world.extent.MutableBlockVolume;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import java.util.List;
public class SpongeAugmentedGenerator implements GenerationPopulator {
private static SpongeAugmentedGenerator generator;
@ -44,14 +45,14 @@ public class SpongeAugmentedGenerator implements GenerationPopulator {
AugmentedUtils.generate(world.getName(), cx, cz, new DelegateLocalBlockQueue(null) {
@Override
public boolean setBlock(int x, int y, int z, int id, int data) {
terrain.setBlock(bx + x, y, bz + z, SpongeUtil.getBlockState(id, data));
terrain.setBlock(bx + x, y, bz + z, SpongeUtil.getBlockState(id, data), SpongeUtil.CAUSE);
return true;
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
BlockState block = terrain.getBlock(bx + x, y, bz + z);
return block == null ? PlotBlock.get(0, 0) : SpongeUtil.getPlotBlock(block);
return SpongeUtil.getPlotBlock(block);
}
@Override

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