file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
WGUtils.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/WGUtils.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.*;
public class WGUtils {
// Integer.MAX_VALUE/MIN_VALUE causes strange issues with WG not detecting players in regions,
// so we use the 16 bit limit, which is more than enough.
public static final int MAX_BUILD_HEIGHT = Short.MAX_VALUE;
public static final int MIN_BUILD_HEIGHT = Short.MIN_VALUE;
public static FlagRegistry getFlagRegistry() {
return WorldGuard.getInstance().getFlagRegistry();
}
public static RegionManager getRegionManagerWithPlayer(Player p) {
return WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(p.getWorld()));
}
/**
* Get a RegionManager from a world.
*
* @param w the world
* @return the region manager, or null if it is not found
*/
public static RegionManager getRegionManagerWithWorld(World w) {
if (w == null) return null;
return WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(w));
}
/**
* Get all region managers for all worlds.
* Use this instead of looping worlds manually because some worlds may not have a region manager.
*
* @return returns all region managers from all worlds
*/
public static HashMap<World, RegionManager> getAllRegionManagers() {
HashMap<World, RegionManager> m = new HashMap<>();
for (World w : Bukkit.getWorlds()) {
RegionManager rgm = getRegionManagerWithWorld(w);
if (rgm != null) m.put(w, rgm);
}
return m;
}
// Turn WG region name into a location (ex. ps138x35y358z)
public static PSLocation parsePSRegionToLocation(String regionId) {
int psx = Integer.parseInt(regionId.substring(2, regionId.indexOf("x")));
int psy = Integer.parseInt(regionId.substring(regionId.indexOf("x") + 1, regionId.indexOf("y")));
int psz = Integer.parseInt(regionId.substring(regionId.indexOf("y") + 1, regionId.length() - 1));
return new PSLocation(psx, psy, psz);
}
/**
* Find regions that are overlapping or adjacent to the region given.
* @param r
* @param rgm
* @param w
* @return the list of regions
*/
public static Set<ProtectedRegion> findOverlapOrAdjacentRegions(ProtectedRegion r, RegionManager rgm, World w) {
HashSet<ProtectedRegion> overlappingRegions = new HashSet<>(rgm.getApplicableRegions(r).getRegions()); // we need to ensure addAll is implemented
// find adjacent regions (not overlapping, but bordering)
for (var edgeRegion : getTransientEdgeRegions(w, r)) {
overlappingRegions.addAll(rgm.getApplicableRegions(edgeRegion).getRegions());
}
// HACK: WORKAROUND FOR BUG
// We have a major issue with detecting adjacent regions when the other regions are PSGroupRegion (the one adjacent
// to the current one), which is likely a WorldGuard bug?
//
// If you create an adjacent region south or east of the region, it seems that it doesn't detect the adjacent edge
// overlap, you need to increase the edge by one more block for the north and west (2 blocks from region edge).
for (var edgeRegion : getTransientEdgeRegionsHelper(w, r, true)) {
for (var region : rgm.getApplicableRegions(edgeRegion).getRegions()) {
PSRegion psr = PSRegion.fromWGRegion(w, region);
if (psr instanceof PSGroupRegion) {
overlappingRegions.add(region);
}
}
}
return overlappingRegions;
}
/**
* Find regions that are overlapping or adjacent to the region given.
* @param r
* @param regionsToCheck
* @param w
* @return the list of regions
*/
public static Set<ProtectedRegion> findOverlapOrAdjacentRegions(ProtectedRegion r, List<ProtectedRegion> regionsToCheck, World w) {
HashSet<ProtectedRegion> overlappingRegions = new HashSet<>(r.getIntersectingRegions(regionsToCheck)); // we need to ensure addAll is implemented
// find adjacent regions (not overlapping, but bordering)
for (var edgeRegion : getTransientEdgeRegions(w, r)) {
overlappingRegions.addAll(edgeRegion.getIntersectingRegions(regionsToCheck));
}
// HACK: WORKAROUND FOR BUG
// We have a major issue with detecting adjacent regions when the other regions are PSGroupRegion (the one adjacent
// to the current one), which is likely a WorldGuard bug?
//
// If you create an adjacent region south or east of the region, it seems that it doesn't detect the adjacent edge
// overlap, you need to increase the edge by one more block for the north and west (2 blocks from region edge).
for (var edgeRegion : getTransientEdgeRegionsHelper(w, r, true)) {
for (var region : edgeRegion.getIntersectingRegions(regionsToCheck)) {
PSRegion psr = PSRegion.fromWGRegion(w, region);
if (psr instanceof PSGroupRegion) {
overlappingRegions.add(region);
}
}
}
return overlappingRegions;
}
/**
* Find the list of regions that border `r` (adjacent to the edge), but do not include the corners.
* @param r region
* @return the list of regions
*/
public static List<ProtectedRegion> getTransientEdgeRegions(World w, ProtectedRegion r) {
return getTransientEdgeRegionsHelper(w, r, false);
}
private static List<ProtectedRegion> getTransientEdgeRegionsHelper(World w, ProtectedRegion r, boolean oneBlockAdjustHack) {
ArrayList<ProtectedRegion> toReturn = new ArrayList<>();
PSRegion psr = PSRegion.fromWGRegion(w, r);
// note that PSGroupRegion is a subclass of PSStandardRegion, so we need PSGroupRegion check first
if (r instanceof ProtectedPolygonalRegion && psr instanceof PSGroupRegion) {
PSGroupRegion psgr = (PSGroupRegion) PSRegion.fromWGRegion(w, r);
for (PSMergedRegion psmr : psgr.getMergedRegions()) {
var testRegion = getDefaultProtectedRegion(psmr.getTypeOptions(), WGUtils.parsePSRegionToLocation(psmr.getId()));
toReturn.addAll(getTransientEdgeRegionsHelper(w, testRegion, oneBlockAdjustHack));
}
} else if (r instanceof ProtectedCuboidRegion || (psr instanceof PSStandardRegion)) {
BlockVector3 minPoint = r.getMinimumPoint(), maxPoint = r.getMaximumPoint();
long minX = minPoint.getX(), maxX = maxPoint.getX(), minY = minPoint.getY(),
maxY = maxPoint.getY(), minZ = minPoint.getZ(), maxZ = maxPoint.getZ();
toReturn = new ArrayList<>(
Arrays.asList(
new ProtectedCuboidRegion(r.getId() + "-edge-0", true, BlockVector3.at(minX, minY - 1, minZ), BlockVector3.at(maxX, maxY + 1, maxZ)),
new ProtectedCuboidRegion(r.getId() + "-edge-1", true, BlockVector3.at(minX - 1, minY, minZ), BlockVector3.at(maxX + 1, maxY, maxZ)),
new ProtectedCuboidRegion(r.getId() + "-edge-2", true, BlockVector3.at(minX, minY, minZ - 1), BlockVector3.at(maxX, maxY, maxZ + 1))
)
);
if (oneBlockAdjustHack) {
// one block extra in the north
toReturn.add(new ProtectedCuboidRegion(r.getId() + "-edge-3", true, BlockVector3.at(minX, minY, minZ - 2), BlockVector3.at(maxX, maxY, maxZ)));
// one block extra in the west
toReturn.add(new ProtectedCuboidRegion(r.getId() + "-edge-4", true, BlockVector3.at(minX - 2, minY, minZ), BlockVector3.at(maxX, maxY, maxZ)));
}
}
return toReturn;
}
// whether region overlaps an unowned region that is more priority
public static boolean overlapsStrongerRegion(World w, ProtectedRegion r, LocalPlayer lp) {
RegionManager rgm = WGUtils.getRegionManagerWithWorld(w);
ApplicableRegionSet rp = rgm.getApplicableRegions(r);
// loop through all regions to check for "none" option
for (ProtectedRegion rg : rp.getRegions()) {
if (rg.getId().equals(r.getId())) continue;
if (ProtectionStones.isPSRegion(rg)) {
PSRegion psr = PSRegion.fromWGRegion(w, rg);
// if no overlap allowed by this region type, even if owner
if (psr.getTypeOptions().allowOtherRegionsToOverlap.equals("none")) {
return true;
}
}
}
if (rgm.overlapsUnownedRegion(r, lp)) { // check if the lp is not owner of a intersecting region
for (ProtectedRegion rg : rp) {
// ignore itself it has already has been added to the rgm
if (rg.getId().equals(r.getId())) continue;
if (rg.isOwner(lp)) continue;
if (rg.getPriority() > r.getPriority()) { // if protection priority < overlap priority
return true;
}
// check ProtectionStones allow_other_regions_to_overlap settings
if (ProtectionStones.isPSRegion(rg)) {
PSRegion pr = PSRegion.fromWGRegion(w, rg);
// don't need to check for owner, since all of these are unowned regions.
if (pr.isMember(lp.getUniqueId()) && pr.getTypeOptions().allowOtherRegionsToOverlap.equals("member")) {
// if members are allowed to overlap this region
continue;
}
if (pr.getTypeOptions().allowOtherRegionsToOverlap.equals("all")) {
// if everyone is allowed to overlap this region
continue;
}
// otherwise, this region is not allowed to be overlapped
return true;
} else if (rg.getPriority() >= r.getPriority()) { // if the priorities are the same for plain WorldGuard regions, prevent overlap
return true;
}
}
}
return false;
}
// returns "" if there is no psregion
public static String matchLocationToPSID(Location l) {
BlockVector3 v = BlockVector3.at(l.getX(), l.getY(), l.getZ());
String currentPSID = "";
RegionManager rgm = WGUtils.getRegionManagerWithWorld(l.getWorld());
List<String> idList = rgm.getApplicableRegionsIDs(v);
if (idList.size() == 1) { // if the location is only in one region
if (ProtectionStones.isPSRegionFormat(rgm.getRegion(idList.get(0)))) {
currentPSID = idList.get(0);
}
} else {
// Get the nearest protection stone if in overlapping region
double distanceToPS = -1, tempToPS;
for (String currentID : idList) {
if (ProtectionStones.isPSRegionFormat(rgm.getRegion(currentID))) {
PSLocation psl = WGUtils.parsePSRegionToLocation(currentID);
Location psLocation = new Location(l.getWorld(), psl.x, psl.y, psl.z);
tempToPS = l.distance(psLocation);
if (distanceToPS == -1 || tempToPS < distanceToPS) {
distanceToPS = tempToPS;
currentPSID = currentID;
}
}
}
}
return currentPSID;
}
public static BlockVector3 getMinVector(double bx, double by, double bz, long xRadius, long yRadius, long zRadius) {
return BlockVector3.at(bx - xRadius, (yRadius == -1) ? MIN_BUILD_HEIGHT : by - yRadius, bz - zRadius);
}
public static BlockVector3 getMaxVector(double bx, double by, double bz, long xRadius, long yRadius, long zRadius) {
return BlockVector3.at(bx + xRadius, (yRadius == -1) ? MAX_BUILD_HEIGHT : by + yRadius, bz + zRadius);
}
public static BlockVector3 getMinChunkVector(double bx, double by, double bz, long chunkRadius, long yRadius) {
--chunkRadius; // this becomes chunk offset from centre chunk, not radius
long chunkX = (long) Math.floor(bx / 16);
long chunkZ = (long) Math.floor(bz / 16);
return BlockVector3.at((chunkX - chunkRadius) * 16, (yRadius == -1) ? MIN_BUILD_HEIGHT : by - yRadius, (chunkZ - chunkRadius) * 16);
}
public static BlockVector3 getMaxChunkVector(double bx, double by, double bz, long chunkRadius, long yRadius) {
--chunkRadius; // this becomes chunk offset from centre chunk, not radius
long chunkX = (long) Math.floor(bx / 16);
long chunkZ = (long) Math.floor(bz / 16);
return BlockVector3.at((chunkX + chunkRadius) * 16 + 15, (yRadius == -1) ? MAX_BUILD_HEIGHT : by + yRadius, (chunkZ + chunkRadius) * 16 + 15);
}
// create PS ids without making the numbers have scientific notation (addressed with long)
public static String createPSID(double bx, double by, double bz) {
return "ps" + (long) bx + "x" + (long) by + "y" + (long) bz + "z";
}
public static String createPSID(Location l) {
return createPSID(l.getX(), l.getY(), l.getZ());
}
public static boolean hasNoAccess(ProtectedRegion region, Player p, LocalPlayer lp, boolean canBeMember) {
if (region == null) return true;
return !p.hasPermission("protectionstones.superowner") && !region.isOwner(lp) && (!canBeMember || !region.isMember(lp));
}
// get the overlapping sets of groups of regions a player owns
public static HashMap<String, ArrayList<String>> getPlayerAdjacentRegionGroups(Player p, RegionManager rm) {
PSPlayer psp = PSPlayer.fromPlayer(p);
List<PSRegion> pRegions = psp.getPSRegions(p.getWorld(), false);
HashMap<String, String> idToGroup = new HashMap<>();
HashMap<String, ArrayList<String>> groupToIDs = new HashMap<>();
for (PSRegion r : pRegions) {
Set<ProtectedRegion> overlapping = findOverlapOrAdjacentRegions(r.getWGRegion(), r.getWGRegionManager(), r.getWorld());
// algorithm to find adjacent regions
String adjacentGroup = idToGroup.get(r.getId());
for (ProtectedRegion pr : overlapping) {
if (ProtectionStones.isPSRegion(pr) && pr.isOwner(WorldGuardPlugin.inst().wrapPlayer(p)) && !pr.getId().equals(r.getId())) {
if (adjacentGroup == null) { // if the region hasn't been found to overlap a region yet
if (idToGroup.get(pr.getId()) == null) { // if the overlapped region isn't part of a group yet
idToGroup.put(pr.getId(), r.getId());
idToGroup.put(r.getId(), r.getId());
groupToIDs.put(r.getId(), new ArrayList<>(Arrays.asList(pr.getId(), r.getId()))); // create new group
} else { // if the overlapped region is part of a group
String groupID = idToGroup.get(pr.getId());
idToGroup.put(r.getId(), groupID);
groupToIDs.get(groupID).add(r.getId());
}
adjacentGroup = idToGroup.get(r.getId());
} else { // if the region is part of a group already
if (idToGroup.get(pr.getId()) == null) { // if the overlapped region isn't part of a group
idToGroup.put(pr.getId(), adjacentGroup);
groupToIDs.get(adjacentGroup).add(pr.getId());
} else if (!idToGroup.get(pr.getId()).equals(adjacentGroup)) { // if the overlapped region is part of a group, merge the groups
String mergeGroupID = idToGroup.get(pr.getId());
for (String gid : groupToIDs.get(mergeGroupID)) {
idToGroup.put(gid, adjacentGroup);
}
groupToIDs.get(adjacentGroup).addAll(groupToIDs.get(mergeGroupID));
groupToIDs.remove(mergeGroupID);
}
}
}
}
if (adjacentGroup == null) {
idToGroup.put(r.getId(), r.getId());
groupToIDs.put(r.getId(), new ArrayList<>(Collections.singletonList(r.getId())));
}
}
return groupToIDs;
}
public static ProtectedCuboidRegion getDefaultProtectedRegion(PSProtectBlock b, PSLocation v) {
BlockVector3 min, max;
if (b.chunkRadius > 0) {
min = getMinChunkVector(v.x, v.y, v.z, b.chunkRadius, b.yRadius);
max = getMaxChunkVector(v.x, v.y, v.z, b.chunkRadius, b.yRadius);
} else {
min = getMinVector(v.x, v.y, v.z, b.xRadius, b.yRadius, b.zRadius);
max = getMaxVector(v.x, v.y, v.z, b.xRadius, b.yRadius, b.zRadius);
}
return new ProtectedCuboidRegion(createPSID(v.x, v.y, v.z), min, max);
}
public static List<BlockVector2> getPointsFromDecomposedRegion(PSRegion r) {
assert r.getPoints().size() == 4;
List<Integer> xs = new ArrayList<>(), zs = new ArrayList<>();
for (BlockVector2 p : r.getPoints()) {
if (!xs.contains(p.getX())) xs.add(p.getX());
if (!zs.contains(p.getZ())) zs.add(p.getZ());
}
List<BlockVector2> points = new ArrayList<>();
for (int x = xs.get(0); x != xs.get(1); x += (xs.get(0) > xs.get(1)) ? -1 : 1) {
points.add(BlockVector2.at(x, zs.get(0)));
points.add(BlockVector2.at(x, zs.get(1)));
}
for (int z = zs.get(0); z != zs.get(1); z += (zs.get(0) > zs.get(1)) ? -1 : 1) {
points.add(BlockVector2.at(xs.get(0), z));
points.add(BlockVector2.at(xs.get(1), z));
}
return points;
}
public static boolean canMergeRegionTypes(PSProtectBlock current, PSRegion mergeInto) {
if (current.allowedMergingIntoTypes.contains("all"))
return true;
if (mergeInto instanceof PSGroupRegion) {
for (PSMergedRegion r : ((PSGroupRegion) mergeInto).getMergedRegions()) {
if (!current.allowedMergingIntoTypes.contains(r.getTypeOptions().alias))
return false;
}
}
return current.allowedMergingIntoTypes.contains(mergeInto.getTypeOptions().alias);
}
// set a flag on a region, only saving it to db if it is actually a new value
// prevents unnecessary messages in the console from saves
public static <T extends com.sk89q.worldguard.protection.flags.Flag<String>> void setFlagIfNeeded(ProtectedRegion region, T flag, String value) {
String curValue = region.getFlag(flag);
if ((curValue == null && value == null) || (curValue != null && !curValue.equals(value))) {
region.setFlag(flag, value);
}
}
public static <T extends com.sk89q.worldguard.protection.flags.Flag<Set<V>>, V> void setFlagIfNeeded(ProtectedRegion region, T flag, Set<V> value) {
Set<V> curValue = region.getFlag(flag);
if (!checkCollectionEquality(curValue, value)) {
region.setFlag(flag, value);
}
}
public static <T extends com.sk89q.worldguard.protection.flags.Flag<List<V>>, V> void setFlagIfNeeded(ProtectedRegion region, T flag, List<V> value) {
List<V> curValue = region.getFlag(flag);
if (!checkCollectionEquality(curValue, value)) {
region.setFlag(flag, value);
}
}
private static <V> boolean checkCollectionEquality(Collection<V> col1, Collection<V> col2) {
// check if any are null
if (col1 == null || col2 == null) {
return col1 == col2;
}
// check length
if (col1.size() != col2.size()) {
return false;
}
var iterator1 = col1.iterator();
var iterator2 = col2.iterator();
// check individual values if they are exactly the same
while (iterator1.hasNext()) {
if (!iterator1.next().equals(iterator2.next())) {
return false;
}
}
return true;
}
}
| 21,943 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
BlockUtil.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/BlockUtil.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils;
import dev.espi.protectionstones.PSProtectBlock;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.block.Skull;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.HashMap;
import java.util.UUID;
public class BlockUtil {
static final int MAX_USERNAME_LENGTH = 16;
public static HashMap<String, String> uuidToBase64Head = new HashMap<>();
public static ItemStack getProtectBlockItemFromType(String type) {
if (type.startsWith(Material.PLAYER_HEAD.toString())) {
return new ItemStack(Material.PLAYER_HEAD);
} else {
return new ItemStack(Material.getMaterial(type));
}
}
// used for preventing unnecessary calls to .getOwningPlayer() which could cause server freezes
private static boolean isOwnedSkullTypeConfigured() {
for (PSProtectBlock b : ProtectionStones.getInstance().getConfiguredBlocks()) {
if (b.type.startsWith("PLAYER_HEAD:")) {
return true;
}
}
return false;
}
public static String getProtectBlockType(ItemStack i) {
if (i.getType() == Material.PLAYER_HEAD || i.getType() == Material.LEGACY_SKULL_ITEM) {
SkullMeta sm = (SkullMeta) i.getItemMeta();
// PLAYER_HEAD
if (!sm.hasOwner() || !isOwnedSkullTypeConfigured()) {
return Material.PLAYER_HEAD.toString();
}
// PLAYER_HEAD:base64
if (ProtectionStones.getBlockOptions("PLAYER_HEAD:" + sm.getOwningPlayer().getUniqueId()) != null) {
return Material.PLAYER_HEAD + ":" + sm.getOwningPlayer().getUniqueId();
}
// PLAYER_HEAD:name
return Material.PLAYER_HEAD + ":" + sm.getOwningPlayer().getName(); // return name if it doesn't exist
}
return i.getType().toString();
}
public static String getProtectBlockType(Block block) {
if (block.getType() == Material.PLAYER_HEAD || block.getType() == Material.PLAYER_WALL_HEAD) {
Skull s = (Skull) block.getState();
if (s.hasOwner() && isOwnedSkullTypeConfigured()) {
OfflinePlayer op = s.getOwningPlayer();
if (ProtectionStones.getBlockOptions("PLAYER_HEAD:" + op.getUniqueId()) != null) {
// PLAYER_HEAD:base64
return Material.PLAYER_HEAD + ":" + op.getUniqueId();
} else {
// PLAYER_HEAD:name
return Material.PLAYER_HEAD + ":" + op.getName(); // return name if doesn't exist
}
} else { // PLAYER_HEAD
return Material.PLAYER_HEAD.toString();
}
} else if (block.getType() == Material.CREEPER_WALL_HEAD) {
return Material.CREEPER_HEAD.toString();
} else if (block.getType() == Material.DRAGON_WALL_HEAD) {
return Material.DRAGON_HEAD.toString();
} else if (block.getType() == Material.ZOMBIE_WALL_HEAD) {
return Material.ZOMBIE_HEAD.toString();
} else if (block.getType() == Material.SKELETON_WALL_SKULL) {
return Material.SKELETON_SKULL.toString();
} else if (block.getType() == Material.WITHER_SKELETON_WALL_SKULL) {
return Material.WITHER_SKELETON_SKULL.toString();
} else {
return block.getType().toString();
}
}
public static void setHeadType(String psType, Block b) {
if (psType.split(":").length < 2) return;
String name = psType.split(":")[1];
if (name.length() > MAX_USERNAME_LENGTH) {
blockWithBase64(b, name);
} else {
OfflinePlayer op = Bukkit.getOfflinePlayer(psType.split(":")[1]);
Skull s = (Skull) b.getState();
s.setOwningPlayer(op);
s.update();
}
}
public static ItemStack setHeadType(String psType, ItemStack item) {
String name = psType.split(":")[1];
if (name.length() > MAX_USERNAME_LENGTH) { // base 64 head
String uuid = name;
// if 1.16 or above, use new uuid format
if (Integer.parseInt(MiscUtil.getVersionString().split("\\.")[1]) >= 16 || !MiscUtil.getVersionString().split("\\.")[0].equals("1")) {
uuid = MiscUtil.getUniqueIdIntArray(UUID.fromString(uuid));
} else { // quotes are needed for pre 1.16 uuids
uuid = "\"" + uuid + "\"";
}
return Bukkit.getUnsafe().modifyItemStack(item, "{SkullOwner:{Name:\"" + name + "\",Id:" + uuid + ",Properties:{textures:[{Value:\"" + uuidToBase64Head.get(name) + "\"}]}}}");
} else { // normal name head
SkullMeta sm = (SkullMeta) item.getItemMeta();
sm.setOwningPlayer(Bukkit.getOfflinePlayer(name));
item.setItemMeta(sm);
return item;
}
}
// Note: this code is really weird
private static void blockWithBase64(Block block, String uuid) {
String base64 = uuidToBase64Head.get(uuid), args;
// if 1.16 or above, use new uuid format
if (Integer.parseInt(MiscUtil.getVersionString().split("\\.")[1]) >= 16 || !MiscUtil.getVersionString().split("\\.")[0].equals("1")) {
uuid = MiscUtil.getUniqueIdIntArray(UUID.fromString(uuid));
args = String.format(
"%d %d %d %s",
block.getX(),
block.getY(),
block.getZ(),
"{SkullOwner:{Name:\"" + uuid + "\",Id:" + uuid + ",Properties:{textures:[{Value:\"" + base64 + "\"}]}}}"
);
} else { // tag was different pre 1.16
args = String.format(
"%d %d %d %s",
block.getX(),
block.getY(),
block.getZ(),
"{Owner:{Name:\"" + uuid + "\",Id:\"" + uuid + "\",Properties:{textures:[{Value:\"" + base64 + "\"}]}}}"
);
}
// fake entity to run command at its location
Entity e = block.getWorld().spawn(new Location(block.getWorld(), 0, 0, 0), ArmorStand.class, ent -> {
ent.setCustomName("mrpig");
ent.setInvulnerable(true);
ent.setVisible(false);
});
// run data command to change block using the pig's world
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "execute at @e[type=armor_stand,nbt={CustomName:'{\"extra\":[{\"text\":\"" + e.getName() + "\"}],\"text\":\"\"}'}] run data merge block " + args);
e.remove();
}
public static boolean isBase64PSHead(String type) {
return type.startsWith("PLAYER_HEAD") && type.split(":").length > 1 && type.split(":")[1].length() > MAX_USERNAME_LENGTH;
}
public static String getUUIDFromBase64PS(PSProtectBlock b) {
String base64 = b.type.split(":")[1];
// return UUID.nameUUIDFromBytes(base64.getBytes()).toString(); <- I should be using this
// the below is bad, because hashcode should really not be used... unfortunately, this is used in production so it will have to stay like this
// until I can find a way to convert items to the new uuid
// see github issue #126
return new UUID(base64.hashCode(), base64.hashCode()).toString();
}
}
| 8,300 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
RegionTraverse.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/RegionTraverse.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.Vector2;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.function.Consumer;
public class RegionTraverse {
private static final ArrayList<Vector2> DIRECTIONS = new ArrayList<>(Arrays.asList(Vector2.at(0, 1), Vector2.at(1, 0), Vector2.at(-1, 0), Vector2.at(0, -1)));
private static final ArrayList<Vector2> CORNER_DIRECTIONS = new ArrayList<>(Arrays.asList(Vector2.at(1, 1), Vector2.at(-1, -1), Vector2.at(-1, 1), Vector2.at(1, -1)));
public static class TraverseReturn {
public BlockVector2 point;
public boolean isVertex;
public int vertexGroupID;
public int numberOfExposedEdges;
public TraverseReturn(BlockVector2 point, boolean isVertex, int vertexGroupID, int numberOfExposedEdges) {
this.point = point;
this.isVertex = isVertex;
this.vertexGroupID = vertexGroupID;
this.numberOfExposedEdges = numberOfExposedEdges;
}
}
private static class TraverseData {
BlockVector2 v, previous;
boolean first;
TraverseData(BlockVector2 v, BlockVector2 previous, boolean first) {
this.v = v;
this.previous = previous;
this.first = first;
}
}
private static boolean isInRegion(BlockVector2 point, List<ProtectedRegion> regions) {
for (ProtectedRegion r : regions)
if (r.contains(point)) return true;
return false;
}
// can't use recursion because stack overflow
// doesn't do so well with 1 block wide segments jutting out
public static void traverseRegionEdge(HashSet<BlockVector2> points, List<ProtectedRegion> regions, Consumer<TraverseReturn> run) {
int pointID = 0;
while (!points.isEmpty()) {
BlockVector2 start = points.iterator().next();
TraverseData td = new TraverseData(start, null, true);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ algorithm starts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
boolean cont = true;
while (cont) {
cont = false;
BlockVector2 v = td.v, previous = td.previous;
if (!td.first && v.equals(start)) break;
int exposedEdges = 0;
List<BlockVector2> insideVertex = new ArrayList<>();
for (Vector2 dir : DIRECTIONS) {
BlockVector2 test = BlockVector2.at(v.getX() + dir.getX(), v.getZ() + dir.getZ());
if (!isInRegion(test, regions)) {
exposedEdges++;
} else {
insideVertex.add(test);
}
}
points.remove(v); // remove current point if it exists
switch (exposedEdges) {
case 1: // normal edge
run.accept(new TraverseReturn(v, false, pointID, exposedEdges)); // run consumer
if (previous == null) { // if this is the first node we need to determine a direction to go to (that isn't into the polygon, but is on edge)
if (insideVertex.get(0).getX() == insideVertex.get(1).getZ() || insideVertex.get(0).getZ() == insideVertex.get(1).getZ() || insideVertex.get(0).getX() == insideVertex.get(2).getZ() || insideVertex.get(0).getZ() == insideVertex.get(2).getZ()) {
previous = insideVertex.get(0);
} else {
previous = insideVertex.get(1);
}
}
td = new TraverseData(BlockVector2.at(v.getX() + (v.getX() - previous.getX()), v.getZ() + (v.getZ() - previous.getZ())), v, false);
cont = true;
break;
case 2: // convex vertex
// possibly also 1 block wide segment with 2 edges opposite, but we'll ignore that
run.accept(new TraverseReturn(v, true, pointID, exposedEdges)); // run consumer
if (insideVertex.get(0).equals(previous)) {
td = new TraverseData(insideVertex.get(1), v, false);
cont = true;
} else {
td = new TraverseData(insideVertex.get(0), v, false);
cont = true;
}
break;
case 3: // random 1x1 jutting out
//if (isInRegion(v, regions)) ProtectionStones.getInstance().getLogger().info("Reached impossible situation in region edge traversal at " + v.getX() + " " + v.getZ() + ", please notify the developers that you saw this message!");
// it's fine right now but it'd be nice if it worked
break;
case 0: // concave vertex, or point in middle of region
List<Vector2> cornersNotIn = new ArrayList<>();
for (Vector2 dir : CORNER_DIRECTIONS) {
BlockVector2 test = BlockVector2.at(v.getX() + dir.getX(), v.getZ() + dir.getZ());
if (!isInRegion(test, regions)) cornersNotIn.add(dir);
}
if (cornersNotIn.size() == 1) { // concave vertex
run.accept(new TraverseReturn(v, true, pointID, exposedEdges)); // run consumer
Vector2 dir = cornersNotIn.get(0);
if (previous == null || previous.equals(BlockVector2.at(v.getX() + dir.getX(), v.getZ()))) {
td = new TraverseData(BlockVector2.at(v.getX(), v.getZ() + dir.getZ()), v, false);
cont = true;
} else {
td = new TraverseData(BlockVector2.at(v.getX() + dir.getX(), v.getZ()), v, false);
cont = true;
}
} else if (cornersNotIn.size() == 2) { // 1 block diagonal perfect overlap
run.accept(new TraverseReturn(v, false, pointID, exposedEdges)); // run consumer
if (previous == null) previous = insideVertex.get(0);
td = new TraverseData(BlockVector2.at(v.getX() + (v.getX() - previous.getX()), v.getZ() + (v.getZ() - previous.getZ())), v, false);
cont = true;
}
// ignore if in middle of region (cornersNotIn size = 0)
break;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ algorithm ends ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pointID++;
}
}
}
| 7,816 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
MiscUtil.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/MiscUtil.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils;
import dev.espi.protectionstones.ProtectionStones;
import net.luckperms.api.model.user.User;
import net.luckperms.api.model.user.UserManager;
import net.luckperms.api.node.Node;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class MiscUtil {
public static String getUniqueIdIntArray(UUID uuid) {
long least = uuid.getMostSignificantBits();
long most = uuid.getLeastSignificantBits();
int[] arr = new int[]{(int) (least >> 32), (int) least, (int) (most >> 32), (int) most};
return String.format("[I; %d, %d, %d, %d]", arr[0], arr[1], arr[2], arr[3]);
}
public static String getVersionString() {
return Bukkit.getBukkitVersion().split("-")[0];
}
public static Duration parseRentPeriod(String period) throws NumberFormatException {
Duration rentPeriod = Duration.ZERO;
for (String s : period.split(" ")) {
if (s.contains("w")) {
rentPeriod = rentPeriod.plusDays(Long.parseLong(s.replace("w", "")) * 7);
} else if (s.contains("d")) {
rentPeriod = rentPeriod.plusDays(Long.parseLong(s.replace("d", "")));
} else if (s.contains("h")) {
rentPeriod = rentPeriod.plusHours(Long.parseLong(s.replace("h", "")));
} else if (s.contains("m")) {
rentPeriod = rentPeriod.plusMinutes(Long.parseLong(s.replace("m", "")));
} else if (s.contains("s")) {
rentPeriod = rentPeriod.plusSeconds(Long.parseLong(s.replace("s", "")));
}
}
return rentPeriod;
}
public static int getPermissionNumber(Player p, String perm, int def) {
return getPermissionNumber(p.getEffectivePermissions().stream().map(PermissionAttachmentInfo::getPermission).collect(Collectors.toList()), perm, def);
}
public static int getPermissionNumber(List<String> permissions, String perm, int def /* default */) {
int n = -99999;
for (String permission : permissions) {
if (permission.startsWith(perm)) {
String value = permission.substring(perm.length());
if (MiscUtil.isValidInteger(value)) {
n = Math.max(n, Integer.parseInt(value));
}
}
}
return n == -99999 ? def : n;
}
public static String concatWithoutLast(List<String> l, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < l.size(); i++) {
sb.append(l.get(i)).append(i == l.size()-1 ? "" : separator);
}
return sb.toString();
}
public static String describeDuration(Duration duration) {
long days = duration.toDays();
duration = duration.minusDays(days);
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.toMillis() / 1000;
String s = "";
if (days != 0) s += days + "d";
if (hours != 0) s += hours + "h";
if (minutes != 0) s += minutes + "m";
if (seconds != 0) s += seconds + "s";
return s;
}
public static List<String> getLuckPermsUserPermissions(UUID uniqueId) throws ExecutionException, InterruptedException {
UserManager userManager = ProtectionStones.getInstance().getLuckPerms().getUserManager();
User user = userManager.loadUser(uniqueId).get();
List<String> permissions = new ArrayList<>();
// add permissions set on the user
permissions.addAll(user.getNodes().stream().filter(Node::getValue).map(Node::getKey).collect(Collectors.toList()));
// add permissions set on the groups
permissions.addAll(user.getInheritedGroups(user.getQueryOptions())
.stream()
.flatMap(g -> g.getNodes()
.stream()
.filter(Node::getValue)
.map(Node::getKey))
.collect(Collectors.toList()));
return permissions;
}
public static boolean isValidInteger(String str) {
if (str == null) {
return false;
}
try {
// this apparently throws NumberFormatException if it is beyond the integer limit, so we catch that
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
} catch (NullPointerException e) {}
return false;
}
}
| 5,550 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
RecipeUtil.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/RecipeUtil.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.utils;
import dev.espi.protectionstones.PSProtectBlock;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.RecipeChoice;
import org.bukkit.inventory.ShapedRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class RecipeUtil {
private static List<NamespacedKey> recipes = new ArrayList<>();
public static void setupPSRecipes() {
for (PSProtectBlock b : ProtectionStones.getInstance().getConfiguredBlocks()) {
// add custom recipes to Bukkit
if (b.allowCraftWithCustomRecipe) {
try {
Bukkit.addRecipe(parseRecipe(b));
recipes.add(getNamespacedKeyForBlock(b));
} catch (IllegalStateException e) {
ProtectionStones.getPluginLogger().warning("Reloading custom recipes does not work right now, you have to restart the server for updated recipes.");
}
}
}
}
public static void removePSRecipes() {
// remove previous protectionstones recipes (/ps reload)
Iterator<Recipe> iter = Bukkit.getServer().recipeIterator();
while (iter.hasNext()) {
try {
Recipe r = iter.next();
if (r instanceof ShapedRecipe && (((ShapedRecipe) r).getKey().getNamespace().equalsIgnoreCase(ProtectionStones.getInstance().getName()))) {
iter.remove();
}
} catch (Exception ignored) {
}
}
recipes.clear();
}
public static List<NamespacedKey> getRecipeKeys() {
return recipes;
}
public static NamespacedKey getNamespacedKeyForBlock(PSProtectBlock block) {
return new NamespacedKey(ProtectionStones.getInstance(), block.type.replaceAll("[+/=:]", ""));
}
public static ShapedRecipe parseRecipe(PSProtectBlock block) {
// create item
ItemStack item = block.createItem();
item.setAmount(block.recipeAmount);
// create recipe
// key must adhere to [a-z0-9/._-]
ShapedRecipe recipe = new ShapedRecipe(getNamespacedKeyForBlock(block), item);
// parse config
HashMap<String, Character> items = new HashMap<>();
List<String> recipeLine = new ArrayList<>();
char id = 'a';
for (int i = 0; i < block.customRecipe.size(); i++) {
recipeLine.add("");
for (String mat : block.customRecipe.get(i)) {
if (mat.equals("")) {
recipeLine.set(i, recipeLine.get(i) + " ");
} else {
if (items.get(mat) == null) {
items.put(mat, id++);
}
recipeLine.set(i, recipeLine.get(i) + items.get(mat));
}
}
}
// recipe
recipe.shape(recipeLine.toArray(new String[0]));
for (String mat : items.keySet()) {
if (Material.matchMaterial(mat) != null) { // general material type
recipe.setIngredient(items.get(mat), Material.matchMaterial(mat));
} else if (mat.startsWith("PROTECTION_STONES:")) { // ProtectionStones block
// format PROTECTION_STONES:alias
String alias = mat.substring(mat.indexOf(":") + 1);
PSProtectBlock use = ProtectionStones.getProtectBlockFromAlias(alias);
if (use != null && use.createItem() != null) {
recipe.setIngredient(items.get(mat), new RecipeChoice.ExactChoice(use.createItem()));
} else {
ProtectionStones.getPluginLogger().warning("Unable to resolve material " + mat + " for the crafting recipe for " + block.alias + ".");
}
} else {
ProtectionStones.getPluginLogger().warning("Unable to find material " + mat + " for the crafting recipe for " + block.alias + ".");
}
}
return recipe;
}
}
| 4,880 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
Objs.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/Objs.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.utils;
import java.util.Objects;
public class Objs {
public static<T> T replaceNull(T obj, T replacementIfNull) {
return obj != null ? obj : replacementIfNull;
}
}
| 841 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
LimitUtil.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/LimitUtil.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.List;
public class LimitUtil {
// warning: group regions should be split into merged regions first
public static String checkAddOwner(PSPlayer psp, List<PSProtectBlock> blocksAdded) {
HashMap<PSProtectBlock, Integer> regionLimits = psp.getRegionLimits();
int maxPS = psp.getGlobalRegionLimits();
ProtectionStones.getInstance().debug(String.format("Player's global limit is %d.", maxPS));
ProtectionStones.getInstance().debug(String.format("Player has limits on %d region types.", regionLimits.size()));
if (maxPS != -1 || !regionLimits.isEmpty()) { // only check if limit was found
// count player's protection blocks
int total = 0;
HashMap<PSProtectBlock, Integer> playerRegionCounts = getOwnedRegionTypeCounts(psp);
// add the blocks
for (PSProtectBlock b : blocksAdded) {
ProtectionStones.getInstance().debug(String.format("Adding region type %s.", b.alias));
if (playerRegionCounts.containsKey(b)) {
playerRegionCounts.put(b, playerRegionCounts.get(b)+1);
} else {
playerRegionCounts.put(b, 1);
}
}
// check each limit
for (PSProtectBlock type : playerRegionCounts.keySet()) {
if (regionLimits.containsKey(type)) {
ProtectionStones.getInstance().debug(String.format("Of type %s: player will have %d regions - Player's limit is %d regions.", type.alias, playerRegionCounts.get(type), regionLimits.get(type)));
if (playerRegionCounts.get(type) > regionLimits.get(type)) {
return PSL.ADDREMOVE_PLAYER_REACHED_LIMIT.msg();
}
}
total += playerRegionCounts.get(type);
}
// check if player has passed region limit
ProtectionStones.getInstance().debug(String.format("The player will have %d regions in total. Their limit is %d.", total, maxPS));
if (total > maxPS && maxPS != -1) {
return PSL.ADDREMOVE_PLAYER_REACHED_LIMIT.msg();
}
}
return "";
}
public static boolean check(Player p, PSProtectBlock b) {
if (!p.hasPermission("protectionstones.admin")) {
// check if player has limit on protection stones
String msg = LimitUtil.hasPlayerPassedRegionLimit(PSPlayer.fromPlayer(p), b);
if (!msg.isEmpty()) {
PSL.msg(p, msg);
return false;
}
}
return true;
}
public static boolean hasPassedOrEqualsRentLimit(Player p) {
int lim = MiscUtil.getPermissionNumber(p, "protectionstones.rent.limit.", -1);
if (lim != -1) {
int total = 0;
// find total number of rented regions
HashMap<World, RegionManager> m = WGUtils.getAllRegionManagers();
for (World w : m.keySet()) {
RegionManager rgm = m.get(w);
for (ProtectedRegion r : rgm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r) && r.getOwners().contains(WorldGuardPlugin.inst().wrapPlayer(p))) {
PSRegion psr = PSRegion.fromWGRegion(p.getWorld(), r);
if (psr != null && psr.getTenant() != null && psr.getTenant().equals(p.getUniqueId())) total++;
}
}
}
return total >= lim;
}
return false;
}
/**
* Returns the region counts of a player (for all worlds).
* @param psp player
* @return map of region types to the counts
*/
private static HashMap<PSProtectBlock, Integer> getOwnedRegionTypeCounts(PSPlayer psp) {
if (ProtectionStones.getInstance().isDebug()) { // psp.getName may incur a performance penalty
ProtectionStones.getInstance().debug(String.format("Debug limits for: %s", psp.getName()));
}
HashMap<PSProtectBlock, Integer> counts = new HashMap<>();
HashMap<World, RegionManager> m = WGUtils.getAllRegionManagers();
for (World w : m.keySet()) {
psp.getPSRegions(w, false).forEach(r -> {
if (r instanceof PSGroupRegion) {
ProtectionStones.getInstance().debug(String.format("Checking group region %s's (world %s) (type %s) regions:", r.getId(), w.getName(), r.getTypeOptions().alias));
for (PSMergedRegion psmr : ((PSGroupRegion) r).getMergedRegions()) {
if (psmr.getTypeOptions() == null) continue;
if (!counts.containsKey(psmr.getTypeOptions())) {
counts.put(psmr.getTypeOptions(), 1);
} else {
counts.put(psmr.getTypeOptions(), counts.get(psmr.getTypeOptions())+1);
}
ProtectionStones.getInstance().debug(String.format("Merged region %s (world %s) (type %s)", psmr.getId(), w.getName(), psmr.getTypeOptions().alias));
}
} else {
if (r.getTypeOptions() == null) return;
if (!counts.containsKey(r.getTypeOptions())) {
counts.put(r.getTypeOptions(), 1);
} else {
counts.put(r.getTypeOptions(), counts.get(r.getTypeOptions())+1);
}
ProtectionStones.getInstance().debug(String.format("Region %s (world %s) (type %s)", r.getId(), w.getName(), r.getTypeOptions().alias));
}
});
}
return counts;
}
private static String hasPlayerPassedRegionLimit(PSPlayer psp, PSProtectBlock b) {
HashMap<PSProtectBlock, Integer> regionLimits = psp.getRegionLimits();
int maxPS = psp.getGlobalRegionLimits();
if (maxPS != -1 || !regionLimits.isEmpty()) { // only check if limit was found
// count player's protection stones
int total = 0, bFound = 0;
HashMap<PSProtectBlock, Integer> playerRegionCounts = getOwnedRegionTypeCounts(psp);
for (PSProtectBlock type : playerRegionCounts.keySet()) {
ProtectionStones.getInstance().debug(String.format("Adding region type %s.", b.alias));
if (type.equals(b)) {
bFound = playerRegionCounts.get(type);
}
total += playerRegionCounts.get(type);
}
// check if player has passed region limit
ProtectionStones.getInstance().debug(String.format("The player will have %d regions in total. Their limit is %d.", total, maxPS));
if (total >= maxPS && maxPS != -1) {
return PSL.REACHED_REGION_LIMIT.msg().replace("%limit%", ""+maxPS);
}
// check if player has passed per block limit
ProtectionStones.getInstance().debug(String.format("Of type %s: player will have %d regions - Player's limit is %d regions.", b.alias, bFound, regionLimits.get(b) == null ? -1 : regionLimits.get(b)));
if (regionLimits.get(b) != null && bFound >= regionLimits.get(b)) {
return PSL.REACHED_PER_BLOCK_REGION_LIMIT.msg().replace("%limit%", ""+regionLimits.get(b));
}
}
return "";
}
}
| 8,478 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ConfigUpgrades.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/upgrade/ConfigUpgrades.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils.upgrade;
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.Bukkit;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class ConfigUpgrades {
// Upgrade the config one version up (ex. 3 -> 4)
public static boolean doConfigUpgrades() {
boolean leaveLoop = false;
switch (ProtectionStones.getInstance().getConfigOptions().configVersion) {
case 3:
ProtectionStones.config.set("config_version", 4);
ProtectionStones.config.set("base_command", "ps");
ProtectionStones.config.set("aliases", Arrays.asList("pstone", "protectionstones", "protectionstone"));
break;
case 4:
ProtectionStones.config.set("config_version", 5);
ProtectionStones.config.set("async_load_uuid_cache", false);
ProtectionStones.config.set("ps_view_cooldown", 20);
break;
case 5:
ProtectionStones.config.set("config_version", 6);
ProtectionStones.config.set("allow_duplicate_region_names", false);
break;
case 6:
ProtectionStones.config.set("config_version", 7);
ProtectionStones.config.set("drop_item_when_inventory_full", true);
break;
case 7:
ProtectionStones.config.set("config_version", 8);
ProtectionStones.config.set("regions_must_be_adjacent", false);
break;
case 8:
ProtectionStones.config.set("config_version", 9);
ProtectionStones.config.set("allow_merging_regions", true);
break;
case 9:
ProtectionStones.config.set("config_version", 10);
ProtectionStones.config.set("allow_merging_holes", true);
break;
case 10:
ProtectionStones.config.set("config_version", 11);
for (File file : ProtectionStones.blockDataFolder.listFiles()) {
CommentedFileConfig c = CommentedFileConfig.builder(file).sync().build();
c.load();
c.setComment("type", " Define your protection block below\n" +
" Use block type from here: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html\n" +
" --------------------------------------------------------------------------------------------------\n" +
" If you want to use player heads, you can use \"PLAYER_HEAD:player_name\" (ex. \"PLAYER_HEAD:Notch\")\n" +
" To use custom player heads, you need the base64 value of the head. On minecraft-heads.com, you will find this value in the Other section under \"Value:\".\n" +
" To use UUIDs for player heads, go to https://sessionserver.mojang.com/session/minecraft/profile/PUT-UUID-HERE and copy the value from the \"value\" field not including quotes.\n" +
" When you have the value, you can set the type to \"PLAYER_HEAD:value\"");
try {
c.set("region.home_x_offset", ((Integer) c.get("region.home_x_offset")).doubleValue());
c.set("region.home_y_offset", ((Integer) c.get("region.home_y_offset")).doubleValue());
c.set("region.home_z_offset", ((Integer) c.get("region.home_z_offset")).doubleValue());
} catch (Exception e) {}
c.save();
c.close();
}
break;
case 11:
ProtectionStones.config.set("config_version", 12);
ProtectionStones.config.set("economy.max_rent_price", -1.0);
ProtectionStones.config.set("economy.min_rent_price", 1.0);
ProtectionStones.config.setComment("economy.max_rent_price", " Set limits on the price for renting. Set to -1.0 to disable.");
ProtectionStones.config.set("economy.max_rent_period", -1);
ProtectionStones.config.set("economy.min_rent_period", 1);
ProtectionStones.config.setComment("economy.max_rent_period", " Set limits on the period between rent payments, in seconds (86400 seconds = 1 day). Set to -1 to disable.");
ProtectionStones.config.set("economy.tax_enabled", false);
ProtectionStones.config.set("economy.tax_message_on_join", true);
ProtectionStones.config.setComment("economy.tax_enabled", " Set taxes on regions.\n" +
" Taxes are configured in each individual block config.\n" +
" Whether or not to enable the tax command.");
for (File file : ProtectionStones.blockDataFolder.listFiles()) {
CommentedFileConfig c = CommentedFileConfig.builder(file).sync().build();
c.load();
try {
List<String> l = c.get("region.hidden_flags_from_info");
l.addAll(Arrays.asList("ps-rent-settings", "ps-tax-payments-due", "ps-tax-last-payment-added", "ps-tax-autopayer"));
c.set("region.hidden_flags_from_info", l);
} catch (Exception e) {}
c.save();
c.close();
}
break;
case 12:
ProtectionStones.config.set("config_version", 13);
ProtectionStones.config.set("default_protection_block_placement_off", false);
ProtectionStones.config.setComment("default_protection_block_placement_off", " Whether when players join, by default they have protection block placement toggled off (equivalent to running /ps toggle)");
ProtectionStones.config.set("default_allow_addowner_for_offline_players_without_lp", false);
ProtectionStones.config.setComment("default_allow_addowner_for_offline_players_without_lp", " If you do not have LuckPerms, ProtectionStones is unable to determine the limits of offline players (since it depends\n" +
" on permissions), and so it requires players to be online. Set this to true if your server does not need limits (and so\n" +
" the check is unnecessary).");
break;
case 13:
ProtectionStones.config.set("config_version", 14);
ProtectionStones.config.set("admin.cleanup_delete_regions_with_members_but_no_owners", true);
ProtectionStones.config.setComment("admin.cleanup_delete_regions_with_members_but_no_owners", " Whether /ps admin cleanup remove should delete regions that have members, but don't have owners (after inactive\n" +
" owners are removed).\n" +
" Regions that have no owners or members will be deleted regardless.");
break;
case 14:
ProtectionStones.config.set("config_version", 15);
// fix incorrect value set
if (ProtectionStones.config.get("allow_addowner_for_offline_players_without_lp") == null) {
Object value = ProtectionStones.config.get("default_allow_addowner_for_offline_players_without_lp");
ProtectionStones.config.removeComment("default_allow_addowner_for_offline_players_without_lp");
ProtectionStones.config.remove("default_allow_addowner_for_offline_players_without_lp");
ProtectionStones.config.set("allow_addowner_for_offline_players_without_lp", value == null ? false : (boolean) value);
ProtectionStones.config.setComment("allow_addowner_for_offline_players_without_lp", " If you do not have LuckPerms, ProtectionStones is unable to determine the limits of offline players (since it depends\n" +
" on permissions), and so it requires players to be online. Set this to true if your server does not need limits (and so\n" +
" the check is unnecessary).");
}
break;
case 15:
ProtectionStones.config.set("config_version", 16);
ProtectionStones.config.set("allow_home_teleport_for_members", true);
ProtectionStones.config.setComment("allow_home_teleport_for_members", " Whether or not members of a region can /ps home to the region.");
break;
case ProtectionStones.CONFIG_VERSION:
leaveLoop = true;
break;
default:
Bukkit.getLogger().info("Invalid config version! The plugin may not load correctly!");
leaveLoop = true;
break;
}
return leaveLoop;
}
}
| 9,735 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
LegacyUpgrade.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/upgrade/LegacyUpgrade.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.utils.upgrade;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
public class LegacyUpgrade {
// upgrade to 1.17, upgrade regions with 0->256 to SHORT_MIN->SHORT_MAX
public static void upgradeRegionsWithNegativeYValues() {
ProtectionStones.getInstance().getLogger().info("Upgrading region y-values for 1.17...");
for (RegionManager rgm : WGUtils.getAllRegionManagers().values()) {
List<ProtectedRegion> newRegions = new ArrayList<>();
// loop through each region
for (var region : rgm.getRegions().values()) {
int minY = region.getMinimumPoint().getBlockY(), maxY = region.getMaximumPoint().getBlockY();
if (ProtectionStones.isPSRegion(region) && minY == 0 && maxY == 256) {
// clone region, and recreate with new min/max points
ProtectedRegion toAdd = null;
if (region instanceof ProtectedPolygonalRegion) { // convert merged region
toAdd = new ProtectedPolygonalRegion(region.getId(), region.getPoints(), WGUtils.MIN_BUILD_HEIGHT, WGUtils.MAX_BUILD_HEIGHT);
} else if (region instanceof ProtectedCuboidRegion) { // convert standard region
BlockVector3 minVec = BlockVector3.at(region.getMinimumPoint().getX(), WGUtils.MIN_BUILD_HEIGHT, region.getMinimumPoint().getZ()),
maxVec = BlockVector3.at(region.getMaximumPoint().getX(), WGUtils.MAX_BUILD_HEIGHT, region.getMaximumPoint().getZ());
toAdd = new ProtectedCuboidRegion(region.getId(), minVec, maxVec);
}
if (toAdd != null) {
ProtectionStones.getInstance().getLogger().info("Updated region " + region.getId());
toAdd.copyFrom(region); // copy region settings
newRegions.add(toAdd);
}
} else {
newRegions.add(region);
}
}
rgm.setRegions(newRegions);
try {
rgm.save();
} catch (StorageException e) {
e.printStackTrace();
}
}
// update config to mark that uuid upgrade has been done
ProtectionStones.config.set("region_negative_min_max_updated", true);
ProtectionStones.config.save();
ProtectionStones.getInstance().getLogger().info("Finished!");
}
// for one day when we switch to proper base64 generation (no hashcode, use nameuuidfrombytes)
// problem is, currently I don't know how to convert all items to use this uuid
public static void fixBase64HeadRegions() {
HashMap<String, String> oldToNew = new HashMap<>();
for (PSProtectBlock b : ProtectionStones.getInstance().getConfiguredBlocks()) {
if (b.type.startsWith("PLAYER_HEAD:") && b.type.split(":").length > 1) {
String base64 = b.type.split(":")[1];
oldToNew.put(new UUID(base64.hashCode(), base64.hashCode()).toString(), UUID.nameUUIDFromBytes(base64.getBytes()).toString());
}
}
for (World world : Bukkit.getWorlds()) {
RegionManager rm = WGUtils.getRegionManagerWithWorld(world);
for (ProtectedRegion r : rm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r)) {
PSRegion psr = PSRegion.fromWGRegion(world, r);
if (psr instanceof PSGroupRegion) {
PSGroupRegion psgr = (PSGroupRegion) psr;
for (PSMergedRegion psmr : psgr.getMergedRegions()) {
String type = psmr.getType();
if (oldToNew.containsKey(type)) {
Set<String> flag = psmr.getGroupRegion().getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES);
String original = null;
for (String s : flag) {
String[] spl = s.split(" ");
String id = spl[0];
if (id.equals(psmr.getId())) {
original = s;
break;
}
}
if (original != null) {
flag.remove(original);
flag.add(psmr.getId() + " " + oldToNew.get(type));
}
}
}
}
if (oldToNew.containsKey(psr.getType())) {
psr.getWGRegion().setFlag(FlagHandler.PS_BLOCK_MATERIAL, oldToNew.get(psr.getType()));
}
}
}
try {
rm.save();
} catch (StorageException e) {
e.printStackTrace();
}
}
}
// check that all of the PS custom flags are in ps regions and upgrade if not
// originally used for the v1 -> v2 transition
public static void upgradeRegions() {
YamlConfiguration hideFile = null;
if (new File(ProtectionStones.getInstance().getDataFolder() + "/hiddenpstones.yml").exists()) {
hideFile = YamlConfiguration.loadConfiguration(new File(ProtectionStones.getInstance().getDataFolder() + "/hiddenpstones.yml"));
}
for (World world : Bukkit.getWorlds()) {
RegionManager rm = WGUtils.getRegionManagerWithWorld(world);
for (String regionName : rm.getRegions().keySet()) {
if (regionName.startsWith("ps") && !ProtectionStones.isPSRegion(rm.getRegion(regionName))) {
try {
PSLocation psl = WGUtils.parsePSRegionToLocation(regionName);
ProtectedRegion r = rm.getRegion(regionName);
// get material of ps
String entry = psl.x + "x" + psl.y + "y" + psl.z + "z", material;
if (hideFile != null && hideFile.contains(entry)) {
material = hideFile.getString(entry);
} else {
material = world.getBlockAt(psl.x, psl.y, psl.z).getType().toString();
}
if (r.getFlag(FlagHandler.PS_BLOCK_MATERIAL) == null) {
r.setFlag(FlagHandler.PS_BLOCK_MATERIAL, material);
}
if (r.getFlag(FlagHandler.PS_HOME) == null) {
if (ProtectionStones.isProtectBlockType(material)) {
PSProtectBlock cpb = ProtectionStones.getBlockOptions(material);
r.setFlag(FlagHandler.PS_HOME, (psl.x + cpb.homeXOffset) + " " + (psl.y + cpb.homeYOffset) + " " + (psl.z + cpb.homeZOffset));
} else {
r.setFlag(FlagHandler.PS_HOME, psl.x + " " + psl.y + " " + psl.z);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try {
rm.save();
} catch (Exception e) {
Bukkit.getLogger().severe("[ProtectionStones] WorldGuard Error [" + e + "] during Region File Save");
}
}
}
// convert regions to use UUIDs instead of player names
public static void convertToUUID() {
Bukkit.getLogger().info("Updating PS regions to UUIDs...");
for (World world : Bukkit.getWorlds()) {
RegionManager rm = WGUtils.getRegionManagerWithWorld(world);
// iterate over regions in world
for (String regionName : rm.getRegions().keySet()) {
if (regionName.startsWith("ps")) {
ProtectedRegion region = rm.getRegion(regionName);
// convert owners with player names to UUIDs
List<String> owners, members;
owners = new ArrayList<>(region.getOwners().getPlayers());
members = new ArrayList<>(region.getMembers().getPlayers());
// convert
for (String owner : owners) {
UUID uuid = Bukkit.getOfflinePlayer(owner).getUniqueId();
region.getOwners().removePlayer(owner);
region.getOwners().addPlayer(uuid);
}
for (String member : members) {
UUID uuid = Bukkit.getOfflinePlayer(member).getUniqueId();
region.getMembers().removePlayer(member);
region.getMembers().addPlayer(uuid);
}
}
}
try {
rm.save();
} catch (Exception e) {
Bukkit.getLogger().severe("[ProtectionStones] WorldGuard Error [" + e + "] during Region File Save");
}
}
// update config to mark that uuid upgrade has been done
ProtectionStones.config.set("uuidupdated", true);
ProtectionStones.config.save();
Bukkit.getLogger().info("Done!");
}
// upgrade from config < v2.0.0
public static void upgradeFromV1V2() {
Bukkit.getLogger().info(ChatColor.AQUA + "Upgrading configs from v1.x to v2.0+...");
try {
ProtectionStones.blockDataFolder.mkdir();
Files.copy(PSConfig.class.getResourceAsStream("/config.toml"), Paths.get(ProtectionStones.configLocation.toURI()), StandardCopyOption.REPLACE_EXISTING);
FileConfig fc = FileConfig.builder(ProtectionStones.configLocation).build();
fc.load();
File oldConfig = new File(ProtectionStones.getInstance().getDataFolder() + "/config.yml");
YamlConfiguration yml = YamlConfiguration.loadConfiguration(oldConfig);
fc.set("uuidupdated", (yml.get("UUIDUpdated") != null) && yml.getBoolean("UUIDUpdated"));
fc.set("placing_cooldown", (yml.getBoolean("cooldown.enable")) ? yml.getInt("cooldown.cooldown") : -1);
// options from global scope
List<String> worldsDenied = yml.getStringList("Worlds Denied");
List<String> flags = yml.getStringList("Flags");
List<String> allowedFlags = new ArrayList<>(Arrays.asList(yml.getString("Allowed Flags").split(",")));
// upgrade blocks
for (String type : yml.getConfigurationSection("Region").getKeys(false)) {
File file = new File(ProtectionStones.blockDataFolder.getAbsolutePath() + "/" + type + ".toml");
Files.copy(PSConfig.class.getResourceAsStream("/block1.toml"), Paths.get(file.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
FileConfig b = FileConfig.builder(file).build();
b.load();
b.set("type", type);
b.set("alias", type);
b.set("description", yml.getInt("Region." + type + ".X Radius") + " radius protected area.");
b.set("restrict_obtaining", false);
b.set("world_list_type", "blacklist");
b.set("worlds", worldsDenied);
b.set("region.x_radius", yml.getInt("Region." + type + ".X Radius"));
b.set("region.y_radius", yml.getInt("Region." + type + ".Y Radius"));
b.set("region.z_radius", yml.getInt("Region." + type + ".Z Radius"));
b.set("region.flags", flags);
b.set("region.allowed_flags", allowedFlags);
b.set("region.priority", yml.getInt("Region." + type + ".Priority"));
b.set("block_data.display_name", "");
b.set("block_data.lore", Arrays.asList());
b.set("behaviour.auto_hide", yml.getBoolean("Region." + type + ".Auto Hide"));
b.set("behaviour.no_drop", yml.getBoolean("Region." + type + ".No Drop"));
b.set("behaviour.prevent_piston_push", yml.getBoolean("Region." + type + ".Block Piston"));
// ignore silk touch option
b.set("player.prevent_teleport_in", yml.getBoolean("Teleport To PVP.Block Teleport"));
b.save();
b.close();
}
fc.save();
fc.close();
oldConfig.renameTo(new File(ProtectionStones.getInstance().getDataFolder() + "/config.yml.old"));
} catch (IOException e) {
e.printStackTrace();
}
Bukkit.getLogger().info(ChatColor.GREEN + "Done!");
Bukkit.getLogger().info(ChatColor.GREEN + "Please be sure to double check your configs with the new options!");
Bukkit.getLogger().info(ChatColor.AQUA + "Updating PS Regions to new format...");
LegacyUpgrade.upgradeRegions();
Bukkit.getLogger().info(ChatColor.GREEN + "Done!");
}
}
| 14,745 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
GUIScreen.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/gui/GUIScreen.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.gui;
public class GUIScreen {
}
| 722 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
GreetingFlagHandler.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/flags/GreetingFlagHandler.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.flags;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.FlagValueChangeHandler;
import com.sk89q.worldguard.session.handler.Handler;
import dev.espi.protectionstones.FlagHandler;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
// greeting-action flag
public class GreetingFlagHandler extends FlagValueChangeHandler<String> {
public static final Factory FACTORY = new Factory();
public static class Factory extends Handler.Factory<GreetingFlagHandler> {
@Override
public GreetingFlagHandler create(Session session) {
return new GreetingFlagHandler(session);
}
}
public GreetingFlagHandler(Session session) {
super(session, FlagHandler.GREET_ACTION);
}
@Override
protected void onInitialValue(LocalPlayer localPlayer, ApplicableRegionSet applicableRegionSet, String s) {
}
@Override
protected boolean onSetValue(LocalPlayer localPlayer, Location location, Location location1, ApplicableRegionSet applicableRegionSet, String currentValue, String lastValue, MoveType moveType) {
if (currentValue != null && !currentValue.equals(lastValue) && Bukkit.getPlayer(localPlayer.getUniqueId()) != null) {
Bukkit.getPlayer(localPlayer.getUniqueId()).spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.translateAlternateColorCodes('&', currentValue)));
}
return true;
}
@Override
protected boolean onAbsentValue(LocalPlayer localPlayer, Location location, Location location1, ApplicableRegionSet applicableRegionSet, String lastValue, MoveType moveType) {
return true;
}
}
| 2,653 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
FarewellFlagHandler.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/flags/FarewellFlagHandler.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.flags;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.FlagValueChangeHandler;
import com.sk89q.worldguard.session.handler.Handler;
import dev.espi.protectionstones.FlagHandler;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
// farewell-action flag
public class FarewellFlagHandler extends FlagValueChangeHandler<String> {
public static final FarewellFlagHandler.Factory FACTORY = new FarewellFlagHandler.Factory();
public static class Factory extends Handler.Factory<FarewellFlagHandler> {
@Override
public FarewellFlagHandler create(Session session) {
return new FarewellFlagHandler(session);
}
}
protected FarewellFlagHandler(Session session) {
super(session, FlagHandler.FAREWELL_ACTION);
}
@Override
protected void onInitialValue(LocalPlayer localPlayer, ApplicableRegionSet applicableRegionSet, String s) {
}
@Override
protected boolean onSetValue(LocalPlayer localPlayer, Location from, Location to, ApplicableRegionSet toSet, String currentValue, String lastValue, MoveType moveType) {
Player p = Bukkit.getPlayer(localPlayer.getUniqueId());
// the greeting action flag for the other region should show instead if it is set
for (ProtectedRegion r : toSet.getRegions()) {
if (r.getFlag(FlagHandler.GREET_ACTION) != null) {
return true;
}
}
if (p != null && lastValue != null && !lastValue.equals(currentValue)) {
p.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.translateAlternateColorCodes('&', lastValue)));
}
return true;
}
@Override
protected boolean onAbsentValue(LocalPlayer localPlayer, Location location, Location location1, ApplicableRegionSet applicableRegionSet, String lastValue, MoveType moveType) {
Player p = Bukkit.getPlayer(localPlayer.getUniqueId());
if (p != null && lastValue != null) {
p.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.translateAlternateColorCodes('&', lastValue)));
}
return true;
}
}
| 3,397 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgHideUnhide.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgHideUnhide.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class ArgHideUnhide implements PSCommandArg {
@Override
public List<String> getNames() {
return Arrays.asList("hide", "unhide");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.hide", "protectionstones.unhide");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] arg, HashMap<String, String> flags) {
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
// preliminary checks
if (arg[0].equals("unhide") && !p.hasPermission("protectionstones.unhide"))
return PSL.msg(p, PSL.NO_PERMISSION_UNHIDE.msg());
if (arg[0].equals("hide") && !p.hasPermission("protectionstones.hide"))
return PSL.msg(p, PSL.NO_PERMISSION_HIDE.msg());
if (r == null)
return PSL.msg(p, PSL.NOT_IN_REGION.msg());
if (WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), false))
return PSL.msg(p, PSL.NO_ACCESS.msg());
if (r.isHidden()) {
if (arg[0].equals("hide")) {
return PSL.msg(p, PSL.ALREADY_HIDDEN.msg());
}
r.unhide();
} else {
if (arg[0].equals("unhide")) {
return PSL.msg(p, PSL.ALREADY_NOT_HIDDEN.msg());
}
r.hide();
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 2,757 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PSCommandArg.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/PSCommandArg.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import org.bukkit.command.CommandSender;
import java.util.HashMap;
import java.util.List;
public interface PSCommandArg {
List<String> getNames();
boolean allowNonPlayersToExecute();
List<String> getPermissionsToExecute();
HashMap<String, Boolean> getRegisteredFlags(); // <flag, has value after>
boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags);
List<String> tabComplete(CommandSender sender, String alias, String[] args);
}
| 1,190 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgToggle.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgToggle.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgToggle implements PSCommandArg {
// /ps on
public static class ArgToggleOn implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("on");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.toggle");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
if (p.hasPermission("protectionstones.toggle")) {
ProtectionStones.toggleList.remove(p.getUniqueId());
p.sendMessage(PSL.TOGGLE_ON.msg());
} else {
p.sendMessage(PSL.NO_PERMISSION_TOGGLE.msg());
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
// /ps off
public static class ArgToggleOff implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("off");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.toggle");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
if (p.hasPermission("protectionstones.toggle")) {
ProtectionStones.toggleList.add(p.getUniqueId());
p.sendMessage(PSL.TOGGLE_OFF.msg());
} else {
p.sendMessage(PSL.NO_PERMISSION_TOGGLE.msg());
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
@Override
public List<String> getNames() {
return Collections.singletonList("toggle");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.toggle");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
if (p.hasPermission("protectionstones.toggle")) {
if (!ProtectionStones.toggleList.contains(p.getUniqueId())) {
ProtectionStones.toggleList.add(p.getUniqueId());
p.sendMessage(PSL.TOGGLE_OFF.msg());
} else {
ProtectionStones.toggleList.remove(p.getUniqueId());
p.sendMessage(PSL.TOGGLE_ON.msg());
}
} else {
p.sendMessage(PSL.NO_PERMISSION_TOGGLE.msg());
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 4,666 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgGet.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgGet.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSPlayer;
import dev.espi.protectionstones.PSProtectBlock;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.ProtectionStones;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.text.DecimalFormat;
import java.util.*;
public class ArgGet implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("get");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.get");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
private boolean openGetGUI(Player p) {
PSL.msg(p, PSL.GET_HEADER.msg());
for (PSProtectBlock b : ProtectionStones.getInstance().getConfiguredBlocks()) {
if ((!b.permission.equals("") && !p.hasPermission(b.permission)) || (b.preventPsGet && !p.hasPermission("protectionstones.admin"))) {
continue; // no permission
}
String price = new DecimalFormat("#.##").format(b.price);
TextComponent tc = new TextComponent(PSL.GET_GUI_BLOCK.msg()
.replace("%alias%", b.alias)
.replace("%price%", price)
.replace("%description%", b.description)
.replace("%xradius%", ""+b.xRadius)
.replace("%yradius%", ""+b.yRadius)
.replace("%zradius%", ""+b.zRadius));
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.GET_GUI_HOVER.msg()
.replace("%alias%", b.alias)
.replace("%price%", price)
.replace("%description%", b.description)
.replace("%xradius%", ""+b.xRadius)
.replace("%yradius%", ""+b.yRadius)
.replace("%zradius%", ""+b.zRadius)).create()));
tc.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " get " + b.alias));
p.spigot().sendMessage(tc);
}
return true;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
PSPlayer psp = PSPlayer.fromPlayer(p);
if (!p.hasPermission("protectionstones.get"))
return PSL.msg(p, PSL.NO_PERMISSION_GET.msg());
// /ps get (for GUI)
if (args.length == 1) return openGetGUI(p);
if (args.length != 2)
return PSL.msg(p, PSL.GET_HELP.msg());
// check if argument is valid block
PSProtectBlock cp = ProtectionStones.getProtectBlockFromAlias(args[1]);
if (cp == null)
return PSL.msg(p, PSL.INVALID_BLOCK.msg());
// check for block permission (custom)
if (!cp.permission.equals("") && !p.hasPermission(cp.permission))
return PSL.msg(p, PSL.GET_NO_PERMISSION_BLOCK.msg());
// check if /ps get is disabled on this
if (cp.preventPsGet && !p.hasPermission("protectionstones.admin"))
return PSL.msg(p, PSL.GET_NO_PERMISSION_BLOCK.msg());
// check if player has enough money
if (ProtectionStones.getInstance().isVaultSupportEnabled() && cp.price != 0 && !psp.hasAmount(cp.price))
return PSL.msg(p, PSL.NOT_ENOUGH_MONEY.msg().replace("%price%", String.format("%.2f", cp.price)));
// debug message
if (!ProtectionStones.getInstance().isVaultSupportEnabled() && cp.price != 0) {
Bukkit.getLogger().info("Vault is not enabled but there is a price set on the protection stone! It will not work!");
}
// take money
if (ProtectionStones.getInstance().isVaultSupportEnabled() && cp.price != 0) {
EconomyResponse er = psp.withdrawBalance(cp.price);
if (!er.transactionSuccess()) {
return PSL.msg(p, er.errorMessage);
}
}
// check if item was able to be added (inventory not full)
if (!p.getInventory().addItem(cp.createItem()).isEmpty()) {
if (ProtectionStones.getInstance().getConfigOptions().dropItemWhenInventoryFull) { // drop on floor
PSL.msg(p, PSL.NO_ROOM_DROPPING_ON_FLOOR.msg());
p.getWorld().dropItem(p.getLocation(), cp.createItem());
} else { // cancel event
PSL.msg(p, PSL.NO_ROOM_IN_INVENTORY.msg());
if (ProtectionStones.getInstance().isVaultSupportEnabled()) {
EconomyResponse er = psp.depositBalance(cp.price);
if (!er.transactionSuccess()) {
return PSL.msg(p, er.errorMessage);
}
}
}
return true;
}
return PSL.msg(p, PSL.GET_GOTTEN.msg());
}
// tab completion
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
List<String> l = new ArrayList<>();
for (PSProtectBlock b : ProtectionStones.getInstance().getConfiguredBlocks()) {
if ((!b.permission.equals("") && !sender.hasPermission(b.permission)) || (b.preventPsGet && !sender.hasPermission("protectionstones.admin"))) continue; // no permission
l.add(b.alias);
}
return args.length == 2 ? StringUtil.copyPartialMatches(args[1], l, new ArrayList<>()) : null;
}
}
| 6,689 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgName.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgName.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgName implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("name");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.name");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.name")) {
PSL.msg(s, PSL.NO_PERMISSION_NAME.msg());
return true;
}
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null) {
PSL.msg(s, PSL.NOT_IN_REGION.msg());
return true;
}
if (WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), false)) {
PSL.msg(s, PSL.NO_ACCESS.msg());
return true;
}
if (args.length < 2) {
PSL.msg(s, PSL.NAME_HELP.msg());
return true;
}
if (args[1].equals("none")) {
r.setName(null);
PSL.msg(p, PSL.NAME_REMOVED.msg().replace("%id%", r.getId()));
} else {
if (!ProtectionStones.getInstance().getConfigOptions().allowDuplicateRegionNames && ProtectionStones.isPSNameAlreadyUsed(args[1])) {
PSL.msg(p, PSL.NAME_TAKEN.msg().replace("%name%", args[1]));
return true;
}
r.setName(args[1]);
PSL.msg(p, PSL.NAME_SET_NAME.msg().replace("%id%", r.getId()).replace("%name%", r.getName()));
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 3,082 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgSetparent.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgSetparent.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.ChatUtil;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgSetparent implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("setparent");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.setparent");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.setparent")) {
PSL.msg(s, PSL.NO_PERMISSION_SETPARENT.msg());
return true;
}
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null) {
PSL.msg(s, PSL.NOT_IN_REGION.msg());
return true;
}
if (WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), false)) {
PSL.msg(s, PSL.NO_ACCESS.msg());
return true;
}
if (args.length != 2) {
PSL.msg(s, PSL.SETPARENT_HELP.msg());
return true;
}
if (args[1].equals("none")) { // remove parent
try {
r.setParent(null);
PSL.msg(s, PSL.SETPARENT_SUCCESS_REMOVE.msg().replace("%id%", r.getName() == null ? r.getId() : r.getName()));
} catch (ProtectedRegion.CircularInheritanceException e) {
e.printStackTrace(); // won't happen ever
}
} else {
List<PSRegion> parent = ProtectionStones.getPSRegions(p.getWorld(), args[1]);
if (parent.isEmpty()) {
PSL.msg(s, PSL.REGION_DOES_NOT_EXIST.msg());
return true;
}
if (!p.hasPermission("protectionstones.setparent.others") && !parent.get(0).isOwner(p.getUniqueId())) {
PSL.msg(s, PSL.NO_PERMISSION_SETPARENT_OTHERS.msg());
return true;
}
if (parent.size() > 1) {
ChatUtil.displayDuplicateRegionAliases(p, parent);
return true;
}
try {
r.setParent(parent.get(0));
} catch (ProtectedRegion.CircularInheritanceException e) {
PSL.msg(s, PSL.SETPARENT_CIRCULAR_INHERITANCE.msg());
return true;
}
PSL.msg(s, PSL.SETPARENT_SUCCESS.msg().replace("%id%", r.getName() == null ? r.getId() : r.getName())
.replace("%parent%", parent.get(0).getName() == null ? parent.get(0).getId() : parent.get(0).getName()));
}
return false;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 4,152 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminSetTaxAutopayers.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminSetTaxAutopayers.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
class ArgAdminSetTaxAutopayers {
static boolean argumentAdminSetTaxAutopayers(CommandSender s, String[] args) {
if (!ProtectionStones.getInstance().getConfigOptions().taxEnabled) {
return PSL.msg(s, ChatColor.RED + "Taxes are disabled! Enable it in the config.");
}
PSL.msg(s, ChatColor.GRAY + "Scanning through regions, and setting tax autopayers for regions that don't have one...");
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
WGUtils.getAllRegionManagers().forEach((w, rgm) -> {
for (ProtectedRegion r : rgm.getRegions().values()) {
PSRegion psr = PSRegion.fromWGRegion(w, r);
if (psr != null && psr.getTypeOptions() != null && psr.getTypeOptions().taxPeriod != -1 && psr.getTaxAutopayer() == null) {
if (psr.getOwners().size() >= 1) {
PSL.msg(s, ChatColor.GRAY + "Configured tax autopayer to be " + psr.getOwners().get(0).toString() + " for region " + psr.getId());
psr.setTaxAutopayer(psr.getOwners().get(0));
}
}
}
});
PSL.msg(s, ChatColor.GREEN + "Complete!");
});
return true;
}
}
| 2,346 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgHome.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgHome.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.ChatUtil;
import dev.espi.protectionstones.utils.MiscUtil;
import dev.espi.protectionstones.utils.TextGUI;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.*;
import java.util.stream.Collectors;
public class ArgHome implements PSCommandArg {
private static HashMap<UUID, List<String>> tabCache = new HashMap<>();
@Override
public List<String> getNames() {
return Collections.singletonList("home");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.home");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
HashMap<String, Boolean> h = new HashMap<>();
h.put("-p", true);
return h;
}
// tab completion
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (!(sender instanceof Player p)) return null;
PSPlayer psp = PSPlayer.fromPlayer(p);
if (args.length == 2) {
// add to cache if not already
if (tabCache.get(p.getUniqueId()) == null) {
List<PSRegion> regions = psp.getHomes(p.getWorld());
List<String> regionNames = new ArrayList<>();
for (PSRegion r : regions) {
if (r.getName() != null) {
regionNames.add(r.getName());
} else {
regionNames.add(r.getId());
}
}
// cache home regions
tabCache.put(p.getUniqueId(), regionNames);
Bukkit.getScheduler().runTaskLater(ProtectionStones.getInstance(), () -> {
tabCache.remove(p.getUniqueId());
}, 200); // remove cache after 10 seconds
}
return StringUtil.copyPartialMatches(args[1], tabCache.get(p.getUniqueId()), new ArrayList<>());
}
return null;
}
private static final int GUI_SIZE = 17;
private void openHomeGUI(PSPlayer psp, List<PSRegion> homes, int page) {
List<TextComponent> entries = new ArrayList<>();
for (PSRegion r : homes) {
String msg;
if (r.getName() == null) {
msg = ChatColor.GRAY + "> " + ChatColor.AQUA + r.getId();
} else {
msg = ChatColor.GRAY + "> " + ChatColor.AQUA + r.getName() + " (" + r.getId() + ")";
}
TextComponent tc = new TextComponent(msg);
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.HOME_CLICK_TO_TP.msg()).create()));
if (r.getName() == null) {
tc.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " home " + r.getId()));
} else {
tc.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " home " + r.getName()));
}
entries.add(tc);
}
TextGUI.displayGUI(psp.getPlayer(), PSL.HOME_HEADER.msg(), "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " home -p %page%", page, GUI_SIZE, entries, true);
if (page * GUI_SIZE + GUI_SIZE < entries.size())
PSL.msg(psp, PSL.HOME_NEXT.msg().replace("%page%", page + 2 + ""));
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
// prelim checks
if (!p.hasPermission("protectionstones.home"))
return PSL.msg(p, PSL.NO_PERMISSION_HOME.msg());
if (args.length != 2 && args.length != 1)
return PSL.msg(p, PSL.HOME_HELP.msg());
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
PSPlayer psp = PSPlayer.fromPlayer(p);
if (args.length == 1) {
// just "/ps home"
List<PSRegion> regions = psp.getHomes(p.getWorld());
if (regions.size() == 1) { // teleport to home if there is only one home
ArgTp.teleportPlayer(p, regions.get(0));
} else { // otherwise, open the GUI
openHomeGUI(psp, regions, (flags.get("-p") == null || !MiscUtil.isValidInteger(flags.get("-p")) ? 0 : Integer.parseInt(flags.get("-p")) - 1));
}
} else {// /ps home [id]
// get regions from the query
String query = args[1];
List<PSRegion> regions = psp.getHomes(p.getWorld())
.stream()
.filter(region -> region.getId().equals(query)
|| (region.getName() != null && region.getName().equals(query)))
.collect(Collectors.toList());
if (regions.isEmpty()) {
PSL.msg(s, PSL.REGION_DOES_NOT_EXIST.msg());
return;
}
// if there is more than one name in the query
if (regions.size() > 1) {
ChatUtil.displayDuplicateRegionAliases(p, regions);
return;
}
ArgTp.teleportPlayer(p, regions.get(0));
}
});
return true;
}
}
| 6,657 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdmin.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdmin.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.utils.upgrade.LegacyUpgrade;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.*;
/*
* To add new sub commands, add them here, and in ArgAdminHelp manually
*/
public class ArgAdmin implements PSCommandArg {
// has to be a method, because the base command config option is not available until the plugin is loaded
public static String getCleanupHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" admin cleanup [remove|preview] [-t typealias (optional)] [days] [world (optional)]";
}
public static String getFlagHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" admin flag [world] [flagname] [value|null|default]";
}
public static String getChangeBlockHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" admin changeblock [world] [oldtypealias] [newtypealias]";
}
public static String getChangeRegionTypeHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" admin changeregiontype [world] [oldtype] [newtype]";
}
public static String getForceMergeHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" admin forcemerge [world]";
}
@Override
public List<String> getNames() {
return Collections.singletonList("admin");
}
@Override
public boolean allowNonPlayersToExecute() {
return true;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.admin");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
// /ps admin [arg]
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.admin")) {
return PSL.msg(s, PSL.NO_PERMISSION_ADMIN.msg());
}
if (args.length < 2) {
ArgAdminHelp.argumentAdminHelp(s, args);
return true;
}
switch (args[1].toLowerCase()) {
case "help":
return ArgAdminHelp.argumentAdminHelp(s, args);
case "version":
s.sendMessage(ChatColor.AQUA + "ProtectionStones: " + ChatColor.GRAY + ProtectionStones.getInstance().getDescription().getVersion());
s.sendMessage(ChatColor.AQUA + "Developers: " + ChatColor.GRAY + ProtectionStones.getInstance().getDescription().getAuthors());
s.sendMessage(ChatColor.AQUA + "Bukkit: " + ChatColor.GRAY + Bukkit.getVersion());
s.sendMessage(ChatColor.AQUA + "WG: " + ChatColor.GRAY + WorldGuardPlugin.inst().getDescription().getVersion());
break;
case "hide":
return ArgAdminHide.argumentAdminHide(s, args);
case "unhide":
return ArgAdminHide.argumentAdminHide(s, args);
case "cleanup":
return ArgAdminCleanup.argumentAdminCleanup(s, args);
case "stats":
return ArgAdminStats.argumentAdminStats(s, args);
case "lastlogon":
return ArgAdminLastlogon.argumentAdminLastLogon(s, args);
case "lastlogons":
return ArgAdminLastlogon.argumentAdminLastLogons(s, args);
case "flag":
return ArgAdminFlag.argumentAdminFlag(s, args);
case "recreate":
return ArgAdminRecreate.argumentAdminRecreate(s, args);
case "changeblock":
return ArgAdminChangeblock.argumentAdminChangeblock(s, args);
case "changeregiontype":
return ArgAdminChangeType.argumentAdminChangeType(s, args);
case "forcemerge":
return ArgAdminForceMerge.argumentAdminForceMerge(s, args);
case "settaxautopayers":
return ArgAdminSetTaxAutopayers.argumentAdminSetTaxAutopayers(s, args);
case "fixregions":
s.sendMessage(ChatColor.YELLOW + "Fixing...");
LegacyUpgrade.upgradeRegions();
s.sendMessage(ChatColor.YELLOW + "Done!");
break;
case "debug":
if (ProtectionStones.getInstance().isDebug()) {
s.sendMessage(ChatColor.YELLOW + "Debug mode is now off.");
ProtectionStones.getInstance().setDebug(false);
} else {
s.sendMessage(ChatColor.YELLOW + "Debug mode is now on.");
ProtectionStones.getInstance().setDebug(true);
}
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (args.length == 2) {
List<String> arg = Arrays.asList("version", "hide", "unhide", "cleanup", "stats", "lastlogon", "lastlogons", "flag", "recreate", "fixregions", "debug", "forcemerge", "changeblock", "changeregiontype", "settaxautopayers");
return StringUtil.copyPartialMatches(args[1], arg, new ArrayList<>());
} else if (args.length >= 3 && args[1].equals("forcemerge")) {
return ArgAdminForceMerge.tabComplete(sender, alias, args);
}
return null;
}
}
| 6,647 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgList.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgList.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSPlayer;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.UUIDCache;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.*;
import java.util.stream.Collectors;
public class ArgList implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("list");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.list");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.list"))
return PSL.msg(s, PSL.NO_PERMISSION_LIST.msg());
if (args.length == 2 && !s.hasPermission("protectionstones.list.others"))
return PSL.msg(s, PSL.NO_PERMISSION_LIST_OTHERS.msg());
if (args.length == 2 && !UUIDCache.containsName(args[1]))
return PSL.msg(s, PSL.PLAYER_NOT_FOUND.msg());
PSPlayer psp = PSPlayer.fromPlayer((Player) s);
// run query async to reduce load
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
if (args.length == 1) {
List<PSRegion> regions = psp.getPSRegionsCrossWorld(psp.getPlayer().getWorld(), true);
display(s, regions, psp.getUuid(), true);
} else if (args.length == 2) {
UUID uuid = UUIDCache.getUUIDFromName(args[1]);
List<PSRegion> regions = PSPlayer.fromUUID(uuid).getPSRegionsCrossWorld(psp.getPlayer().getWorld(), true);
display(s, regions, uuid, false);
} else {
PSL.msg(s, PSL.LIST_HELP.msg());
}
});
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (!sender.hasPermission("protectionstones.list") || !sender.hasPermission("protectionstones.list.others")) {
return null;
}
if (args.length == 2) {
// autocomplete with online player list
return StringUtil.copyPartialMatches(args[1], Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName).collect(Collectors.toList()), new ArrayList<>());
}
return null;
}
private void display(CommandSender s, List<PSRegion> regions, UUID pUUID, boolean isCurrentPlayer) {
List<String> ownerOf = new ArrayList<>(), memberOf = new ArrayList<>();
for (PSRegion r : regions) {
if (r.isOwner(pUUID)) {
if (r.getName() == null) {
ownerOf.add(ChatColor.GRAY + "> " + ChatColor.AQUA + r.getId());
} else {
ownerOf.add(ChatColor.GRAY + "> " + ChatColor.AQUA + r.getName() + " (" + r.getId() + ")");
}
}
if (r.isMember(pUUID)) {
if (r.getName() == null) {
memberOf.add(ChatColor.GRAY + "> " + ChatColor.AQUA + r.getId());
} else {
memberOf.add(ChatColor.GRAY + "> " + ChatColor.AQUA + r.getName() + " (" + r.getId() + ")");
}
}
}
if (ownerOf.isEmpty() && memberOf.isEmpty()) {
if (isCurrentPlayer) {
PSL.msg(s, PSL.LIST_NO_REGIONS.msg());
} else {
PSL.msg(s, PSL.LIST_NO_REGIONS_PLAYER.msg().replace("%player%", UUIDCache.getNameFromUUID(pUUID)));
}
return;
}
PSL.msg(s, PSL.LIST_HEADER.msg().replace("%player%", UUIDCache.getNameFromUUID(pUUID)));
if (!ownerOf.isEmpty()) {
PSL.msg(s, PSL.LIST_OWNER.msg());
for (String str : ownerOf) s.sendMessage(str);
}
if (!memberOf.isEmpty()) {
PSL.msg(s, PSL.LIST_MEMBER.msg());
for (String str : memberOf) s.sendMessage(str);
}
}
}
| 5,146 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgRent.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgRent.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSEconomy;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.LimitUtil;
import dev.espi.protectionstones.utils.MiscUtil;
import dev.espi.protectionstones.utils.UUIDCache;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.time.Duration;
import java.util.*;
public class ArgRent implements PSCommandArg {
public static String getLeaseHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" rent lease [price] [period]";
}
public static String getStopLeaseHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" rent stoplease";
}
public static String getRentHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" rent rent";
}
public static String getStopRentingHelp() {
return ChatColor.AQUA + "> " + ChatColor.GRAY + "/" + ProtectionStones.getInstance().getConfigOptions().base_command +
" rent stoprenting";
}
@Override
public List<String> getNames() {
return Arrays.asList("rent");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.rent");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
private void runHelp(CommandSender s) {
PSL.msg(s, PSL.RENT_HELP_HEADER.msg());
PSL.msg(s, getLeaseHelp());
PSL.msg(s, getStopLeaseHelp());
PSL.msg(s, getRentHelp());
PSL.msg(s, getStopRentingHelp());
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.rent")) {
return PSL.msg(s, PSL.NO_PERMISSION_RENT.msg());
}
if (!ProtectionStones.getInstance().isVaultSupportEnabled()) {
Bukkit.getLogger().info(ChatColor.RED + "Vault is required, but is not enabled on this server. Contact an administrator.");
s.sendMessage(ChatColor.RED + "Vault is required, but is not enabled on this server. Contact an administrator.");
return true;
}
Player p = (Player) s;
if (args.length == 1) {
runHelp(s);
} else {
if (args[1].equals("help")) {
runHelp(s);
return true;
}
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null) {
return PSL.msg(p, PSL.NOT_IN_REGION.msg());
}
switch (args[1]) {
case "lease":
if (!r.isOwner(p.getUniqueId())) // check if player is a region owner
return PSL.msg(p, PSL.NOT_OWNER.msg());
if (r.getRentStage() == PSRegion.RentStage.RENTING) // check if already renting
return PSL.msg(p, PSL.RENT_ALREADY_RENTING.msg());
if (args.length < 4)
return PSL.msg(p, getLeaseHelp());
if (!NumberUtils.isNumber(args[2])) // check price
return PSL.msg(p, getLeaseHelp());
if (r.forSale()) // if region is already being sold
return PSL.msg(p, PSL.RENT_BEING_SOLD.msg());
double price = Double.parseDouble(args[2]);
if (ProtectionStones.getInstance().getConfigOptions().minRentPrice != -1 && price < ProtectionStones.getInstance().getConfigOptions().minRentPrice) // if rent price is too low
return PSL.msg(p, PSL.RENT_PRICE_TOO_LOW.msg().replace("%price%", ""+ProtectionStones.getInstance().getConfigOptions().minRentPrice));
if (ProtectionStones.getInstance().getConfigOptions().maxRentPrice != -1 && price > ProtectionStones.getInstance().getConfigOptions().maxRentPrice) // if rent price is too high
return PSL.msg(p, PSL.RENT_PRICE_TOO_HIGH.msg().replace("%price%", ""+ProtectionStones.getInstance().getConfigOptions().maxRentPrice));
String period = String.join(" ", Arrays.asList(args).subList(3, args.length));
try {
Duration d = MiscUtil.parseRentPeriod(period);
if (ProtectionStones.getInstance().getConfigOptions().minRentPeriod != -1 && d.getSeconds() < ProtectionStones.getInstance().getConfigOptions().minRentPeriod) {
return PSL.msg(p, PSL.RENT_PERIOD_TOO_SHORT.msg().replace("%period%", ""+ProtectionStones.getInstance().getConfigOptions().minRentPeriod));
}
if (ProtectionStones.getInstance().getConfigOptions().maxRentPeriod != -1 && d.getSeconds() > ProtectionStones.getInstance().getConfigOptions().maxRentPeriod) {
return PSL.msg(p, PSL.RENT_PERIOD_TOO_LONG.msg().replace("%period%", ""+ProtectionStones.getInstance().getConfigOptions().maxRentPeriod));
}
} catch (NumberFormatException e) {
return PSL.msg(p, PSL.RENT_PERIOD_INVALID.msg());
}
r.setRentable(p.getUniqueId(), period, price);
return PSL.msg(p, PSL.RENT_LEASE_SUCCESS.msg().replace("%price%", args[2]).replace("%period%", period));
case "stoplease":
if (r.getRentStage() == PSRegion.RentStage.NOT_RENTING)
return PSL.msg(p, PSL.RENT_NOT_RENTED.msg());
if (r.getTypeOptions().landlordStillOwner) {
// landlord can be any of the region's owner; doesn't really matter if tenant calls /ps rent stoplease
if (!r.isOwner(p.getUniqueId()))
return PSL.msg(p, PSL.NOT_OWNER.msg());
} else {
// landlord must be the specified landlord
if (r.getLandlord() != null && !p.getUniqueId().equals(r.getLandlord()))
return PSL.msg(p, PSL.NOT_OWNER.msg());
}
UUID tenant = r.getTenant();
r.removeRenting();
PSL.msg(p, PSL.RENT_STOPPED.msg());
if (tenant != null) {
PSL.msg(p, PSL.RENT_EVICTED.msg().replace("%tenant%", UUIDCache.getNameFromUUID(tenant)));
Player tenantPlayer = Bukkit.getPlayer(tenant);
if (tenantPlayer != null && tenantPlayer.isOnline()) {
PSL.msg(p, PSL.RENT_TENANT_STOPPED_TENANT.msg().replace("%region%", r.getName() == null ? r.getId() : r.getName()));
}
}
break;
case "rent":
if (r.getRentStage() != PSRegion.RentStage.LOOKING_FOR_TENANT)
return PSL.msg(p, PSL.RENT_NOT_RENTING.msg());
if (!ProtectionStones.getInstance().getVaultEconomy().has(p, r.getPrice()))
return PSL.msg(p, PSL.NOT_ENOUGH_MONEY.msg().replace("%price%", String.format("%.2f", r.getPrice())));
if (r.getLandlord().equals(p.getUniqueId()))
return PSL.msg(p, PSL.RENT_CANNOT_RENT_OWN_REGION.msg());
if (LimitUtil.hasPassedOrEqualsRentLimit(p))
return PSL.msg(p, PSL.RENT_REACHED_LIMIT.msg());
r.rentOut(r.getLandlord(), p.getUniqueId(), r.getRentPeriod(), r.getPrice());
PSL.msg(p, PSL.RENT_RENTING_TENANT.msg()
.replace("%region%", r.getName() == null ? r.getId() : r.getName())
.replace("%price%", String.format("%.2f", r.getPrice()))
.replace("%period%", r.getRentPeriod()));
if (Bukkit.getPlayer(r.getLandlord()) != null) {
PSL.msg(Bukkit.getPlayer(r.getLandlord()), PSL.RENT_RENTING_LANDLORD.msg()
.replace("%player%", p.getName())
.replace("%region%", r.getName() == null ? r.getId() : r.getName()));
}
PSEconomy.doRentPayment(r);
break;
case "stoprenting":
if (r.getTenant() == null || !r.getTenant().equals(p.getUniqueId()))
return PSL.msg(p, PSL.RENT_NOT_TENANT.msg());
r.removeOwner(r.getTenant());
r.removeMember(r.getTenant());
r.addOwner(r.getLandlord());
r.setTenant(null);
PSL.msg(p, PSL.RENT_TENANT_STOPPED_TENANT.msg().replace("%region%", r.getName() == null ? r.getId() : r.getName()));
if (Bukkit.getPlayer(r.getLandlord()) != null) {
PSL.msg(Bukkit.getPlayer(r.getLandlord()), PSL.RENT_TENANT_STOPPED_LANDLORD.msg()
.replace("%player%", p.getName())
.replace("%region%", r.getName() == null ? r.getId() : r.getName()));
}
break;
default:
runHelp(s);
break;
}
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
List<String> arg = Arrays.asList("lease", "stoplease", "rent", "stoprenting");
if (args.length == 3 && args[1].equals("lease")) {
return StringUtil.copyPartialMatches(args[2], Arrays.asList("100"), new ArrayList<>());
} else if (args.length == 4 && args[1].equals("lease")) {
return StringUtil.copyPartialMatches(args[3], Arrays.asList("1w", "1d", "1h"), new ArrayList<>());
}
return args.length == 2 ? StringUtil.copyPartialMatches(args[1], arg, new ArrayList<>()) : null;
}
}
| 11,415 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminFlag.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminFlag.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.FlagHandler;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.UUIDCache;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
class ArgAdminFlag {
static boolean argumentAdminFlag(CommandSender p, String[] args) {
if (args.length < 5) {
PSL.msg(p, ArgAdmin.getFlagHelp());
return true;
}
String flag, value = "", gee = "";
World w = Bukkit.getWorld(args[2]);
if (w == null)
return PSL.msg(p, PSL.INVALID_WORLD.msg());
if (args[3].equalsIgnoreCase("-g")) {
flag = args[5];
for (int i = 6; i < args.length; i++) value += args[i] + " ";
gee = args[4];
} else {
flag = args[3];
for (int i = 4; i < args.length; i++) value += args[i] + " ";
}
if (WGUtils.getFlagRegistry().get(flag) == null)
return PSL.msg(p, PSL.FLAG_NOT_SET.msg());
final String fValue = value, fGee = gee;
RegionManager rgm = WGUtils.getRegionManagerWithWorld(w);
for (ProtectedRegion r : rgm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r) && PSRegion.fromWGRegion(w, r) != null) {
String flagValue = fValue;
// apply %player% placeholder
if (FlagHandler.getPlayerPlaceholderFlags().contains(flag) && (!r.getOwners().getUniqueIds().isEmpty())) {
String name = UUIDCache.getNameFromUUID(r.getOwners().getUniqueIds().stream().findFirst().get());
if (name != null) {
flagValue = flagValue.replace("%player%", name);
}
}
ArgFlag.setFlag(PSRegion.fromWGRegion(w, r), p, flag, flagValue.trim(), fGee);
}
}
return true;
}
}
| 2,888 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgHelp.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgHelp.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.MiscUtil;
import dev.espi.protectionstones.utils.TextGUI;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgHelp implements PSCommandArg {
private static class HelpEntry {
String[] permission;
TextComponent msg;
HelpEntry(TextComponent msg, String... permission) {
this.permission = permission;
this.msg = msg;
}
}
public static List<HelpEntry> helpMenu = new ArrayList<>();
public static void initHelpMenu() {
String base = "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " ";
helpMenu.clear();
helpMenu.add(new HelpEntry(sendWithPerm(PSL.INFO_HELP.msg(), PSL.INFO_HELP_DESC.msg(), base + "info"), "protectionstones.info"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.ADDREMOVE_HELP.msg(), PSL.ADDREMOVE_HELP_DESC.msg(), base), "protectionstones.members"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.ADDREMOVE_OWNER_HELP.msg(), PSL.ADDREMOVE_OWNER_HELP_DESC.msg(), base), "protectionstones.owners"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.GET_HELP.msg(), PSL.GET_HELP_DESC.msg(), base + "get"), "protectionstones.get"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.GIVE_HELP.msg(), PSL.GIVE_HELP_DESC.msg(), base + "give"), "protectionstones.give"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.COUNT_HELP.msg(), PSL.COUNT_HELP_DESC.msg(), base + "count"), "protectionstones.count", "protectionstones.count.others"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.LIST_HELP.msg(), PSL.LIST_HELP_DESC.msg(), base + "list"), "protectionstones.list", "protectionstones.list.others"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.NAME_HELP.msg(), PSL.NAME_HELP_DESC.msg(), base + "name"), "protectionstones.name"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.MERGE_HELP.msg(), PSL.MERGE_HELP_DESC.msg(), base + "merge"), "protectionstones.merge"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.SETPARENT_HELP.msg(), PSL.SETPARENT_HELP_DESC.msg(), base + "setparent"), "protectionstones.setparent", "protectionstones.setparent.others"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.FLAG_HELP.msg(), PSL.FLAG_HELP_DESC.msg(), base + "flag"), "protectionstones.flags"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.RENT_HELP.msg(), PSL.RENT_HELP_DESC.msg(), base + "rent"), "protectionstones.rent"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.TAX_HELP.msg(), PSL.TAX_HELP_DESC.msg(), base + "tax"), "protectionstones.tax"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.BUY_HELP.msg(), PSL.BUY_HELP_DESC.msg(), base + "buy"), "protectionstones.buysell"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.SELL_HELP.msg(), PSL.SELL_HELP_DESC.msg(), base + "sell"), "protectionstones.buysell"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.HOME_HELP.msg(), PSL.HOME_HELP_DESC.msg(), base + "home"), "protectionstones.home"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.SETHOME_HELP.msg(), PSL.SETHOME_HELP_DESC.msg(), base + "sethome"), "protectionstones.sethome"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.TP_HELP.msg(), PSL.TP_HELP_DESC.msg(), base + "tp"), "protectionstones.tp"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.VISIBILITY_HIDE_HELP.msg(), PSL.VISIBILITY_HIDE_HELP_DESC.msg(), base + "hide"), "protectionstones.hide"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.VISIBILITY_UNHIDE_HELP.msg(), PSL.VISIBILITY_UNHIDE_HELP_DESC.msg(), base + "unhide"), "protectionstones.unhide"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.TOGGLE_HELP.msg(), PSL.TOGGLE_HELP_DESC.msg(), base + "toggle"), "protectionstones.toggle"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.VIEW_HELP.msg(), PSL.VIEW_HELP_DESC.msg(), base + "view"), "protectionstones.view"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.UNCLAIM_HELP.msg(), PSL.UNCLAIM_HELP_DESC.msg(), base + "unclaim"), "protectionstones.unclaim"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.PRIORITY_HELP.msg(), PSL.PRIORITY_HELP_DESC.msg(), base + "priority"), "protectionstones.priority"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.REGION_HELP.msg(), PSL.REGION_HELP_DESC.msg(), base + "region"), "protectionstones.region"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.ADMIN_HELP.msg(), PSL.ADMIN_HELP_DESC.msg(), base + "admin"), "protectionstones.admin"));
helpMenu.add(new HelpEntry(sendWithPerm(PSL.RELOAD_HELP.msg(), PSL.RELOAD_HELP_DESC.msg(), base + "reload"), "protectionstones.admin"));
}
@Override
public List<String> getNames() {
return Collections.singletonList("help");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return null;
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
private static final int GUI_SIZE = 16;
@Override
public boolean executeArgument(CommandSender p, String[] args, HashMap<String, String> flags) {
int page = 0;
if (args.length > 1 && MiscUtil.isValidInteger(args[1])) {
page = Integer.parseInt(args[1]) - 1;
}
List<TextComponent> entries = new ArrayList<>();
for (HelpEntry he : helpMenu) {
// ignore blank lines
if (he.msg.getText().equals("")) {
continue;
}
// check player permissions
for (String perm : he.permission) {
if (p.hasPermission(perm)) {
entries.add(he.msg);
break;
}
}
}
TextGUI.displayGUI(p, PSL.HELP.msg(), "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " help %page%", page, GUI_SIZE, entries, false);
if (page >= 0 && page * GUI_SIZE + GUI_SIZE < entries.size()) {
PSL.msg(p, PSL.HELP_NEXT.msg().replace("%page%", page + 2 + ""));
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
private static TextComponent sendWithPerm(String msg, String desc, String cmd) {
TextComponent m = new TextComponent(msg);
m.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd));
m.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(desc).create()));
return m;
}
}
| 7,830 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminHide.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminHide.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
class ArgAdminHide {
// /ps admin hide
static boolean argumentAdminHide(CommandSender p, String[] args) {
RegionManager mgr;
World w;
if (p instanceof Player) {
mgr = WGUtils.getRegionManagerWithPlayer((Player) p);
w = ((Player) p).getWorld();
} else {
if (args.length != 3) {
PSL.msg(p, PSL.ADMIN_CONSOLE_WORLD.msg());
return true;
}
if (Bukkit.getWorld(args[2]) == null) {
PSL.msg(p, PSL.INVALID_WORLD.msg());
return true;
}
w = Bukkit.getWorld(args[2]);
mgr = WGUtils.getRegionManagerWithWorld(w);
}
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
// loop through regions that are protection stones and hide or unhide the block
for (ProtectedRegion r : mgr.getRegions().values()) {
if (ProtectionStones.isPSRegion(r)) {
PSRegion region = PSRegion.fromWGRegion(w, r);
if (args[1].equalsIgnoreCase("hide")) {
Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), region::hide);
} else if (args[1].equalsIgnoreCase("unhide")){
Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), region::unhide);
}
}
}
String hMessage = args[1].equalsIgnoreCase("unhide") ? "unhidden" : "hidden";
PSL.msg(p, PSL.ADMIN_HIDE_TOGGLED.msg()
.replace("%message%", hMessage));
});
return true;
}
}
| 2,842 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgBuySell.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgBuySell.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSPlayer;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.LimitUtil;
import dev.espi.protectionstones.utils.UUIDCache;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class ArgBuySell implements PSCommandArg {
@Override
public List<String> getNames() {
return Arrays.asList("buy", "sell");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.buysell");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
if (!p.hasPermission("protectionstones.buysell")) {
PSL.msg(p, PSL.NO_PERMISSION_BUYSELL.msg());
return true;
}
if (!ProtectionStones.getInstance().isVaultSupportEnabled()) {
Bukkit.getLogger().info(ChatColor.RED + "Vault is required, but is not enabled on this server. Contact an administrator.");
s.sendMessage(ChatColor.RED + "Vault is required, but is not enabled on this server. Contact an administrator.");
return true;
}
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null)
return PSL.msg(p, PSL.NOT_IN_REGION.msg());
if (args[0].equals("buy")) { // buying
if (!r.forSale())
return PSL.msg(p, PSL.BUY_NOT_FOR_SALE.msg());
if ((!r.getTypeOptions().permission.equals("") && !p.hasPermission(r.getTypeOptions().permission)))
return PSL.msg(p, PSL.NO_PERMISSION_REGION_TYPE.msg());
// check if player reached region limit
if (!LimitUtil.check(p, r.getTypeOptions()))
return PSL.msg(p, PSL.REACHED_REGION_LIMIT.msg().replace("%limit%", "" + PSPlayer.fromPlayer(p).getGlobalRegionLimits()));
if (!PSPlayer.fromPlayer(p).hasAmount(r.getPrice()))
return PSL.msg(p, PSL.NOT_ENOUGH_MONEY.msg().replace("%price%", new DecimalFormat("#.##").format(r.getPrice())));
PSL.msg(p, PSL.BUY_SOLD_BUYER.msg()
.replace("%region%", r.getName() == null ? r.getId() : r.getName())
.replace("%price%", String.format("%.2f", r.getPrice()))
.replace("%player%", UUIDCache.getNameFromUUID(r.getLandlord())));
if (Bukkit.getPlayer(r.getLandlord()) != null) {
PSL.msg(Bukkit.getPlayer(r.getLandlord()), PSL.BUY_SOLD_SELLER.msg()
.replace("%region%", r.getName() == null ? r.getId() : r.getName())
.replace("%price%", String.format("%.2f", r.getPrice()))
.replace("%player%", p.getName()));
}
r.sell(p.getUniqueId());
} else if (args[0].equals("sell")) { // selling
if (!r.isOwner(p.getUniqueId()))
return PSL.msg(p, PSL.NOT_OWNER.msg());
if (args.length != 2)
return PSL.msg(p, PSL.SELL_HELP.msg());
if (r.getRentStage() != PSRegion.RentStage.NOT_RENTING)
return PSL.msg(p, PSL.SELL_RENTED_OUT.msg());
if (args[1].equals("stop")) {
r.setSellable(false, null, 0);
PSL.msg(p, PSL.BUY_STOP_SELL.msg());
} else {
if (!NumberUtils.isNumber(args[1]))
return PSL.msg(p, PSL.SELL_HELP.msg());
PSL.msg(p, PSL.SELL_FOR_SALE.msg().replace("%price%", String.format("%.2f", Double.parseDouble(args[1]))));
r.setSellable(true, p.getUniqueId(), Double.parseDouble(args[1]));
}
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 5,104 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgInfo.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgInfo.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.UUIDCache;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
public class ArgInfo implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("info");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.info");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroupUnsafe(p.getLocation());
if (r == null)
return PSL.NOT_IN_REGION.send(p);
if (!p.hasPermission("protectionstones.info.others") && WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), true))
return PSL.NO_ACCESS.send(p);
if (r.getTypeOptions() == null) {
PSL.msg(p, ChatColor.RED + "This region is problematic, and the block type (" + r.getType() + ") is not configured. Please contact an administrator.");
Bukkit.getLogger().info(ChatColor.RED + "This region is problematic, and the block type (" + r.getType() + ") is not configured.");
return true;
}
if (args.length == 1) { // info of current region player is in
if (!p.hasPermission("protectionstones.info"))
return PSL.NO_PERMISSION_INFO.send(p);
PSL.msg(p, PSL.INFO_HEADER.msg());
// region: %region%, priority: %priority%
StringBuilder sb = new StringBuilder();
if (r.getName() == null) {
PSL.INFO_REGION2.append(sb, r.getId());
} else {
PSL.INFO_REGION2.append(sb, r.getName() + " (" + r.getId() + ")");
}
if (!PSL.INFO_PRIORITY2.isEmpty()) {
sb.append(", ").append(PSL.INFO_PRIORITY2.format(r.getWGRegion().getPriority()));
}
PSL.msg(p, sb.toString());
// type: %type%
if (r instanceof PSGroupRegion) {
PSL.INFO_TYPE2.send(p, r.getTypeOptions().alias + " " + PSL.INFO_MAY_BE_MERGED.msg());
displayMerged(p, (PSGroupRegion) r);
} else {
PSL.INFO_TYPE2.send(p, r.getTypeOptions().alias);
}
displayEconomy(p, r);
displayFlags(p, r);
displayOwners(p, r.getWGRegion());
displayMembers(p, r.getWGRegion());
if (r.getParent() != null) {
if (r.getName() != null) {
PSL.INFO_PARENT2.send(p, r.getParent().getName() + " (" + r.getParent().getId() + ")");
} else {
PSL.INFO_PARENT2.send(p, r.getParent().getId());
}
}
BlockVector3 min = r.getWGRegion().getMinimumPoint();
BlockVector3 max = r.getWGRegion().getMaximumPoint();
// only show x,z if it's at block limit
if (min.getBlockY() == WGUtils.MIN_BUILD_HEIGHT && max.getBlockY() == WGUtils.MAX_BUILD_HEIGHT) {
PSL.INFO_BOUNDS_XZ.send(p,
min.getBlockX(), min.getBlockZ(),
max.getBlockX(), max.getBlockZ()
);
} else {
PSL.INFO_BOUNDS_XYZ.send(p,
min.getBlockX(), min.getBlockY(), min.getBlockZ(),
max.getBlockX(), max.getBlockY(), max.getBlockZ()
);
}
} else if (args.length == 2) { // get specific information on current region
switch (args[1].toLowerCase()) {
case "members":
if (!p.hasPermission("protectionstones.members"))
return PSL.NO_PERMISSION_MEMBERS.send(p);
displayMembers(p, r.getWGRegion());
break;
case "owners":
if (!p.hasPermission("protectionstones.owners"))
return PSL.NO_PERMISSION_OWNERS.send(p);
displayOwners(p, r.getWGRegion());
break;
case "flags":
if (!p.hasPermission("protectionstones.flags"))
return PSL.NO_PERMISSION_FLAGS.send(p);
displayFlags(p, r);
break;
default:
PSL.INFO_HELP.send(p);
break;
}
} else {
PSL.INFO_HELP.send(p);
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
private static void displayMerged(Player p, PSGroupRegion r) {
StringBuilder msg = new StringBuilder();
for (PSMergedRegion pr : r.getMergedRegions()) {
msg.append(pr.getId()).append(" (").append(pr.getTypeOptions().alias).append("), ");
}
PSL.INFO_MERGED2.send(p, msg);
}
private static void displayEconomy(Player p, PSRegion r) {
if (r.forSale()) {
PSL.INFO_AVAILABLE_FOR_SALE.send(p);
PSL.INFO_SELLER2.send(p, UUIDCache.getNameFromUUID(r.getLandlord()));
PSL.INFO_PRICE2.send(p, String.format("%.2f", r.getPrice()));
}
if (r.getRentStage() == PSRegion.RentStage.LOOKING_FOR_TENANT) {
PSL.INFO_AVAILABLE_FOR_SALE.send(p);
}
if (r.getRentStage() == PSRegion.RentStage.RENTING) {
PSL.INFO_TENANT2.send(p, UUIDCache.getNameFromUUID(r.getTenant()));
}
if (r.getRentStage() != PSRegion.RentStage.NOT_RENTING) {
PSL.INFO_LANDLORD2.send(p, UUIDCache.getNameFromUUID(r.getLandlord()));
PSL.INFO_RENT2.send(p, String.format("%.2f", r.getPrice()));
}
}
private static void displayFlags(Player p, PSRegion r) {
ProtectedRegion region = r.getWGRegion();
PSProtectBlock typeOptions = r.getTypeOptions();
StringBuilder flagDisp = new StringBuilder();
String flagValue;
// loop through all flags
for (Flag<?> flag : WGUtils.getFlagRegistry().getAll()) {
if (region.getFlag(flag) != null && !typeOptions.hiddenFlagsFromInfo.contains(flag.getName())) {
flagValue = region.getFlag(flag).toString();
RegionGroupFlag groupFlag = flag.getRegionGroupFlag();
if (region.getFlag(groupFlag) != null) {
flagDisp.append(String.format("%s: -g %s %s, ", flag.getName(), region.getFlag(groupFlag), flagValue));
} else {
flagDisp.append(String.format("%s: %s, ", flag.getName(), flagValue));
}
flagDisp.append(ChatColor.GRAY);
}
}
if (flagDisp.length() > 2) {
flagDisp = new StringBuilder(flagDisp.substring(0, flagDisp.length() - 2) + ".");
PSL.INFO_FLAGS2.send(p, flagDisp);
} else {
PSL.INFO_FLAGS2.send(p, PSL.INFO_NO_FLAGS.msg());
}
}
private static void displayOwners(Player p, ProtectedRegion region) {
DefaultDomain owners = region.getOwners();
StringBuilder msg = new StringBuilder();
if (owners.size() == 0) {
PSL.INFO_NO_OWNERS.append(msg);
} else {
for (UUID uuid : owners.getUniqueIds()) {
String name = UUIDCache.getNameFromUUID(uuid);
if (name == null) name = Bukkit.getOfflinePlayer(uuid).getName();
msg.append(name).append(", ");
}
for (String name : owners.getPlayers()) { // legacy purposes
msg.append(name).append(", ");
}
msg = new StringBuilder(msg.substring(0, msg.length() - 2));
}
PSL.INFO_OWNERS2.send(p, msg);
}
private static void displayMembers(Player p, ProtectedRegion region) {
DefaultDomain members = region.getMembers();
StringBuilder msg = new StringBuilder();
if (members.size() == 0) {
PSL.INFO_NO_MEMBERS.append(msg);
} else {
for (UUID uuid : members.getUniqueIds()) {
String name = UUIDCache.getNameFromUUID(uuid);
if (name == null) name = uuid.toString();
msg.append(name).append(", ");
}
for (String name : members.getPlayers()) { // legacy purposes
msg.append(name).append(", ");
}
msg = new StringBuilder(msg.substring(0, msg.length() - 2));
}
PSL.INFO_MEMBERS2.send(p, msg);
}
}
| 10,115 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminForceMerge.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminForceMerge.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.FlagHandler;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.WGMerge;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.*;
public class ArgAdminForceMerge {
private static Set<String> flags = new HashSet<>(Arrays.asList("no_member_match", "no_flag_match", "one_owner_match"));
private static Map<Flag<?>, Object> getFlags(Map<Flag<?>, Object> flags) {
Map<Flag<?>, Object> f = new HashMap<>(flags);
f.remove(FlagHandler.PS_BLOCK_MATERIAL);
f.remove(FlagHandler.PS_MERGED_REGIONS_TYPES);
f.remove(FlagHandler.PS_MERGED_REGIONS);
f.remove(FlagHandler.PS_NAME);
f.remove(FlagHandler.PS_HOME);
return f;
}
private static boolean areDomainsEqualByOne(DefaultDomain o1, DefaultDomain o2) {
boolean ret = false;
for (UUID uuid : o1.getUniqueIds()) {
if (o2.contains(uuid)) ret = true;
}
for (UUID uuid : o2.getUniqueIds()) {
if (o1.contains(uuid)) ret = true;
}
return ret;
}
private static boolean areDomainsEqual(DefaultDomain o1, DefaultDomain o2) {
for (UUID uuid : o1.getUniqueIds()) {
if (!o2.contains(uuid)) return false;
}
for (UUID uuid : o2.getUniqueIds()) {
if (!o1.contains(uuid)) return false;
}
return true;
}
// /ps admin forcemerge [world]
public static boolean argumentAdminForceMerge(CommandSender p, String[] args) {
if (args.length < 3) {
PSL.msg(p, ArgAdmin.getForceMergeHelp());
return true;
}
String world = args[2];
World w = Bukkit.getWorld(world);
if (w == null) {
PSL.msg(p, PSL.INVALID_WORLD.msg());
return true;
}
Set<String> options = new HashSet<>();
for (int i = 3; i < args.length; i++) {
if (!flags.contains(args[i])) {
PSL.msg(p, ChatColor.RED + "Invalid option.");
return true;
} else {
options.add(args[i]);
}
}
RegionManager rm = WGUtils.getRegionManagerWithWorld(Bukkit.getWorld(world));
HashMap<String, String> idToGroup = new HashMap<>();
HashMap<String, List<PSRegion>> groupToMembers = new HashMap<>();
// loop over regions in world
for (ProtectedRegion r : rm.getRegions().values()) {
if (!ProtectionStones.isPSRegion(r)) continue;
if (r.getParent() != null) continue;
boolean merged = idToGroup.get(r.getId()) != null;
Map<Flag<?>, Object> baseFlags = getFlags(r.getFlags()); // comparison flags
PSRegion psr = PSRegion.fromWGRegion(w, r);
// loop over overlapping regions
for (ProtectedRegion rOverlap : rm.getApplicableRegions(r)) {
if (!ProtectionStones.isPSRegion(rOverlap)) continue;
if (rOverlap.getId().equals(r.getId())) continue;
Map<Flag<?>, Object> mergeFlags = getFlags(rOverlap.getFlags()); // comparison flags
// check if regions are roughly equal
if (!options.contains("no_member_match") && !areDomainsEqual(rOverlap.getMembers(), r.getMembers())) continue;
if (!options.contains("no_flag_match") && !baseFlags.equals(mergeFlags)) continue;
if (!options.contains("one_owner_match") && !areDomainsEqual(rOverlap.getOwners(), r.getOwners())) continue;
if (options.contains("one_owner_match") && !areDomainsEqualByOne(rOverlap.getOwners(), r.getOwners())) continue;
if (rOverlap.getParent() != null) continue;
// check groupings
String rOverlapGroup = idToGroup.get(rOverlap.getId());
if (merged) { // r is part of a group
String rGroup = idToGroup.get(r.getId());
if (rOverlapGroup == null) { // rOverlap not part of a group
idToGroup.put(rOverlap.getId(), rGroup);
groupToMembers.get(rGroup).add(PSRegion.fromWGRegion(w, rOverlap));
} else if (!rOverlapGroup.equals(rGroup)) { // rOverlap is part of a group (both are part of group)
for (PSRegion pr : groupToMembers.get(rOverlapGroup)) {
idToGroup.put(pr.getId(), rGroup);
}
groupToMembers.get(rGroup).addAll(groupToMembers.get(rOverlapGroup));
groupToMembers.remove(rOverlapGroup);
}
} else { // r not part of group
if (rOverlapGroup == null) { // both are not part of group
idToGroup.put(r.getId(), r.getId());
idToGroup.put(rOverlap.getId(), r.getId());
groupToMembers.put(r.getId(), new ArrayList<>(Arrays.asList(psr, PSRegion.fromWGRegion(w, rOverlap))));
} else { // rOverlap is part of group
idToGroup.put(r.getId(), rOverlapGroup);
groupToMembers.get(rOverlapGroup).add(psr);
}
merged = true;
}
}
}
// actually do region merging
for (String key : groupToMembers.keySet()) {
PSRegion root = null;
p.sendMessage(ChatColor.GRAY + "Merging these regions into " + key + ":");
for (PSRegion r : groupToMembers.get(key)) {
if (r.getId().equals(key)) root = r;
p.sendMessage(ChatColor.GRAY + r.getId());
}
try {
WGMerge.mergeRealRegions(w, rm, root, groupToMembers.get(key));
} catch (WGMerge.RegionHoleException | WGMerge.RegionCannotMergeWhileRentedException e) {
// TODO
}
}
p.sendMessage(ChatColor.GRAY + "Done!");
return true;
}
static List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (args.length == 3) {
List<String> l = new ArrayList<>();
for (World w : Bukkit.getWorlds()) l.add(w.getName());
return StringUtil.copyPartialMatches(args[2], l, new ArrayList<>());
} else {
return StringUtil.copyPartialMatches(args[args.length - 1], flags, new ArrayList<>());
}
}
}
| 7,721 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminStats.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminStats.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.managers.RegionManager;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import java.util.HashMap;
class ArgAdminStats {
// /ps admin stats
static boolean argumentAdminStats(CommandSender p, String[] args) {
WorldGuardPlugin wg = WorldGuardPlugin.inst();
int size = 0;
for (RegionManager rgm : WGUtils.getAllRegionManagers().values()) {
size += rgm.getRegions().values().stream().filter(ProtectionStones::isPSRegion).count();
}
if (args.length > 2) {
String playerName = args[2];
OfflinePlayer op = Bukkit.getOfflinePlayer(playerName);
int count = 0;
HashMap<World, RegionManager> m = WGUtils.getAllRegionManagers();
for (RegionManager rgm : m.values()) {
count += rgm.getRegionCountOfPlayer(wg.wrapOfflinePlayer(op));
}
p.sendMessage(ChatColor.YELLOW + playerName + ":");
p.sendMessage(ChatColor.YELLOW + "================");
long firstPlayed = (System.currentTimeMillis() - op.getFirstPlayed()) / 86400000L;
p.sendMessage(ChatColor.YELLOW + "First played " + firstPlayed + " days ago.");
long lastPlayed = (System.currentTimeMillis() - op.getLastPlayed()) / 86400000L;
p.sendMessage(ChatColor.YELLOW + "Last played " + lastPlayed + " days ago.");
String banMessage = (op.isBanned()) ? "Banned" : "Not Banned";
p.sendMessage(ChatColor.YELLOW + banMessage);
p.sendMessage(ChatColor.YELLOW + "Regions: " + count);
p.sendMessage(ChatColor.YELLOW + "================");
return true;
}
p.sendMessage(ChatColor.YELLOW + "================");
p.sendMessage(ChatColor.YELLOW + "Regions: " + size);
p.sendMessage(ChatColor.YELLOW + "================");
return true;
}
}
| 2,889 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgRegion.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgRegion.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.UUIDCache;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.*;
public class ArgRegion implements PSCommandArg {
// /ps region
@Override
public List<String> getNames() {
return Collections.singletonList("region");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.region");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
RegionManager rgm = WGUtils.getRegionManagerWithPlayer(p);
if (!p.hasPermission("protectionstones.region")) {
PSL.msg(p, PSL.NO_PERMISSION_REGION.msg());
return true;
}
if (args.length < 3) {
PSL.msg(p, PSL.REGION_HELP.msg());
return true;
}
if (!UUIDCache.containsName(args[2])) {
PSL.msg(p, PSL.PLAYER_NOT_FOUND.msg());
return true;
}
UUID playerUuid = UUIDCache.getUUIDFromName(args[2]);
if (args[1].equalsIgnoreCase("list")) { // list player's regions
StringBuilder regionMessage = new StringBuilder();
boolean found = false;
for (ProtectedRegion r : rgm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r) && r.getOwners().contains(playerUuid)) {
found = true;
regionMessage.append(r.getId()).append(", ");
}
}
if (!found) {
PSL.msg(p, PSL.REGION_NOT_FOUND_FOR_PLAYER.msg()
.replace("%player%", args[2]));
} else {
regionMessage = new StringBuilder(regionMessage.substring(0, regionMessage.length() - 2) + ".");
PSL.msg(p, PSL.REGION_LIST.msg()
.replace("%player%", args[2])
.replace("%regions%", regionMessage));
}
} else if ((args[1].equalsIgnoreCase("remove")) || (args[1].equalsIgnoreCase("disown"))) {
boolean found = false;
for (ProtectedRegion r : rgm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r)) {
PSRegion psr = PSRegion.fromWGRegion(p.getWorld(), r);
if (psr.isOwner(playerUuid)) {
found = true;
// remove as owner
psr.removeOwner(playerUuid);
// remove region if empty and is "remove" mode
if (psr.getOwners().size() == 0 && args[1].equalsIgnoreCase("remove")) {
psr.deleteRegion(true);
}
}
}
}
if (!found) {
PSL.msg(p, PSL.REGION_NOT_FOUND_FOR_PLAYER.msg().replace("%player%", args[2]));
return true;
}
if (args[1].equalsIgnoreCase("remove")) {
PSL.msg(p, PSL.REGION_REMOVE.msg().replace("%player%", args[2]));
} else if (args[1].equalsIgnoreCase("disown")) {
PSL.msg(p, PSL.REGION_DISOWN.msg().replace("%player%", args[2]));
}
} else {
PSL.msg(p, PSL.REGION_HELP.msg());
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return args.length == 2 ? StringUtil.copyPartialMatches(args[1], Arrays.asList("disown", "remove", "list"), new ArrayList<>()) : null;
}
}
| 4,924 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgView.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgView.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.ParticlesUtil;
import dev.espi.protectionstones.utils.RegionTraverse;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ArgView implements PSCommandArg {
private static List<UUID> cooldown = new ArrayList<>();
@Override
public List<String> getNames() {
return Collections.singletonList("view");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.view");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (!p.hasPermission("protectionstones.view")) {
PSL.msg(p, PSL.NO_PERMISSION_VIEW.msg());
return true;
}
if (r == null) {
PSL.msg(p, PSL.NOT_IN_REGION.msg());
return true;
}
if (!p.hasPermission("protectionstones.view.others") && WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), true)) {
PSL.msg(p, PSL.NO_ACCESS.msg());
return true;
}
if (cooldown.contains(p.getUniqueId())) {
PSL.msg(p, PSL.VIEW_COOLDOWN.msg());
return true;
}
PSL.msg(p, PSL.VIEW_GENERATING.msg());
// add player to cooldown
cooldown.add(p.getUniqueId());
Bukkit.getScheduler().runTaskLaterAsynchronously(ProtectionStones.getInstance(), () -> cooldown.remove(p.getUniqueId()), 20 * ProtectionStones.getInstance().getConfigOptions().psViewCooldown);
int playerY = p.getLocation().getBlockY(), minY = r.getWGRegion().getMinimumPoint().getBlockY(), maxY = r.getWGRegion().getMaximumPoint().getBlockY();
// send particles to client
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
AtomicInteger modU = new AtomicInteger(0);
if (r instanceof PSGroupRegion) {
PSGroupRegion pr = (PSGroupRegion) r;
for (PSMergedRegion psmr : pr.getMergedRegions()) {
handlePurpleParticle(p, new Location(p.getWorld(), 0.5 + psmr.getProtectBlock().getX(), 1.5 + psmr.getProtectBlock().getY(), 0.5 + psmr.getProtectBlock().getZ()));
for (int y = minY; y <= maxY; y += 10) {
handlePurpleParticle(p, new Location(p.getWorld(), 0.5 + psmr.getProtectBlock().getX(), 0.5 + y, 0.5 + psmr.getProtectBlock().getZ()));
}
}
} else {
handlePurpleParticle(p, new Location(p.getWorld(), 0.5 + r.getProtectBlock().getX(), 1.5 + r.getProtectBlock().getY(), 0.5 + r.getProtectBlock().getZ()));
for (int y = minY; y <= maxY; y += 10) {
handlePurpleParticle(p, new Location(p.getWorld(), 0.5 + r.getProtectBlock().getX(), 0.5 + y, 0.5 + r.getProtectBlock().getZ()));
}
}
RegionTraverse.traverseRegionEdge(new HashSet<>(r.getWGRegion().getPoints()), Collections.singletonList(r.getWGRegion()), tr -> {
if (tr.isVertex) {
handleBlueParticle(p, new Location(p.getWorld(), 0.5+tr.point.getX(), 0.5+playerY, 0.5+tr.point.getZ()));
for (int y = minY; y <= maxY; y += 5) {
handleBlueParticle(p, new Location(p.getWorld(), 0.5+tr.point.getX(), 0.5+y, 0.5+tr.point.getZ()));
}
} else {
if (modU.get() % 2 == 0) {
handlePinkParticle(p, new Location(p.getWorld(), 0.5+tr.point.getX(), 0.5+playerY, 0.5+tr.point.getZ()));
handlePinkParticle(p, new Location(p.getWorld(), 0.5+tr.point.getX(), 0.5+minY, 0.5+tr.point.getZ()));
handlePinkParticle(p, new Location(p.getWorld(), 0.5+tr.point.getX(), 0.5+maxY, 0.5+tr.point.getZ()));
}
modU.set((modU.get() + 1) % 2);
}
});
});
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
private static int PARTICLE_VIEW_DISTANCE_LIMIT = 150;
private static boolean handlePinkParticle(Player p, Location l) {
if (p.getLocation().distance(l) > PARTICLE_VIEW_DISTANCE_LIMIT || Math.abs(l.getY()-p.getLocation().getY()) > 30) return false;
ParticlesUtil.persistRedstoneParticle(p, l, new Particle.DustOptions(Color.fromRGB(233, 30, 99), 2), 30);
return true;
}
private static boolean handleBlueParticle(Player p, Location l) {
if (p.getLocation().distance(l) > PARTICLE_VIEW_DISTANCE_LIMIT || Math.abs(l.getY()-p.getLocation().getY()) > 30) return false;
ParticlesUtil.persistRedstoneParticle(p, l, new Particle.DustOptions(Color.fromRGB(0, 255, 255), 2), 30);
return true;
}
private static boolean handlePurpleParticle(Player p, Location l) {
if (p.getLocation().distance(l) > PARTICLE_VIEW_DISTANCE_LIMIT || Math.abs(l.getY()-p.getLocation().getY()) > 30) return false;
ParticlesUtil.persistRedstoneParticle(p, l, new Particle.DustOptions(Color.fromRGB(255, 0, 255), 10), 30);
return true;
}
}
| 6,551 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgFlag.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgFlag.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.MiscUtil;
import dev.espi.protectionstones.utils.WGUtils;
import net.md_5.bungee.api.chat.*;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.*;
public class ArgFlag implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("flag");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.flags");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
HashMap<String, Boolean> m = new HashMap<>();
m.put("-g", true); // group
return m;
}
private static final int GUI_SIZE = 18;
private static final List<String> FLAG_GROUPS = FlagHandler.FLAG_GROUPS;
private static final int[] REGION_GROUP_KERNING_LENGTHS = {2, 17, 14, 26, 23};
private String getDots(int num) {
StringBuilder str = new StringBuilder(" " + ChatColor.DARK_GRAY);
for (int i = 0; i < num; i++) str.append(".");
return str.toString();
}
// flag gui that has ability to use pages
private boolean openFlagGUI(Player p, PSRegion r, int page) {
List<String> allowedFlags = new ArrayList<>(r.getTypeOptions().allowedFlags.keySet());
// ensure the page is valid and in range
if (page < 0 || (page * GUI_SIZE) > allowedFlags.size()) {
PSL.msg(p, PSL.PAGE_DOES_NOT_EXIST.msg());
return true;
}
// add blank space if gui not long enough
for (int i = 0; i < (GUI_SIZE * page + GUI_SIZE) - (Math.min(allowedFlags.size(), GUI_SIZE * page + GUI_SIZE) - GUI_SIZE * page); i++) {
PSL.msg(p, ChatColor.WHITE + "");
}
PSL.msg(p, PSL.FLAG_GUI_HEADER.msg());
// send actual flags
for (int i = GUI_SIZE * page; i < Math.min(allowedFlags.size(), GUI_SIZE * page + GUI_SIZE); i++) {
if (i >= allowedFlags.size()) {
PSL.msg(p, ChatColor.WHITE + "");
} else {
String flag = allowedFlags.get(i);
List<String> currentFlagGroups = r.getTypeOptions().allowedFlags.get(flag);
TextComponent flagLine = new TextComponent();
// calculate flag command
String suggestedCommand = "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " flag ";
// match flag
Flag<?> f = Flags.fuzzyMatchFlag(WGUtils.getFlagRegistry(), flag);
if (f == null) continue;
Object fValue = r.getWGRegion().getFlag(f);
// check current flag's set group
String groupfValue = "all";
if (f.getRegionGroupFlag() != null && r.getWGRegion().getFlag(f.getRegionGroupFlag()) != null) {
groupfValue = r.getWGRegion().getFlag(f.getRegionGroupFlag()).toString()
.toLowerCase().replace("_", "");
}
// add flag group if there is one set for the flag (for use in click commands)
String flagGroup = "";
if (f.getRegionGroupFlag() != null && r.getWGRegion().getFlag(f.getRegionGroupFlag()) != null) {
flagGroup = "-g " + groupfValue + " ";
}
// replace § with & to prevent "illegal characters in chat" disconnection
if (fValue instanceof String) {
fValue = ((String) fValue).replace("§", "&");
}
// add line based on flag type
if (f instanceof StateFlag) { // allow/deny
boolean isGroupValueAll = groupfValue.equalsIgnoreCase("all") || groupfValue.isEmpty();
TextComponent allow = new TextComponent((fValue == StateFlag.State.ALLOW ? ChatColor.WHITE : ChatColor.DARK_GRAY) + "Allow"),
deny = new TextComponent((fValue == StateFlag.State.DENY ? ChatColor.WHITE : ChatColor.DARK_GRAY) + "Deny");
allow.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_GUI_HOVER_SET.msg()).create()));
deny.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_GUI_HOVER_SET.msg()).create()));
if (fValue == StateFlag.State.ALLOW) {
allow.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " none"));
deny.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " deny"));
} else if (fValue == StateFlag.State.DENY) {
allow.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " allow"));
deny.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " none"));
} else {
allow.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " allow"));
deny.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " deny"));
}
// HACK: Prevent pvp flag value from being changed to none/null, if it is set to a value with the group flag set to all
if (flag.equalsIgnoreCase("pvp") && isGroupValueAll) {
if (fValue == StateFlag.State.DENY) {
deny.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_PREVENT_EXPLOIT_HOVER.msg()).create()));
} else if (fValue == StateFlag.State.ALLOW) {
allow.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_PREVENT_EXPLOIT_HOVER.msg()).create()));
}
}
flagLine.addExtra(allow);
flagLine.addExtra(" ");
flagLine.addExtra(deny);
flagLine.addExtra(getDots(5));
} else if (f instanceof BooleanFlag) { // true/false
TextComponent allow = new TextComponent((fValue == Boolean.TRUE ? ChatColor.WHITE : ChatColor.DARK_GRAY) + "True"),
deny = new TextComponent((fValue == Boolean.FALSE ? ChatColor.WHITE : ChatColor.DARK_GRAY) + "False");
allow.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_GUI_HOVER_SET.msg()).create()));
deny.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_GUI_HOVER_SET.msg()).create()));
if (fValue == Boolean.TRUE) {
allow.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " none"));
deny.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " false"));
} else if (fValue == Boolean.FALSE) {
allow.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " true"));
deny.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " none"));
} else {
allow.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " true"));
deny.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + flagGroup + page + ":" + flag + " false"));
}
flagLine.addExtra(allow);
flagLine.addExtra(" ");
flagLine.addExtra(deny);
flagLine.addExtra(getDots(5));
} else { // text
TextComponent edit = new TextComponent(ChatColor.DARK_GRAY + "Edit");
edit.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.FLAG_GUI_HOVER_SET_TEXT.msg()
.replace("%value%", fValue == null ? "none" : fValue.toString())).create()));
edit.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, suggestedCommand + flagGroup + flag + " "));
flagLine.addExtra(edit);
flagLine.addExtra(getDots(22));
}
// put group it applies to
TextComponent groupChange = new TextComponent(ChatColor.DARK_GRAY + " [ " + ChatColor.WHITE + groupfValue + ChatColor.DARK_GRAY + " ]");
String nextGroup;
if (currentFlagGroups.contains(groupfValue)) { // if the current flag group is an allowed flag group
nextGroup = currentFlagGroups.get((currentFlagGroups.indexOf(groupfValue) + 1) % currentFlagGroups.size());
} else { // otherwise, just take the first allowed flag group
nextGroup = currentFlagGroups.get(0);
}
// set hover and click task for flag group
BaseComponent[] hover;
if (fValue == null) {
hover = new ComponentBuilder(PSL.FLAG_GUI_HOVER_CHANGE_GROUP_NULL.msg()).create();
} else {
hover = new ComponentBuilder(PSL.FLAG_GUI_HOVER_CHANGE_GROUP.msg().replace("%group%", nextGroup)).create();
}
if (!nextGroup.equals(groupfValue)) { // only display hover message if the group is not the same
groupChange.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hover));
}
groupChange.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, suggestedCommand + "-g " + nextGroup + " " + page + ":" + flag + " " + fValue));
flagLine.addExtra(groupChange);
// send message
flagLine.addExtra(getDots(40 - REGION_GROUP_KERNING_LENGTHS[FLAG_GROUPS.indexOf(groupfValue)]) + ChatColor.AQUA + " " + flag);
p.spigot().sendMessage(flagLine);
}
}
// create footer
TextComponent backPage = new TextComponent(ChatColor.AQUA + " <<"), nextPage = new TextComponent(ChatColor.AQUA + ">> ");
backPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.GO_BACK_PAGE.msg()).create()));
nextPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.GO_NEXT_PAGE.msg()).create()));
backPage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " flag " + (page - 1)));
nextPage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " flag " + (page + 1)));
TextComponent footer = new TextComponent(ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET);
// add back page button if the page isn't 0
if (page != 0) footer.addExtra(backPage);
// add page number
footer.addExtra(new TextComponent(ChatColor.WHITE + " " + (page + 1) + " "));
// add forward page button if the page isn't last
if (page * GUI_SIZE + GUI_SIZE < r.getTypeOptions().allowedFlags.size()) footer.addExtra(nextPage);
footer.addExtra(ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====");
p.spigot().sendMessage(footer);
return true;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (!p.hasPermission("protectionstones.flags")) {
PSL.msg(p, PSL.NO_PERMISSION_FLAGS.msg());
return true;
}
if (r == null) {
PSL.msg(p, PSL.NOT_IN_REGION.msg());
return true;
}
if (WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), false)) {
PSL.msg(p, PSL.NO_ACCESS.msg());
return true;
}
// /ps flag GUI
if (args.length == 1) return openFlagGUI(p, r, 0);
// go to GUI page
if (args.length == 2) {
if (MiscUtil.isValidInteger(args[1])) {
return openFlagGUI(p, r, Integer.parseInt(args[1]));
}
PSL.msg(p, PSL.FLAG_HELP.msg());
return true;
}
if (args.length < 3) {
PSL.msg(p, PSL.FLAG_HELP.msg());
return true;
}
// beyond 2 args (set flag)
try {
String flagName = args[1].toLowerCase();
String gui = "";
String[] flagSplit = flagName.split(":");
if (flagSplit.length == 2) { // check if there is a GUI that needs to be reshown
gui = flagSplit[0];
flagName = flagSplit[1];
}
LinkedHashMap<String, List<String>> allowedFlags = r.getTypeOptions().allowedFlags;
// check if flag is allowed and its group is also allowed
if (allowedFlags.keySet().contains(flagName) && allowedFlags.get(flagName).contains(flags.getOrDefault("-g", "all")) && p.hasPermission("protectionstones.flags.edit." + flagName)) {
StringBuilder value = new StringBuilder();
for (int i = 2; i < args.length; i++) value.append(args[i]).append(" ");
setFlag(r, p, args[1], value.toString().trim(), flags.getOrDefault("-g", ""));
// reshow GUI
if (!gui.equals("")) {
Bukkit.dispatchCommand(p, ProtectionStones.getInstance().getConfigOptions().base_command + " flag " + gui);
}
} else {
PSL.msg(p, PSL.NO_PERMISSION_PER_FLAG.msg());
}
} catch (ArrayIndexOutOfBoundsException e) {
PSL.msg(p, PSL.FLAG_HELP.msg());
}
return true;
}
// tab completion
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (sender instanceof Player) {
Player p = (Player) sender;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null) return null;
List<String> keywords = new ArrayList<>();
if (args.length == 2) { // -g, or allowed flag names
keywords.add("-g");
for (String f : r.getTypeOptions().allowedFlags.keySet()) { // must allow the "all" group
if (r.getTypeOptions().allowedFlags.get(f).contains("all")) {
keywords.add(f);
}
}
return StringUtil.copyPartialMatches(args[1], keywords, new ArrayList<>());
} else if (args.length == 3 && args[1].equals("-g")) { // -g options
keywords.addAll(FlagHandler.FLAG_GROUPS);
return StringUtil.copyPartialMatches(args[2], keywords, new ArrayList<>());
} else if (args.length == 3) { // flag options
keywords.addAll(Arrays.asList("null", "default"));
Flag<?> f = Flags.fuzzyMatchFlag(WGUtils.getFlagRegistry(), args[1]);
if (f instanceof StateFlag) {
keywords.addAll(Arrays.asList("allow", "deny"));
} else if (f instanceof BooleanFlag) {
keywords.addAll(Arrays.asList("true", "false"));
}
return StringUtil.copyPartialMatches(args[2], keywords, new ArrayList<>());
} else if (args.length == 4 && args[1].equals("-g")) { // -g option flag
for (String f : r.getTypeOptions().allowedFlags.keySet()) {
if (r.getTypeOptions().allowedFlags.get(f).contains(args[2])) { // if the flag is allowed for this group
keywords.add(f);
}
}
return StringUtil.copyPartialMatches(args[3], keywords, new ArrayList<>());
} else if (args.length == 5 && args[1].equals("-g")) { // -g option flag arg
keywords.addAll(Arrays.asList("null", "default"));
Flag<?> f = Flags.fuzzyMatchFlag(WGUtils.getFlagRegistry(), args[3]);
if (f instanceof StateFlag) {
keywords.addAll(Arrays.asList("allow", "deny"));
} else if (f instanceof BooleanFlag) {
keywords.addAll(Arrays.asList("true", "false"));
}
return StringUtil.copyPartialMatches(args[4], keywords, new ArrayList<>());
}
}
return null;
}
// /ps flag logic (utilizing WG internal /region flag logic)
static void setFlag(PSRegion r, CommandSender p, String flagName, String value, String groupValue) {
// correct the flag if gui flags are there
String[] flagSplit = flagName.split(":");
if (flagSplit.length == 2) flagName = flagSplit[1];
Flag flag = Flags.fuzzyMatchFlag(WGUtils.getFlagRegistry(), flagName);
ProtectedRegion region = r.getWGRegion();
try {
if (value.equalsIgnoreCase("default")) { // get default from config, or from WG
HashMap<Flag<?>, Object> flags = new HashMap<>(r.getTypeOptions().regionFlags);
FlagHandler.initDefaultFlagPlaceholders(flags, (Player) p);
if (flags.get(flag) != null) {
region.setFlag(flag, flags.get(flag));
} else {
region.setFlag(flag, flag.getDefault());
}
if (flag.getRegionGroupFlag() != null) {
region.setFlag(flag.getRegionGroupFlag(), null);
}
PSL.msg(p, PSL.FLAG_SET.msg().replace("%flag%", flagName));
} else if (value.equalsIgnoreCase("null") || value.equalsIgnoreCase("none")) { // null flag (remove)
// HACK: pvp flag should never be allowed to set null when the flag group is restricted to all, since
// the default is that nonmembers can be killed, but members cannot.
boolean isGroupValueAll = groupValue.equalsIgnoreCase("all") || groupValue.isEmpty();
if (r.getTypeOptions().regionFlags.get(flag) != null && isGroupValueAll && flagName.equalsIgnoreCase("pvp")) {
PSL.msg(p, PSL.FLAG_PREVENT_EXPLOIT.msg());
return;
}
region.setFlag(flag, null);
if (flag.getRegionGroupFlag() != null) {
region.setFlag(flag.getRegionGroupFlag(), null);
}
PSL.msg(p, PSL.FLAG_SET.msg().replace("%flag%", flagName));
} else { // custom set flag using WG internal
FlagContext fc = FlagContext.create().setInput(value).build();
region.setFlag(flag, flag.parseInput(fc));
if (!groupValue.equals("") && flag.getRegionGroupFlag() != null) {
region.setFlag(flag.getRegionGroupFlag(), flag.getRegionGroupFlag().detectValue(groupValue));
}
PSL.msg(p, PSL.FLAG_SET.msg().replace("%flag%", flagName));
}
} catch (InvalidFlagFormat invalidFlagFormat) {
//invalidFlagFormat.printStackTrace();
PSL.msg(p, PSL.FLAG_NOT_SET.msg().replace("%flag%", flagName));
}
}
}
| 21,287 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgGive.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgGive.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSProtectBlock;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.ProtectionStones;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.StringUtil;
import java.util.*;
public class ArgGive implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("give");
}
@Override
public boolean allowNonPlayersToExecute() {
return true;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.give");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender p, String[] args, HashMap<String, String> flags) {
if (!p.hasPermission("protectionstones.give"))
return PSL.msg(p, PSL.NO_PERMISSION_GIVE.msg());
if (args.length < 3)
return PSL.msg(p, PSL.GIVE_HELP.msg());
// check if player online
if (Bukkit.getPlayer(args[2]) == null)
return PSL.msg(p, PSL.PLAYER_NOT_FOUND.msg() + " (" + args[2] + ")");
// check if argument is valid block
PSProtectBlock cp = ProtectionStones.getProtectBlockFromAlias(args[1]);
if (cp == null)
return PSL.msg(p, PSL.INVALID_BLOCK.msg());
// check if item was able to be added (inventory not full)
Player ps = Bukkit.getPlayer(args[2]);
ItemStack item = cp.createItem();
if (args.length >= 4 && NumberUtils.isNumber(args[3]))
item.setAmount(Integer.parseInt(args[3]));
if (!ps.getInventory().addItem(item).isEmpty()) {
if (ProtectionStones.getInstance().getConfigOptions().dropItemWhenInventoryFull) {
PSL.msg(ps, PSL.NO_ROOM_DROPPING_ON_FLOOR.msg());
ps.getWorld().dropItem(ps.getLocation(), cp.createItem());
} else {
return PSL.msg(p, PSL.GIVE_NO_INVENTORY_ROOM.msg());
}
}
return PSL.msg(p, PSL.GIVE_GIVEN.msg().replace("%block%", args[1]).replace("%player%", Bukkit.getPlayer(args[2]).getDisplayName()));
}
// tab completion
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
List<String> l = new ArrayList<>();
if (args.length == 2) {
for (PSProtectBlock b : ProtectionStones.getInstance().getConfiguredBlocks()) l.add(b.alias);
return StringUtil.copyPartialMatches(args[1], l, new ArrayList<>());
} else if (args.length == 3) {
for (Player p : Bukkit.getOnlinePlayers()) l.add(p.getName());
return StringUtil.copyPartialMatches(args[2], l, new ArrayList<>());
}
return null;
}
}
| 3,708 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgCount.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgCount.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSGroupRegion;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSPlayer;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.UUIDCache;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
public class ArgCount implements PSCommandArg {
// Only PS regions, not other regions
static int[] countRegionsOfPlayer(UUID uuid, World w) {
int[] count = {0, 0}; // total, including merged
PSPlayer psp = PSPlayer.fromUUID(uuid);
psp.getPSRegions(w, false).forEach(r -> {
count[0]++;
if (r instanceof PSGroupRegion) {
count[1] += ((PSGroupRegion) r).getMergedRegions().size();
}
});
return count;
}
@Override
public List<String> getNames() {
return Collections.singletonList("count");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.count", "protectionstones.count.others");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
// /ps count
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
int[] count;
if (args.length == 1) {
if (!p.hasPermission("protectionstones.count")) {
PSL.msg(p, PSL.NO_PERMISSION_COUNT.msg());
return;
}
count = countRegionsOfPlayer(p.getUniqueId(), p.getWorld());
PSL.msg(p, PSL.PERSONAL_REGION_COUNT.msg().replace("%num%", "" + count[0]));
if (count[1] != 0) {
PSL.msg(p, PSL.PERSONAL_REGION_COUNT_MERGED.msg().replace("%num%", ""+count[1]));
}
} else if (args.length == 2) {
if (!p.hasPermission("protectionstones.count.others")) {
PSL.msg(p, PSL.NO_PERMISSION_COUNT_OTHERS.msg());
return;
}
if (!UUIDCache.containsName(args[1])) {
PSL.msg(p, PSL.PLAYER_NOT_FOUND.msg());
return;
}
UUID countUuid = UUIDCache.getUUIDFromName(args[1]);
count = countRegionsOfPlayer(countUuid, p.getWorld());
PSL.msg(p, PSL.OTHER_REGION_COUNT.msg()
.replace("%player%", UUIDCache.getNameFromUUID(countUuid))
.replace("%num%", "" + count[0]));
if (count[1] != 0) {
PSL.msg(p, PSL.OTHER_REGION_COUNT_MERGED.msg()
.replace("%player%", UUIDCache.getNameFromUUID(countUuid))
.replace("%num%", "" + count[1]));
}
} else {
PSL.msg(p, PSL.COUNT_HELP.msg());
}
});
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 4,133 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminHelp.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminHelp.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.ProtectionStones;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class ArgAdminHelp {
private static void send(CommandSender p, String text, String info) {
TextComponent tc = new TextComponent(text);
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(info).create()));
p.spigot().sendMessage(tc);
}
static boolean argumentAdminHelp(CommandSender p, String[] args) {
String bc = "/" + ProtectionStones.getInstance().getConfigOptions().base_command;
p.sendMessage(ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " PS Admin Help " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "=====\n" + ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps admin help");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin version", "Show the version number of the plugin.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin hide", "Hide all of the protection stone blocks in the world you are in.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin unhide", "Unhide all of the protection stone blocks in the world you are in.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin cleanup remove [days] [-t typealias (optional)] [world (console)]", "Remove inactive players that haven't joined within the last [days] days from protected regions in the world you are in (or specified). Then, remove any regions with no owners left.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin cleanup disown [days] [-t typealias (optional)] [world (console)]", "Remove inactive players that haven't joined within the last [days] days from protected regions in the world you are in (or specified).");
send(p, ArgAdmin.getFlagHelp(), "Set a flag for all protection stone regions in a world.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin lastlogon [player]", "Get the last time a player logged on.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin lastlogons", "List all of the last logons of each player.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin stats [player (optional)]", "Show some statistics of the plugin.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin recreate", "Recreate all PS regions using radius set in config.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin debug", "Toggles debug mode.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin settaxautopayers", "Add a tax autopayer for every region on the server that does not have one.");
send(p, ArgAdmin.getForceMergeHelp(), "Merge overlapping PS regions together if they have the same owners, members and flags.");
send(p, ArgAdmin.getChangeBlockHelp(), "Change all of the PS blocks and regions in a world to a different block. Both blocks must be configured in config.");
send(p, ArgAdmin.getChangeRegionTypeHelp(), "Change the internal type of all PS regions of a certain type. Useful for error correction.");
send(p, ChatColor.AQUA + "> " + ChatColor.GRAY + bc + " admin fixregions", "Use this command to recalculate block types for PS regions in a world.");
return true;
}
}
| 4,240 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminChangeType.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminChangeType.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.FlagHandler;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import java.util.HashSet;
import java.util.Set;
class ArgAdminChangeType {
// /ps admin changeregiontype [world] [fromblocktype] [toblocktype]
static boolean argumentAdminChangeType(CommandSender p, String[] args) {
if (args.length < 5) {
return PSL.msg(p, ArgAdmin.getChangeRegionTypeHelp());
}
World w = Bukkit.getWorld(args[2]);
if (w == null) {
return PSL.msg(p, PSL.INVALID_WORLD.msg());
}
RegionManager rgm = WGUtils.getRegionManagerWithWorld(w);
if (rgm == null) {
return PSL.msg(p, ChatColor.GRAY + "The world does not have WorldGuard configured!");
}
String fromType = args[3], toType = args[4];
// loop through and update flags manually (do not rely on PSRegion API, since this can include invalid regions)
for (ProtectedRegion r : rgm.getRegions().values()) {
// update block material
if (r.getFlag(FlagHandler.PS_BLOCK_MATERIAL) != null && r.getFlag(FlagHandler.PS_BLOCK_MATERIAL).equals(fromType)) {
r.setFlag(FlagHandler.PS_BLOCK_MATERIAL, toType);
p.sendMessage(ChatColor.GRAY + "Updated region " + r.getId());
}
// update merged regions
if (r.getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES) != null) {
Set<String> s = new HashSet<>();
for (String entry : r.getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES)) {
String[] spl = entry.split(" ");
if (spl.length == 2) {
if (spl[1].equals(fromType)) { // if it is of the type to change
p.sendMessage(ChatColor.GRAY + "Updated merged region " + spl[0]);
s.add(spl[0] + " " + toType);
} else {
s.add(entry);
}
}
}
r.setFlag(FlagHandler.PS_MERGED_REGIONS_TYPES, s);
}
}
p.sendMessage(ChatColor.GREEN + "Finished!");
p.sendMessage(ChatColor.GRAY + "You should restart the server, and make sure the new block type is configured in the config.");
return true;
}
}
| 3,325 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgReload.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgReload.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgReload implements PSCommandArg {
// /ps reload
@Override
public List<String> getNames() {
return Collections.singletonList("reload");
}
@Override
public boolean allowNonPlayersToExecute() {
return true;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.admin");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender p, String[] args, HashMap<String, String> flags) {
if (!p.hasPermission("protectionstones.admin")) {
PSL.msg(p, PSL.NO_PERMISSION_ADMIN.msg());
return true;
}
PSL.msg(p, PSL.RELOAD_START.msg());
ProtectionStones.loadConfig(true);
PSL.msg(p, PSL.RELOAD_COMPLETE.msg());
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 1,992 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminCleanup.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminCleanup.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
class ArgAdminCleanup {
private static File previewFile;
private static FileWriter previewFileOutputStream;
// /ps admin cleanup [remove/preview]
static boolean argumentAdminCleanup(CommandSender p, String[] preParseArgs) {
if (preParseArgs.length < 3 || !Arrays.asList("remove", "preview").contains(preParseArgs[2].toLowerCase())) {
PSL.msg(p, ArgAdmin.getCleanupHelp());
return true;
}
String cleanupOperation = preParseArgs[2].toLowerCase(); // [remove|preview]
World w;
String alias = null;
List<String> args = new ArrayList<>();
// determine if there is an alias flag selected, and remove [-t typealias] if there is
for (int i = 3; i < preParseArgs.length; i++) {
if (preParseArgs[i].equals("-t") && i != preParseArgs.length-1) {
alias = preParseArgs[++i];
} else {
args.add(preParseArgs[i]);
}
}
// the args array should consist of: [days, world (optional)]
if (args.size() > 1 && Bukkit.getWorld(args.get(1)) != null) {
w = Bukkit.getWorld(args.get(1));
} else {
if (p instanceof Player) {
w = ((Player) p).getWorld();
} else {
PSL.msg(p, args.size() > 1 ? PSL.INVALID_WORLD.msg() : PSL.ADMIN_CONSOLE_WORLD.msg());
return true;
}
}
// create preview file
if (cleanupOperation.equals("preview")) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd H-m-s");
previewFile = new File(ProtectionStones.getInstance().getDataFolder().getAbsolutePath() + "/" + LocalDateTime.now().format(formatter) + " cleanup preview.txt");
try {
previewFile.createNewFile();
previewFileOutputStream = new FileWriter(previewFile);
} catch (IOException e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Internal error, please check the console logs.");
return true;
}
}
RegionManager rgm = WGUtils.getRegionManagerWithWorld(w);
Map<String, ProtectedRegion> regions = rgm.getRegions();
// async cleanup task
String finalAlias = alias;
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
int days = (args.size() > 0) ? Integer.parseInt(args.get(0)) : 30; // 30 days is default if days aren't specified
PSL.msg(p, PSL.ADMIN_CLEANUP_HEADER.msg()
.replace("%arg%", cleanupOperation)
.replace("%days%", "" + days));
HashSet<UUID> activePlayers = new HashSet<>();
// loop over offline players and add to list if they haven't joined recently
for (OfflinePlayer op : Bukkit.getServer().getOfflinePlayers()) {
long lastPlayed = (System.currentTimeMillis() - op.getLastPlayed()) / 86400000L;
try {
// a player is active if they have joined within the days
if (lastPlayed < days) {
activePlayers.add(op.getUniqueId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
// loop over all regions async and find regions to delete
List<PSRegion> toDelete = new ArrayList<>();
for (String regionId : regions.keySet()) {
PSRegion r = PSRegion.fromWGRegion(w, regions.get(regionId));
if (r == null) { // not a ps region (unconfigured types still count as ps regions)
continue;
}
// if an alias is specified, skip regions that aren't of the type
if (finalAlias != null && (r.getTypeOptions() == null || !r.getTypeOptions().alias.equals(finalAlias))) {
continue;
}
long numOfActiveOwners = r.getOwners().stream().filter(activePlayers::contains).count();
long numOfActiveMembers = r.getMembers().stream().filter(activePlayers::contains).count();
// remove region if there are no owners left
if (numOfActiveOwners == 0) {
if (ProtectionStones.getInstance().getConfigOptions().cleanupDeleteRegionsWithMembersButNoOwners || numOfActiveMembers == 0) {
toDelete.add(r);
}
}
}
// start recursive iteration to delete a region each tick
Iterator<PSRegion> deleteRegionsIterator = toDelete.iterator();
regionLoop(deleteRegionsIterator, p, cleanupOperation.equalsIgnoreCase("remove"));
});
return true;
}
static private void regionLoop(Iterator<PSRegion> deleteRegionsIterator, CommandSender p, boolean isRemoveOperation) {
if (deleteRegionsIterator.hasNext()) {
Bukkit.getScheduler().runTaskLater(ProtectionStones.getInstance(), () ->
processRegion(deleteRegionsIterator, p, isRemoveOperation), 1);
} else { // finished region iteration
PSL.msg(p, PSL.ADMIN_CLEANUP_FOOTER.msg()
.replace("%arg%", isRemoveOperation ? "remove" : "preview"));
// flush and close preview file
if (!isRemoveOperation) {
try {
p.sendMessage(ChatColor.YELLOW + "Dumped the list regions that can be deleted in " + previewFile.getName() + " (in the plugin folder).");
previewFileOutputStream.flush();
previewFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Process a region, and then iterate to the next region on the next tick.
// This is to prevent the server from pausing for the entire duration of the cleanup.
// (lag from loading chunks to remove protection blocks)
static private void processRegion(Iterator<PSRegion> deleteRegionsIterator, CommandSender p, boolean isRemoveOperation) {
PSRegion r = deleteRegionsIterator.next();
if (isRemoveOperation) { // delete
p.sendMessage(ChatColor.YELLOW + "Removed region " + r.getId() + " due to inactive owners.");
// must be sync
r.deleteRegion(true);
} else { // preview
p.sendMessage(ChatColor.YELLOW + "Found region " + r.getId() + " that can be deleted.");
// adds region id to preview file
try {
previewFileOutputStream.write(r.getId() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
// go to next region
regionLoop(deleteRegionsIterator, p, isRemoveOperation);
}
}
| 8,290 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgSethome.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgSethome.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgSethome implements PSCommandArg {
// /ps sethome
@Override
public List<String> getNames() {
return Collections.singletonList("sethome");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.sethome");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
WorldGuardPlugin wg = WorldGuardPlugin.inst();
if (!p.hasPermission("protectionstones.sethome"))
return PSL.msg(p, PSL.NO_PERMISSION_SETHOME.msg());
if (r == null)
return PSL.msg(p, PSL.NOT_IN_REGION.msg());
if (WGUtils.hasNoAccess(r.getWGRegion(), p, wg.wrapPlayer(p), false))
return PSL.msg(p, PSL.NO_ACCESS.msg());
Location l = p.getLocation();
r.setHome(l.getBlockX(), l.getBlockY(), l.getBlockZ(), l.getYaw(), l.getPitch());
return PSL.msg(p, PSL.SETHOME_SET.msg().replace("%psid%", r.getName() != null ? String.format("%s (%s)", r.getName(), r.getId()) : r.getId()));
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 2,615 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminRecreate.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminRecreate.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.RemovalStrategy;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
class ArgAdminRecreate {
static boolean argumentAdminRecreate(CommandSender s, String[] args) {
s.sendMessage(ChatColor.YELLOW + "Recreating...");
HashMap<World, RegionManager> m = WGUtils.getAllRegionManagers();
for (World w : m.keySet()) {
RegionManager rgm = m.get(w);
List<ProtectedRegion> toAdd = new ArrayList<>();
for (ProtectedRegion r : rgm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r)) {
PSRegion wr = PSRegion.fromWGRegion(w, r);
if (wr instanceof PSGroupRegion) continue; // skip group regions for now TODO
PSProtectBlock blockOptions = wr.getTypeOptions();
if (blockOptions == null) {
Bukkit.getLogger().info("Region " + r.getId() + " in world " + w.getName() + " is not configured in the block config! Skipping...");
continue;
}
ProtectedRegion nr = WGUtils.getDefaultProtectedRegion(blockOptions, WGUtils.parsePSRegionToLocation(wr.getId()));
nr.copyFrom(r); // copy region data over
toAdd.add(nr);
}
}
for (ProtectedRegion r : toAdd) {
rgm.removeRegion(r.getId(), RemovalStrategy.UNSET_PARENT_IN_CHILDREN);
rgm.addRegion(r);
}
}
s.sendMessage(ChatColor.YELLOW + "Done.");
return true;
}
}
| 2,703 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminLastlogon.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminLastlogon.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.PSL;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
import java.util.Comparator;
class ArgAdminLastlogon {
// /ps admin lastlogon
static class PlayerComparator implements Comparator<OfflinePlayer> {
@Override
public int compare(OfflinePlayer o1, OfflinePlayer o2) {
return o1.getName().compareTo(o2.getName());
}
}
static boolean argumentAdminLastLogon(CommandSender p, String[] args) {
if (args.length < 3) {
p.sendMessage(PSL.COMMAND_REQUIRES_PLAYER_NAME.msg());
return true;
}
OfflinePlayer op = Bukkit.getOfflinePlayer(args[2]);
String playerName = args[2];
long lastPlayed = (System.currentTimeMillis() - op.getLastPlayed()) / 86400000L;
PSL.msg(p, PSL.ADMIN_LAST_LOGON.msg()
.replace("%player%", playerName)
.replace("%days%", "" +lastPlayed));
if (op.isBanned()) {
PSL.msg(p, PSL.ADMIN_IS_BANNED.msg()
.replace("%player%", playerName));
}
return true;
}
// /ps admin lastlogons
static boolean argumentAdminLastLogons(CommandSender p, String[] args) {
int days = 0;
if (args.length > 2) {
try {
days = Integer.parseInt(args[2]);
} catch (Exception e) {
PSL.msg(p, PSL.ADMIN_ERROR_PARSING.msg());
return true;
}
}
OfflinePlayer[] offlinePlayerList = Bukkit.getServer().getOfflinePlayers().clone();
int playerCounter = 0;
PSL.msg(p, PSL.ADMIN_LASTLOGONS_HEADER.msg()
.replace("%days%", "" + days));
Arrays.sort(offlinePlayerList, new PlayerComparator());
for (OfflinePlayer offlinePlayer : offlinePlayerList) {
long lastPlayed = (System.currentTimeMillis() - offlinePlayer.getLastPlayed()) / 86400000L;
if (lastPlayed >= days) {
playerCounter++;
PSL.msg(p, PSL.ADMIN_LASTLOGONS_LINE.msg()
.replace("%player%", offlinePlayer.getName())
.replace("%time%", "" + lastPlayed));
}
}
PSL.msg(p, PSL.ADMIN_LASTLOGONS_FOOTER.msg()
.replace("%count%", "" + playerCounter)
.replace("%checked%", "" + offlinePlayerList.length));
return true;
}
}
| 3,225 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAdminChangeblock.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAdminChangeblock.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import java.util.function.Consumer;
class ArgAdminChangeblock {
// /ps admin changeblock [world] [fromblockalias] [toblockalias]
static boolean argumentAdminChangeblock(CommandSender p, String[] args) {
if (args.length < 5) {
PSL.msg(p, ArgAdmin.getChangeBlockHelp());
return true;
}
String world = args[2], fromBlockAlias = args[3], toBlockAlias = args[4];
if (ProtectionStones.getProtectBlockFromAlias(fromBlockAlias) == null) {
PSL.msg(p, ChatColor.GRAY + "The type to change from is not a registered protection block!");
return true;
}
if (ProtectionStones.getProtectBlockFromAlias(toBlockAlias) == null) {
PSL.msg(p, ChatColor.GRAY + "The type to change to is not a registered protection block!");
return true;
}
String fromBlock = ProtectionStones.getProtectBlockFromAlias(fromBlockAlias).type,
toBlock = ProtectionStones.getProtectBlockFromAlias(toBlockAlias).type;
Consumer<PSRegion> convertFunction = (region) -> {
if (region.getType().equals(fromBlock)) {
p.sendMessage(ChatColor.GRAY + "Changing " + region.getId() + "...");
region.setType(ProtectionStones.getBlockOptions(toBlock));
}
};
World w = Bukkit.getWorld(world);
if (w == null) {
return PSL.msg(p, PSL.INVALID_WORLD.msg());
}
RegionManager rgm = WGUtils.getRegionManagerWithWorld(w);
if (rgm == null) {
return PSL.msg(p, ChatColor.GRAY + "The world does not have WorldGuard configured!");
}
for (ProtectedRegion r : rgm.getRegions().values()) {
if (ProtectionStones.isPSRegion(r)) {
PSRegion pr = PSRegion.fromWGRegion(w, r);
convertFunction.accept(pr);
if (pr instanceof PSGroupRegion) {
for (PSMergedRegion psmr : ((PSGroupRegion) pr).getMergedRegions()) {
convertFunction.accept(psmr);
}
}
}
}
p.sendMessage(ChatColor.GRAY + "Done!");
return true;
}
}
| 3,262 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgMerge.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgMerge.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.WGMerge;
import dev.espi.protectionstones.utils.WGUtils;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.stream.Collectors;
public class ArgMerge implements PSCommandArg {
@Override
public List<String> getNames() {
return Arrays.asList("merge");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.merge");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
public static List<TextComponent> getGUI(Player p, PSRegion r) {
return r.getMergeableRegions(p).stream()
.map(psr -> {
TextComponent tc = new TextComponent(ChatColor.AQUA + "> " + ChatColor.WHITE + psr.getId());
if (psr.getName() != null) tc.addExtra(" (" + psr.getName() + ")"); // name
tc.addExtra(" (" + psr.getTypeOptions().alias + ")"); // region type
tc.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " merge " + r.getId() + " " + psr.getId()));
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.MERGE_CLICK_TO_MERGE.msg().replace("%region%", psr.getId())).create()));
return tc;
})
.collect(Collectors.toList());
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.merge"))
return PSL.msg(s, PSL.NO_PERMISSION_MERGE.msg());
if (!ProtectionStones.getInstance().getConfigOptions().allowMergingRegions)
return PSL.msg(s, PSL.MERGE_DISABLED.msg());
Player p = (Player) s;
if (args.length == 1) { // GUI
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null)
return PSL.msg(s, PSL.NOT_IN_REGION.msg());
if (r.getTypeOptions() == null) {
PSL.msg(p, ChatColor.RED + "This region is problematic, and the block type (" + r.getType() + ") is not configured. Please contact an administrator.");
Bukkit.getLogger().info(ChatColor.RED + "This region is problematic, and the block type (" + r.getType() + ") is not configured.");
return true;
}
if (!r.getTypeOptions().allowMerging)
return PSL.msg(s, PSL.MERGE_NOT_ALLOWED.msg());
List<TextComponent> components = getGUI(p, r);
if (components.isEmpty()) {
PSL.msg(p, PSL.MERGE_NO_REGIONS.msg());
} else {
p.sendMessage(ChatColor.WHITE + ""); // send empty line
PSL.msg(p, PSL.MERGE_HEADER.msg().replace("%region%", r.getId()));
PSL.msg(p, PSL.MERGE_WARNING.msg());
for (TextComponent tc : components) p.spigot().sendMessage(tc);
p.sendMessage(ChatColor.WHITE + ""); // send empty line
}
} else if (args.length == 3) { // /ps merge [region] [root]
RegionManager rm = WGUtils.getRegionManagerWithPlayer(p);
ProtectedRegion region = rm.getRegion(args[1]), root = rm.getRegion(args[2]);
LocalPlayer lp = WorldGuardPlugin.inst().wrapPlayer(p);
if (!ProtectionStones.isPSRegion(region) || !ProtectionStones.isPSRegion(root))
return PSL.msg(p, PSL.MULTI_REGION_DOES_NOT_EXIST.msg());
if (!p.hasPermission("protectionstones.admin") && (!region.isOwner(lp) || !root.isOwner(lp)))
return PSL.msg(p, PSL.NO_ACCESS.msg());
// check if region is actually overlapping the region
var overlappingRegionIds = WGUtils.findOverlapOrAdjacentRegions(root, rm, p.getWorld()).stream().map(ProtectedRegion::getId).collect(Collectors.toList());
if (!overlappingRegionIds.contains(region.getId()))
return PSL.msg(p, PSL.REGION_NOT_OVERLAPPING.msg());
// check if merging is allowed in config
PSRegion aRegion = PSRegion.fromWGRegion(p.getWorld(), region), aRoot = PSRegion.fromWGRegion(p.getWorld(), root);
if (!aRegion.getTypeOptions().allowMerging || !aRoot.getTypeOptions().allowMerging)
return PSL.msg(p, PSL.MERGE_NOT_ALLOWED.msg());
// check if the region types allow for it
if (!WGUtils.canMergeRegionTypes(aRegion.getTypeOptions(), aRoot))
return PSL.msg(p, PSL.MERGE_NOT_ALLOWED.msg());
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
try {
WGMerge.mergeRealRegions(p.getWorld(), rm, aRoot, Arrays.asList(aRegion, aRoot));
} catch (WGMerge.RegionHoleException e) {
PSL.msg(p, PSL.NO_REGION_HOLES.msg());
return;
} catch (WGMerge.RegionCannotMergeWhileRentedException e) {
PSL.msg(p, PSL.CANNOT_MERGE_RENTED_REGION.msg().replace("%region%", e.getRentedRegion().getName() == null ? e.getRentedRegion().getId() : e.getRentedRegion().getName()));
return;
}
PSL.msg(p, PSL.MERGE_MERGED.msg());
// show menu again if the new region still has overlapping regions
Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), () -> {
if (!getGUI(p, PSRegion.fromWGRegion(p.getWorld(), rm.getRegion(aRoot.getId()))).isEmpty()) {
Bukkit.dispatchCommand(p, ProtectionStones.getInstance().getConfigOptions().base_command + " merge");
}
});
});
} else {
PSL.msg(s, PSL.MERGE_HELP.msg());
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 7,462 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgAddRemove.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgAddRemove.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.LimitUtil;
import dev.espi.protectionstones.utils.UUIDCache;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ArgAddRemove implements PSCommandArg {
@Override
public List<String> getNames() {
return Arrays.asList("add", "remove", "addowner", "removeowner");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.members", "protectionstones.owners");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
HashMap<String, Boolean> m = new HashMap<>();
m.put("-a", false);
return m;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
String operationType = args[0].toLowerCase(); // add, remove, addowner, removeowner
// check permission
if ((operationType.equals("add") || operationType.equals("remove")) && !p.hasPermission("protectionstones.members")) {
return PSL.msg(p, PSL.NO_PERMISSION_MEMBERS.msg());
} else if ((operationType.equals("addowner") || operationType.equals("removeowner")) && !p.hasPermission("protectionstones.owners")) {
return PSL.msg(p, PSL.NO_PERMISSION_OWNERS.msg());
}
// determine player to be added or removed
if (args.length < 2) {
return PSL.msg(p, PSL.COMMAND_REQUIRES_PLAYER_NAME.msg());
}
if (!UUIDCache.containsName(args[1])) {
return PSL.msg(p, PSL.PLAYER_NOT_FOUND.msg());
}
// user being added
UUID addPlayerUuid = UUIDCache.getUUIDFromName(args[1]);
String addPlayerName = UUIDCache.getNameFromUUID(addPlayerUuid);
// getting player regions is slow, so run it async
Bukkit.getServer().getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
List<PSRegion> regions;
// obtain region list that player is being added to or removed from
if (flags.containsKey("-a")) { // add or remove to all regions a player owns
// don't let players remove themself from all of their regions
if (operationType.equals("removeowner") && addPlayerUuid.equals(p.getUniqueId())) {
PSL.msg(p, PSL.CANNOT_REMOVE_YOURSELF_FROM_ALL_REGIONS.msg());
return;
}
regions = PSPlayer.fromPlayer(p).getPSRegions(p.getWorld(), false);
} else { // add or remove to one region (the region currently in)
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null) {
PSL.msg(p, PSL.NOT_IN_REGION.msg());
return;
} else if (WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), false)) {
PSL.msg(p, PSL.NO_ACCESS.msg());
return;
} else if (operationType.equals("removeowner") && addPlayerUuid.equals(p.getUniqueId()) && r.getOwners().size() == 1) {
// don't let users remove themself if they are the last owner of the region
PSL.msg(p, PSL.CANNOT_REMOVE_YOURSELF_LAST_OWNER.msg());
return;
}
regions = Collections.singletonList(r);
}
// check that the player is not over their limit if they are being set owner
if (operationType.equals("addowner")) {
if (determinePlayerSurpassedLimit(p, regions, PSPlayer.fromUUID(addPlayerUuid))) {
return;
}
}
// apply operation to regions
for (PSRegion r : regions) {
if (operationType.equals("add") || operationType.equals("addowner")) {
if (flags.containsKey("-a")) {
PSL.msg(p, PSL.ADDED_TO_REGION_SPECIFIC.msg()
.replace("%player%", addPlayerName)
.replace("%region%", r.getName() == null ? r.getId() : r.getName() + " (" + r.getId() + ")"));
} else {
PSL.msg(p, PSL.ADDED_TO_REGION.msg().replace("%player%", addPlayerName));
}
// add to WorldGuard profile cache
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> UUIDCache.storeWGProfile(addPlayerUuid, addPlayerName));
} else if ((operationType.equals("remove") && r.isMember(addPlayerUuid))
|| (operationType.equals("removeowner") && r.isOwner(addPlayerUuid))) {
if (flags.containsKey("-a")) {
PSL.msg(p, PSL.REMOVED_FROM_REGION_SPECIFIC.msg()
.replace("%player%", addPlayerName)
.replace("%region%", r.getName() == null ? r.getId() : r.getName() + " (" + r.getId() + ")"));
} else {
PSL.msg(p, PSL.REMOVED_FROM_REGION.msg().replace("%player%", addPlayerName));
}
}
switch (operationType) {
case "add" -> r.addMember(addPlayerUuid);
case "remove" -> r.removeMember(addPlayerUuid);
case "addowner" -> r.addOwner(addPlayerUuid);
case "removeowner" -> r.removeOwner(addPlayerUuid);
}
}
});
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (!(sender instanceof Player)) return null;
Player p = (Player) sender;
List<String> ret = new ArrayList<>();
if (args.length == 2) {
ret.add("-a");
}
try {
if (args.length == 2 || (args.length == 3 && args[1].equals("-a"))) {
switch (args[0].toLowerCase()) {
case "add":
case "addowner":
List<String> names = new ArrayList<>();
for (Player pAdd : Bukkit.getOnlinePlayers()) {
if (p.canSee(pAdd)) { // check if the player is not hidden
names.add(pAdd.getName());
}
}
ret.addAll(names);
break;
case "remove":
case "removeowner":
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r != null) {
names = new ArrayList<>();
for (UUID uuid : args[0].equalsIgnoreCase("remove") ? r.getMembers() : r.getOwners()) {
names.add(UUIDCache.getNameFromUUID(uuid));
}
ret.addAll(names);
}
break;
}
try {
return StringUtil.copyPartialMatches(args[args.length - 1], ret, new ArrayList<>());
} catch (IllegalArgumentException e) {
return null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean determinePlayerSurpassedLimit(Player commandSender, List<PSRegion> regionsToBeAddedTo, PSPlayer addedPlayer) {
if (addedPlayer.getPlayer() == null && !ProtectionStones.getInstance().isLuckPermsSupportEnabled()) { // offline player
if (ProtectionStones.getInstance().getConfigOptions().allowAddownerForOfflinePlayersWithoutLp) {
// bypass config option
return false;
} else {
// we need luckperms to determine region limits for offline players, so if luckperms isn't detected, prevent the action
PSL.msg(commandSender, PSL.ADDREMOVE_PLAYER_NEEDS_TO_BE_ONLINE.msg());
return true;
}
}
// find total region amounts after player is added to the regions, and their existing total
String err = LimitUtil.checkAddOwner(addedPlayer, regionsToBeAddedTo.stream()
.flatMap(r -> {
if (r instanceof PSGroupRegion) {
return ((PSGroupRegion) r).getMergedRegions().stream();
}
return Stream.of(r);
})
.map(PSRegion::getTypeOptions)
.filter(Objects::nonNull)
.collect(Collectors.toList()));
if (err.equals("")) {
return false;
} else {
PSL.msg(commandSender, err);
return true;
}
}
}
| 10,118 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgTax.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgTax.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.MiscUtil;
import dev.espi.protectionstones.utils.TextGUI;
import dev.espi.protectionstones.utils.UUIDCache;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.milkbowl.vault.economy.EconomyResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.*;
public class ArgTax implements PSCommandArg {
static final String INFO_HELP = ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps tax info [region (optional)]", // maybe put in /ps info
PAY_HELP = ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps tax pay [amount] [region (optional)]",
AUTOPAY_HELP = ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps tax autopay [region (optional)]";
@Override
public List<String> getNames() {
return Collections.singletonList("tax");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.tax");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
HashMap<String, Boolean> m = new HashMap<>();
m.put("-p", true);
return m;
}
private void runHelp(CommandSender s) {
PSL.msg(s, PSL.TAX_HELP_HEADER.msg());
PSL.msg(s, INFO_HELP);
PSL.msg(s, PAY_HELP);
PSL.msg(s, AUTOPAY_HELP);
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
if (!s.hasPermission("protectionstones.tax")) {
return PSL.msg(s, PSL.NO_PERMISSION_TAX.msg());
}
if (!ProtectionStones.getInstance().getConfigOptions().taxEnabled) {
return PSL.msg(s, ChatColor.RED + "Taxes are disabled! Enable it in the config.");
}
Player p = (Player) s;
PSPlayer psp = PSPlayer.fromPlayer(p);
if (args.length == 1 || args[1].equals("help")) {
runHelp(s);
return true;
}
switch (args[1]) {
case "info":
return taxInfo(args, flags, psp);
case "pay":
return taxPay(args, psp);
case "autopay":
return taxAutoPay(args, psp);
default:
runHelp(s);
break;
}
return true;
}
private static final int GUI_SIZE = 17;
public boolean taxInfo(String[] args, HashMap<String, String> flags, PSPlayer p) {
if (args.length == 2) { // /ps tax info
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
int pageNum = (flags.get("-p") == null || !MiscUtil.isValidInteger(flags.get("-p")) ? 0 : Integer.parseInt(flags.get("-p"))-1);
List<TextComponent> entries = new ArrayList<>();
for (PSRegion r : p.getTaxEligibleRegions()) {
double amountDue = 0;
for (PSRegion.TaxPayment tp : r.getTaxPaymentsDue()) {
amountDue += tp.getAmount();
}
TextComponent component;
if (r.getTaxAutopayer() != null & r.getTaxAutopayer() == p.getUuid()) {
component = new TextComponent(PSL.TAX_PLAYER_REGION_INFO_AUTOPAYER.msg()
.replace("%region%", (r.getName() == null ? r.getId() : r.getName() + " (" + r.getId() + ")"))
.replace("%money%", String.format("%.2f", amountDue)));
} else {
component = new TextComponent(PSL.TAX_PLAYER_REGION_INFO.msg()
.replace("%region%", (r.getName() == null ? r.getId() : r.getName() + " (" + r.getId() + ")"))
.replace("%money%", String.format("%.2f", amountDue)));
}
component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " tax info " + r.getId()));
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.TAX_CLICK_TO_SHOW_MORE_INFO.msg()).create()));
entries.add(component);
}
TextGUI.displayGUI(p.getPlayer(), PSL.TAX_INFO_HEADER.msg(), "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " tax info -p %page%", pageNum, GUI_SIZE, entries, true);
if (pageNum * GUI_SIZE + GUI_SIZE < entries.size())
PSL.msg(p, PSL.TAX_NEXT.msg().replace("%page%", pageNum + 2 + ""));
});
} else if (args.length == 3) { // /ps tax info [region]
List<PSRegion> list = ProtectionStones.getPSRegions(p.getPlayer().getWorld(), args[2]);
if (list.isEmpty()) {
return PSL.msg(p, PSL.REGION_DOES_NOT_EXIST.msg());
}
PSRegion r = list.get(0);
double taxesOwed = 0;
for (PSRegion.TaxPayment tp : r.getTaxPaymentsDue()) {
taxesOwed += tp.getAmount();
}
PSL.msg(p, PSL.TAX_REGION_INFO_HEADER.msg().replace("%region%", r.getName() == null ? r.getId() : r.getName() + " (" + r.getId() + ")"));
PSL.msg(p, PSL.TAX_REGION_INFO.msg()
.replace("%taxrate%", String.format("%.2f", r.getTaxRate()))
.replace("%taxperiod%", r.getTaxPeriod())
.replace("%taxpaymentperiod%", r.getTaxPaymentPeriod())
.replace("%taxautopayer%", r.getTaxAutopayer() == null ? "none" : UUIDCache.getNameFromUUID(r.getTaxAutopayer()))
.replace("%taxowed%", String.format("%.2f", taxesOwed)));
} else {
PSL.msg(p, INFO_HELP);
}
return true;
}
public boolean taxPay(String[] args, PSPlayer p) {
if (args.length != 3 && args.length != 4)
return PSL.msg(p, PAY_HELP);
// the amount to pay must be a number
if (!NumberUtils.isNumber(args[2]))
return PSL.msg(p, PAY_HELP);
PSRegion r = resolveRegion(args.length == 4 ? args[3] : null, p);
if (r == null) return true;
// player must be owner to pay for taxes
if (!r.isOwner(p.getUuid()))
return PSL.msg(p, PSL.NOT_OWNER.msg());
double payment = Double.parseDouble(args[2]);
// must be higher than or equal to zero
if (payment <= 0)
return PSL.msg(p, PAY_HELP);
// player must have this amount of money
if (!p.hasAmount(payment))
return PSL.msg(p, PSL.NOT_ENOUGH_MONEY.msg().replace("%price%", String.format("%.2f", payment)));
// pay tax amount
EconomyResponse res = r.payTax(p, payment);
PSL.msg(p, PSL.TAX_PAID.msg()
.replace("%amount%", String.format("%.2f", res.amount))
.replace("%region%", r.getName() == null ? r.getId() : r.getName() + "(" + r.getId() + ")"));
return true;
}
public boolean taxAutoPay(String[] args, PSPlayer p) {
if (args.length != 2 && args.length != 3)
return PSL.msg(p, AUTOPAY_HELP);
PSRegion r = resolveRegion(args.length == 3 ? args[2] : null, p);
if (r == null) return true;
// player must be the owner of the region
if (!r.isOwner(p.getUuid()))
return PSL.msg(p, PSL.NOT_OWNER.msg());
if (r.getTaxAutopayer() != null && r.getTaxAutopayer().equals(p.getUuid())) { // if removing the the tax autopayer
r.setTaxAutopayer(null);
PSL.msg(p, PSL.TAX_SET_NO_AUTOPAYER.msg().replace("%region%", r.getName() == null ? r.getId() : r.getName() + "(" + r.getId() + ")"));
} else { // if the player is setting themselves as the tax autopayer
r.setTaxAutopayer(p.getUuid());
PSL.msg(p, PSL.TAX_SET_AS_AUTOPAYER.msg().replace("%region%", r.getName() == null ? r.getId() : r.getName() + "(" + r.getId() + ")"));
}
return true;
}
public PSRegion resolveRegion(String region, PSPlayer p) {
PSRegion r;
if (region == null) { // region the player is standing in
r = PSRegion.fromLocationGroup(p.getPlayer().getLocation());
if (r == null) {
PSL.msg(p, PSL.NOT_IN_REGION.msg());
return null;
}
// if taxes are disabled for this region
if (r.getTypeOptions() == null || r.getTypeOptions().taxPeriod == -1) {
PSL.msg(p, PSL.TAX_DISABLED_REGION.msg());
return null;
}
} else { // region query
List<PSRegion> list = ProtectionStones.getPSRegions(p.getPlayer().getWorld(), region);
if (list.isEmpty()) {
PSL.msg(p, PSL.REGION_DOES_NOT_EXIST.msg());
return null;
} else {
r = list.get(0);
}
}
return r;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
if (args.length == 2) {
List<String> arg = Arrays.asList("info", "pay", "autopay");
return StringUtil.copyPartialMatches(args[1], arg, new ArrayList<>());
}
return null;
}
}
| 10,548 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgTp.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgTp.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.ChatUtil;
import dev.espi.protectionstones.utils.UUIDCache;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.util.*;
public class ArgTp implements PSCommandArg {
private static HashMap<UUID, Integer> waitCounter = new HashMap<>();
private static HashMap<UUID, BukkitTask> taskCounter = new HashMap<>();
// /ps tp, /ps home
@Override
public List<String> getNames() {
return Collections.singletonList("tp");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.tp");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
// preliminary checks
if (!p.hasPermission("protectionstones.tp"))
return PSL.msg(p, PSL.NO_PERMISSION_TP.msg());
if (args.length < 2 || args.length > 3)
return PSL.msg(p, PSL.TP_HELP.msg());
if (args.length == 2) { // /ps tp [name/id]
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
// get regions from the query
List<PSRegion> regions = ProtectionStones.getPSRegions(p.getWorld(), args[1]);
if (regions.isEmpty()) {
PSL.msg(s, PSL.REGION_DOES_NOT_EXIST.msg());
return;
}
if (regions.size() > 1) {
ChatUtil.displayDuplicateRegionAliases(p, regions);
return;
}
teleportPlayer(p, regions.get(0));
});
} else { // /ps tp [player] [num]
// get the region id the player wants to teleport to
int regionNumber;
try {
regionNumber = Integer.parseInt(args[2]);
if (regionNumber <= 0) {
return PSL.msg(p, PSL.NUMBER_ABOVE_ZERO.msg());
}
} catch (NumberFormatException e) {
return PSL.msg(p, PSL.TP_VALID_NUMBER.msg());
}
String tpName = args[1];
// region checks, and set lp to offline player
if (!UUIDCache.containsName(tpName)) {
return PSL.msg(p, PSL.PLAYER_NOT_FOUND.msg());
}
UUID tpUuid = UUIDCache.getUUIDFromName(tpName);
// run region search asynchronously to avoid blocking server thread
Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> {
List<PSRegion> regions = PSPlayer.fromUUID(tpUuid).getPSRegionsCrossWorld(p.getWorld(), false);
// check if region was found
if (regions.isEmpty()) {
PSL.msg(p, PSL.REGION_NOT_FOUND_FOR_PLAYER.msg()
.replace("%player%", tpName));
return;
} else if (regionNumber > regions.size()) {
PSL.msg(p, PSL.ONLY_HAS_REGIONS.msg()
.replace("%player%", tpName)
.replace("%num%", "" + regions.size()));
return;
}
teleportPlayer(p, regions.get(regionNumber - 1));
});
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
static void teleportPlayer(Player p, PSRegion r) {
if (r.getTypeOptions() == null) {
PSL.msg(p, ChatColor.RED + "This region is problematic, and the block type (" + r.getType() + ") is not configured. Please contact an administrator.");
Bukkit.getLogger().info(ChatColor.RED + "This region is problematic, and the block type (" + r.getType() + ") is not configured.");
return;
}
// teleport player
if (r.getTypeOptions().tpWaitingSeconds == 0 || p.hasPermission("protectionstones.tp.bypasswait")) {
// no teleport delay
PSL.msg(p, PSL.TPING.msg());
Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), () -> p.teleport(r.getHome())); // run on main thread, not async
} else if (!r.getTypeOptions().noMovingWhenTeleportWaiting) {
// teleport delay, but doesn't care about moving
p.sendMessage(PSL.TP_IN_SECONDS.msg().replace("%seconds%", "" + r.getTypeOptions().tpWaitingSeconds));
Bukkit.getScheduler().runTaskLater(ProtectionStones.getInstance(), () -> {
PSL.msg(p, PSL.TPING.msg());
p.teleport(r.getHome());
}, 20 * r.getTypeOptions().tpWaitingSeconds);
} else {// delay and not allowed to move
PSL.msg(p, PSL.TP_IN_SECONDS.msg().replace("%seconds%", "" + r.getTypeOptions().tpWaitingSeconds));
Location l = p.getLocation().clone();
UUID uuid = p.getUniqueId();
// remove queued teleport if already running
if (taskCounter.get(uuid) != null) removeUUIDTimer(uuid);
// add teleport wait tasks to queue
waitCounter.put(uuid, 0);
taskCounter.put(uuid, Bukkit.getScheduler().runTaskTimer(ProtectionStones.getInstance(), () -> {
Player pl = Bukkit.getPlayer(uuid);
// cancel if the player is not on the server
if (pl == null) {
removeUUIDTimer(uuid);
return;
}
if (waitCounter.get(uuid) == null) {
removeUUIDTimer(uuid);
return;
}
// increment seconds
waitCounter.put(uuid, waitCounter.get(uuid) + 1);
ProtectionStones.getInstance().debug(String.format("Checking player movement. Player location: (%.2f, %.2f, %.2f), actual location: (%.2f, %.2f, %.2f)", pl.getLocation().getX(), pl.getLocation().getY(), pl.getLocation().getZ(), l.getX(), l.getY(), l.getZ()));
// if the player moved cancel it
if (!inThreshold(l.getX(), pl.getLocation().getX()) || !inThreshold(l.getY(), pl.getLocation().getY()) || !inThreshold(l.getZ(), pl.getLocation().getZ())) {
ProtectionStones.getInstance().debug(String.format("Not in threshold. X check: %s, Y check: %s, Z check: %s", inThreshold(l.getX(), pl.getLocation().getX()), inThreshold(l.getY(), pl.getLocation().getY()), inThreshold(l.getZ(), pl.getLocation().getZ())));
PSL.msg(pl, PSL.TP_CANCELLED_MOVED.msg());
removeUUIDTimer(uuid);
} else if (waitCounter.get(uuid) == r.getTypeOptions().tpWaitingSeconds * 4) { // * 4 since this loops 4 times a second
// if the timer has passed, teleport and cancel
PSL.msg(pl, PSL.TPING.msg());
pl.teleport(r.getHome());
removeUUIDTimer(uuid);
}
}, 5, 5) // loop 4 times a second
);
}
}
private static boolean inThreshold(double location, double playerLoc) {
return playerLoc <= location + 1.0 && playerLoc >= location - 1.0;
}
private static void removeUUIDTimer(UUID uuid) {
if (taskCounter.get(uuid) != null) taskCounter.get(uuid).cancel();
waitCounter.remove(uuid);
taskCounter.remove(uuid);
}
}
| 8,798 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgPriority.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgPriority.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import dev.espi.protectionstones.PSL;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgPriority implements PSCommandArg {
@Override
public List<String> getNames() {
return Collections.singletonList("priority");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Arrays.asList("protectionstones.priority");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (!p.hasPermission("protectionstones.priority")) {
PSL.msg(p, PSL.NO_PERMISSION_PRIORITY.msg());
return true;
}
if (r == null) {
PSL.msg(p, PSL.NOT_IN_REGION.msg());
return true;
}
if (WGUtils.hasNoAccess(r.getWGRegion(), p, WorldGuardPlugin.inst().wrapPlayer(p), false)) {
PSL.msg(p, PSL.NO_ACCESS.msg());
return true;
}
if (args.length < 2) {
int priority = r.getWGRegion().getPriority();
PSL.msg(p, PSL.PRIORITY_INFO.msg().replace("%priority%", "" + priority));
return true;
}
try {
int priority = Integer.parseInt(args[1]);
r.getWGRegion().setPriority(priority);
PSL.msg(p, PSL.PRIORITY_SET.msg());
} catch (NumberFormatException e) {
PSL.msg(p, PSL.PRIORITY_ERROR.msg());
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
}
| 2,849 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ArgUnclaim.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/commands/ArgUnclaim.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.commands;
import dev.espi.protectionstones.*;
import dev.espi.protectionstones.utils.TextGUI;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ArgUnclaim implements PSCommandArg {
// /ps unclaim
@Override
public List<String> getNames() {
return Collections.singletonList("unclaim");
}
@Override
public boolean allowNonPlayersToExecute() {
return false;
}
@Override
public List<String> getPermissionsToExecute() {
return Collections.singletonList("protectionstones.unclaim");
}
@Override
public HashMap<String, Boolean> getRegisteredFlags() {
return null;
}
@Override
public boolean executeArgument(CommandSender s, String[] args, HashMap<String, String> flags) {
Player p = (Player) s;
if (!p.hasPermission("protectionstones.unclaim")) {
PSL.msg(p, PSL.NO_PERMISSION_UNCLAIM.msg());
return true;
}
if (args.length >= 2) { // /ps unclaim [list|region-id] (unclaim remote region)
if (!p.hasPermission("protectionstones.unclaim.remote")) {
PSL.msg(p, PSL.NO_PERMISSION_UNCLAIM_REMOTE.msg());
return true;
}
PSPlayer psp = PSPlayer.fromPlayer(p);
// list of regions that the player owns
List<PSRegion> regions = psp.getPSRegionsCrossWorld(psp.getPlayer().getWorld(), false);
if (args[1].equalsIgnoreCase("list")) {
displayPSRegions(s, regions, args.length == 2 ? 0 : tryParseInt(args[2]) - 1);
} else {
for (PSRegion psr : regions) {
if (psr.getId().equalsIgnoreCase(args[1])) {
// cannot break region being rented (prevents splitting merged regions, and breaking as tenant owner)
if (psr.getRentStage() == PSRegion.RentStage.RENTING && !p.hasPermission("protectionstones.superowner")) {
PSL.msg(p, PSL.RENT_CANNOT_BREAK_WHILE_RENTING.msg());
return false;
}
return unclaimBlock(psr, p);
}
}
PSL.msg(p, PSL.REGION_DOES_NOT_EXIST.msg());
}
return true;
} else { // /ps unclaim (no arguments, unclaim current region)
PSRegion r = PSRegion.fromLocationGroupUnsafe(p.getLocation()); // allow unclaiming unconfigured regions
if (r == null) {
PSL.msg(p, PSL.NOT_IN_REGION.msg());
return true;
}
if (!r.isOwner(p.getUniqueId()) && !p.hasPermission("protectionstones.superowner")) {
PSL.msg(p, PSL.NO_REGION_PERMISSION.msg());
return true;
}
// cannot break region being rented (prevents splitting merged regions, and breaking as tenant owner)
if (r.getRentStage() == PSRegion.RentStage.RENTING && !p.hasPermission("protectionstones.superowner")) {
PSL.msg(p, PSL.RENT_CANNOT_BREAK_WHILE_RENTING.msg());
return true;
}
return unclaimBlock(r, p);
}
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) {
return null;
}
private int tryParseInt(String arg) {
int i = 1;
try {
i = Integer.parseInt(arg);
} catch (NumberFormatException ignore) {
//ignore
}
return i;
}
private void displayPSRegions(CommandSender s, List<PSRegion> regions, int page) {
List<TextComponent> entries = new ArrayList<>();
for (PSRegion rs : regions) {
String msg;
if (rs.getName() == null) {
msg = ChatColor.GRAY + "> " + ChatColor.AQUA + rs.getId();
} else {
msg = ChatColor.GRAY + "> " + ChatColor.AQUA + rs.getName() + " (" + rs.getId() + ")";
}
TextComponent tc = new TextComponent(ChatColor.AQUA + " [-] " + msg);
tc.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Click to unclaim " + rs.getId()).create()));
tc.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " unclaim " + rs.getId()));
entries.add(tc);
}
TextGUI.displayGUI(s, PSL.UNCLAIM_HEADER.msg(), "/" + ProtectionStones.getInstance().getConfigOptions().base_command + " unclaim list %page%", page, 17, entries, true);
}
private boolean unclaimBlock(PSRegion r, Player p) {
PSProtectBlock cpb = r.getTypeOptions();
if (cpb != null && !cpb.noDrop) {
// return protection stone
List<ItemStack> items = new ArrayList<>();
if (r instanceof PSGroupRegion) {
for (PSRegion rp : ((PSGroupRegion) r).getMergedRegions()) {
if (rp.getTypeOptions() != null) items.add(rp.getTypeOptions().createItem());
}
} else {
items.add(cpb.createItem());
}
for (ItemStack item : items) {
if (!p.getInventory().addItem(item).isEmpty()) {
// method will return not empty if item couldn't be added
if (ProtectionStones.getInstance().getConfigOptions().dropItemWhenInventoryFull) {
PSL.msg(p, PSL.NO_ROOM_DROPPING_ON_FLOOR.msg());
p.getWorld().dropItem(p.getLocation(), item);
} else {
PSL.msg(p, PSL.NO_ROOM_IN_INVENTORY.msg());
return true;
}
}
}
}
// remove region
// check if removing the region and firing region remove event blocked it
if (!r.deleteRegion(true, p)) {
if (!ProtectionStones.getInstance().getConfigOptions().allowMergingHoles) { // side case if the removing creates a hole and those are prevented
PSL.msg(p, PSL.DELETE_REGION_PREVENTED_NO_HOLES.msg());
}
return true;
}
PSL.msg(p, PSL.NO_LONGER_PROTECTED.msg());
return true;
}
}
| 7,445 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
RegionPlaceholders.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/placeholders/RegionPlaceholders.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.placeholders;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.MiscUtil;
import dev.espi.protectionstones.utils.UUIDCache;
import dev.espi.protectionstones.utils.WGUtils;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class RegionPlaceholders {
public static String resolveSpecifiedRegionPlaceholders(Player p, String identifier) {
String[] spl = identifier.split("_");
if (spl.length > 2) {
String regionIdentifier = spl[1];
List<PSRegion> r;
if (p == null) {
r = new ArrayList<>();
WGUtils.getAllRegionManagers().forEach((w, rgm) -> r.addAll(ProtectionStones.getPSRegions(w, regionIdentifier)));
} else {
r = ProtectionStones.getPSRegions(p.getWorld(), regionIdentifier);
}
if (!r.isEmpty()) {
if (spl[2].equals("config")) {
return ConfigPlaceholders.resolveBlockConfig(r.get(0).getTypeOptions(), identifier.substring(("region_" + regionIdentifier + "_config_").length()));
} else {
return resolveRegionPlaceholders(p, r.get(0), identifier.substring(("region_" + regionIdentifier + "_").length()));
}
}
}
return "";
}
public static String resolveCurrentRegionPlaceholders(Player p, String identifier) {
if (p == null) return "";
PSRegion r = PSRegion.fromLocationGroup(p.getLocation());
if (r == null) return "";
if (identifier.startsWith("currentregion_config_")) { // config options for current region
return ConfigPlaceholders.resolveBlockConfig(r.getTypeOptions(), identifier.substring("currentregion_config_".length()));
} else { // current region placeholders
return resolveRegionPlaceholders(p, r, identifier.substring("currentregion_".length())); // cut out "currentregion_"
}
}
public static String resolveRegionPlaceholders(Player p, PSRegion r, String identifier) {
if (identifier.equals("owners")) {
return MiscUtil.concatWithoutLast(r.getOwners().stream().map(UUIDCache::getNameFromUUID).collect(Collectors.toList()), ", ");
} else if (identifier.equals("members")) {
return MiscUtil.concatWithoutLast(r.getMembers().stream().map(UUIDCache::getNameFromUUID).collect(Collectors.toList()), ", ");
} else if (identifier.equals("name")) {
return r.getName() == null ? r.getId() : r.getName();
} else if (identifier.equals("id")) {
return r.getId();
} else if (identifier.equals("type")) {
return r.getType();
} else if (identifier.equals("alias")) {
return r.getTypeOptions().alias;
} else if (identifier.equals("is_hidden")) {
return r.isHidden() + "";
} else if (identifier.equals("home_location")) {
return String.format("%.1f %.1f %.1f", r.getHome().getX(), r.getHome().getY(), r.getHome().getZ());
} else if (identifier.equals("is_for_sale")) {
return r.forSale() + "";
} else if (identifier.equals("rent_stage")) {
return r.getRentStage().toString().toLowerCase();
} else if (identifier.equals("landlord")) {
return r.getLandlord() == null ? "" : UUIDCache.getNameFromUUID(r.getLandlord());
} else if (identifier.equals("tenant")) {
return r.getTenant() == null ? "" : UUIDCache.getNameFromUUID(r.getTenant());
} else if (identifier.equals("rent_period")) {
return r.getRentPeriod();
} else if (identifier.equals("sale_price")) {
return r.getPrice() + "";
} else if (identifier.equals("rent_amount")) {
return r.getPrice() + "";
} else if (identifier.equals("tax_owed")) {
return String.format("%.2f", r.getTaxPaymentsDue().stream().mapToDouble(PSRegion.TaxPayment::getAmount).sum());
} else if (identifier.equals("tax_autopayer")) {
return r.getTaxAutopayer() == null ? "" : UUIDCache.getNameFromUUID(r.getTaxAutopayer());
} else if (identifier.equals("flags")) {
List<String> flags = new ArrayList<>();
for (Flag<?> f : r.getWGRegion().getFlags().keySet()) {
if (!r.getTypeOptions().hiddenFlagsFromInfo.contains(f.getName())) {
flags.add(f.getName() + " " + r.getWGRegion().getFlag(f) + "&r");
}
}
return MiscUtil.concatWithoutLast(flags, ", ");
} else if (identifier.startsWith("flags_")) {
String[] spl = identifier.split("_");
if (spl.length > 1) {
Flag<?> f = Flags.fuzzyMatchFlag(WGUtils.getFlagRegistry(), spl[1]);
if (r.getWGRegion().getFlag(f) != null) {
return r.getWGRegion().getFlag(f).toString();
}
}
}
return "";
}
}
| 5,901 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PlayerPlaceholders.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/placeholders/PlayerPlaceholders.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.placeholders;
import dev.espi.protectionstones.PSPlayer;
import dev.espi.protectionstones.PSProtectBlock;
import dev.espi.protectionstones.PSRegion;
import dev.espi.protectionstones.ProtectionStones;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class PlayerPlaceholders {
static String resolvePlayer(Player p, String identifier) {
if (p == null) return "";
PSPlayer psp = PSPlayer.fromPlayer(p);
if (identifier.equals("currentplayer_global_region_limit")) {
if (p.hasPermission("protectionstones.admin")) {
return "-1";
} else {
return psp.getGlobalRegionLimits() + "";
}
} else if (identifier.startsWith("currentplayer_region_limit_")) {
String alias = identifier.substring("currentplayer_region_limit_".length());
List<Map.Entry<PSProtectBlock, Integer>> l = psp.getRegionLimits()
.entrySet()
.stream()
.filter(e -> e.getKey().alias.equals(alias))
.collect(Collectors.toList());
if (p.hasPermission("protectionstones.admin")) {
return "-1";
}
if (!l.isEmpty()) {
return l.get(0).getValue() + "";
} else {
return psp.getGlobalRegionLimits() + "";
}
} else if (identifier.startsWith("currentplayer_total_tax_owed")) {
double amount = 0;
for (PSRegion psr : psp.getTaxEligibleRegions()) {
for (PSRegion.TaxPayment tp : psr.getTaxPaymentsDue()) {
amount += tp.getAmount();
}
}
return String.format("%.2f", amount);
} else if (identifier.startsWith("currentplayer_num_of_accessible_regions_")) {
String world = identifier.substring("currentplayer_num_of_accessible_regions_".length());
World w = Bukkit.getWorld(world);
return w == null ? "Invalid world." : "" + psp.getPSRegions(w, true).size();
} else if (identifier.startsWith("currentplayer_num_of_accessible_regions")) {
return "" + Bukkit.getWorlds().stream().mapToInt(w -> psp.getPSRegions(w, true).size()).sum();
} else if (identifier.startsWith("currentplayer_num_of_owned_regions_")) {
String world = identifier.substring("currentplayer_num_of_owned_regions_".length());
World w = Bukkit.getWorld(world);
return w == null ? "Invalid world." : "" + psp.getPSRegions(w, false).size();
} else if (identifier.startsWith("currentplayer_num_of_owned_regions")) {
return "" + Bukkit.getWorlds().stream().mapToInt(w -> psp.getPSRegions(w, false).size()).sum();
} else if (identifier.startsWith("currentplayer_owned_regions_ids_")) {
World w = Bukkit.getWorld(identifier.substring("currentplayer_owned_regions_ids_".length()));
return w == null ? "Invalid world." : getRegionsString(psp.getPSRegions(w, false), false);
} else if (identifier.startsWith("currentplayer_accessible_regions_ids_")) {
World w = Bukkit.getWorld(identifier.substring("currentplayer_accessible_regions_ids_".length()));
return w == null ? "Invalid world." : getRegionsString(psp.getPSRegions(w, true), false);
} else if (identifier.startsWith("currentplayer_owned_regions_names_")) {
World w = Bukkit.getWorld(identifier.substring("currentplayer_owned_regions_names_".length()));
return w == null ? "Invalid world." : getRegionsString(psp.getPSRegions(w, false), true);
} else if (identifier.startsWith("currentplayer_accessible_regions_names_")) {
World w = Bukkit.getWorld(identifier.substring("currentplayer_accessible_regions_names_".length()));
return w == null ? "Invalid world." : getRegionsString(psp.getPSRegions(w, true), true);
} else if (identifier.startsWith("currentplayer_protection_placing_enabled")) {
return ProtectionStones.toggleList.contains(p.getUniqueId()) + "";
}
return "";
}
private static String getRegionsString(List<PSRegion> regions, boolean useNamesIfPossible) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < regions.size(); i++) {
if (useNamesIfPossible && regions.get(i).getName() != null) {
sb.append(regions.get(i).getName());
} else {
sb.append(regions.get(i).getId());
}
if (i < regions.size() - 1) {
sb.append(", ");
}
}
return sb.toString();
}
}
| 5,505 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ConfigPlaceholders.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/placeholders/ConfigPlaceholders.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.placeholders;
import dev.espi.protectionstones.PSConfig;
import dev.espi.protectionstones.PSProtectBlock;
import dev.espi.protectionstones.ProtectionStones;
import dev.espi.protectionstones.utils.MiscUtil;
import java.time.Duration;
import java.util.List;
class ConfigPlaceholders {
private static PSConfig getConf() {
return ProtectionStones.getInstance().getConfigOptions();
}
static String resolveConfig(String identifier) {
String[] spl = identifier.split("_");
if (spl.length > 1) {
if (spl[1].equals("block")) { // config_block_[alias]_...
if (spl.length > 3 && ProtectionStones.getProtectBlockFromAlias(spl[2]) != null) {
StringBuilder sb = new StringBuilder();
for (int i = 3; i < spl.length; i++)
sb.append(spl[i]).append(i == spl.length-1 ? "" : "_");
return resolveBlockConfig(ProtectionStones.getProtectBlockFromAlias(spl[2]), sb.toString());
}
} else { // config_...
return resolveGlobalConfig(identifier);
}
}
return "";
}
private static String resolveGlobalConfig(String identifier) {
StringBuilder sb = new StringBuilder();
switch (identifier) {
case "config_config_version":
return getConf().configVersion + "";
case "config_uuidupdated":
return getConf().uuidupdated + "";
case "config_region_negative_min_max_updated":
return getConf().regionNegativeMinMaxUpdated + "";
case "config_placing_cooldown":
return getConf().placingCooldown + "";
case "config_async_load_uuid_cache":
return getConf().asyncLoadUUIDCache + "";
case "config_allow_duplicate_region_names":
return getConf().allowDuplicateRegionNames + "";
case "config_ps_view_cooldown":
return getConf().psViewCooldown + "";
case "config_ps_base_command":
return getConf().base_command;
case "config_aliases": // comma separated list
for (int i = 0; i < getConf().aliases.size(); i++) {
sb.append(getConf().aliases.get(i)).append(i == getConf().aliases.size()-1 ? "" : ", ");
}
return sb.toString();
case "config_drop_item_when_inventory_full":
return getConf().dropItemWhenInventoryFull + "";
case "config_regions_must_be_adjacent":
return getConf().regionsMustBeAdjacent + "";
case "config_allow_merging_regions":
return getConf().allowMergingRegions + "";
case "config_allow_merging_holes":
return getConf().allowMergingHoles + "";
case "default_protection_block_placement_off":
return getConf().defaultProtectionBlockPlacementOff + "";
case "allow_addowner_for_offline_players_without_lp":
return getConf().allowAddownerForOfflinePlayersWithoutLp + "";
case "allow_home_teleport_for_members":
return getConf().allowHomeTeleportForMembers + "";
case "admin_cleanup_delete_regions_with_members_but_no_owners":
return getConf().cleanupDeleteRegionsWithMembersButNoOwners + "";
case "config_economy_max_rent_price":
return String.format("%.2f", getConf().maxRentPrice);
case "config_economy_min_rent_price":
return String.format("%.2f", getConf().minRentPrice);
case "config_economy_max_rent_period":
return getConf().maxRentPeriod + "";
case "config_economy_max_rent_period_pretty":
return MiscUtil.describeDuration(Duration.ofSeconds(getConf().maxRentPeriod));
case "config_economy_min_rent_period":
return getConf().minRentPeriod + "";
case "config_economy_min_rent_period_pretty":
return MiscUtil.describeDuration(Duration.ofSeconds(getConf().minRentPeriod));
case "config_economy_tax_enabled":
return getConf().taxEnabled + "";
case "config_economy_tax_message_on_join":
return getConf().taxMessageOnJoin + "";
}
return "";
}
static String resolveBlockConfig(PSProtectBlock b, String identifier) {
StringBuilder sb = new StringBuilder();
switch (identifier) {
case "type":
return b.type;
case "alias":
return b.alias;
case "description":
return b.description;
case "restrict_obtaining":
return b.restrictObtaining + "";
case "world_list_type":
return b.worldListType;
case "worlds": // comma separated list
return MiscUtil.concatWithoutLast(b.worlds, " ");
case "prevent_block_place_in_restricted_world":
return b.preventBlockPlaceInRestrictedWorld + "";
case "allow_placing_in_wild":
return b.allowPlacingInWild + "";
case "placing_bypasses_wg_passthrough":
return b.placingBypassesWGPassthrough + "";
case "region_distance_between_claims":
return b.distanceBetweenClaims + "";
case "region_x_radius":
return b.xRadius + "";
case "region_y_radius":
return b.yRadius + "";
case "region_z_radius":
return b.zRadius + "";
case "region_chunk_radius":
return b.chunkRadius + "";
case "region_home_x_offset":
return b.homeXOffset + "";
case "region_home_y_offset":
return b.homeYOffset + "";
case "region_home_z_offset":
return b.homeZOffset + "";
case "region_flags": // comma separated list
return MiscUtil.concatWithoutLast(b.flags, ", ");
case "region_allowed_flags": // comma separated list
return MiscUtil.concatWithoutLast(b.allowedFlagsRaw, ", ");
case "region_hidden_flags_from_info": // comma separated list
return MiscUtil.concatWithoutLast(b.hiddenFlagsFromInfo, ", ");
case "region_priority":
return b.priority + "";
case "region_allow_overlap_unowned_regions":
return b.allowOverlapUnownedRegions + "";
case "region_allow_other_regions_to_overlap":
return b.allowOtherRegionsToOverlap;
case "region_allow_merging":
return b.allowMerging + "";
case "region_allowed_merging_into_types":
return MiscUtil.concatWithoutLast(b.allowedMergingIntoTypes, ", ");
case "block_data_display_name":
return b.displayName;
case "block_data_lore": // \n separated list
for (int i = 0; i < b.lore.size(); i++) {
sb.append(b.lore.get(i)).append("\n");
}
return sb.toString();
case "block_data_enchanted_effect":
return b.enchantedEffect + "";
case "block_data_price":
return String.format("%.2f", b.price);
case "block_data_allow_craft_with_custom_recipe":
return b.allowCraftWithCustomRecipe + "";
case "block_data_custom_recipe":
for (List<String> l : b.customRecipe) {
for (String s : l) {
sb.append(s).append(" ");
}
sb.append("\n");
}
return sb.toString();
case "block_data_recipe_amount":
return b.recipeAmount + "";
case "block_data_custom_model_data":
return b.customModelData + "";
case "economy_tax_amount":
return String.format("%.2f", b.taxAmount);
case "economy_tax_period":
return b.taxPeriod + "";
case "economy_tax_period_pretty":
return MiscUtil.describeDuration(Duration.ofSeconds(b.taxPeriod));
case "economy_tax_payment_time":
return b.taxPaymentTime + "";
case "economy_tax_payment_time_pretty":
return MiscUtil.describeDuration(Duration.ofSeconds(b.taxPaymentTime));
case "economy_start_with_tax_autopay":
return b.startWithTaxAutopay + "";
case "economy_tenant_rent_role":
return b.tenantRentRole;
case "economy_landlord_still_owner":
return b.landlordStillOwner + "";
case "behaviour_auto_hide":
return b.autoHide + "";
case "behaviour_auto_merge":
return b.autoMerge + "";
case "behaviour_no_drop":
return b.noDrop + "";
case "behaviour_prevent_piston_push":
return b.preventPistonPush + "";
case "behaviour_prevent_explode":
return b.preventExplode + "";
case "behaviour_destroy_region_when_explode":
return b.destroyRegionWhenExplode + "";
case "behaviour_prevent_silk_touch":
return b.preventSilkTouch + "";
case "behaviour_cost_to_place":
return String.format("%.2f", b.costToPlace);
case "behaviour_allow_smelt_item":
return b.allowSmeltItem + "";
case "behaviour_allow_use_in_crafting":
return b.allowUseInCrafting + "";
case "player_allow_shift_right_break":
return b.allowShiftRightBreak + "";
case "player_prevent_teleport_in":
return b.preventTeleportIn + "";
case "player_no_moving_when_tp_waiting":
return b.noMovingWhenTeleportWaiting + "";
case "player_tp_waiting_seconds":
return b.tpWaitingSeconds + "";
case "player_prevent_ps_get":
return b.preventPsGet + "";
case "player_prevent_ps_home":
return b.preventPsHome + "";
case "player_permission":
return b.permission;
case "event_enable":
return b.eventsEnabled + "";
case "event_on_region_create":
return MiscUtil.concatWithoutLast(b.regionCreateCommands, ", ");
case "event_on_region_destroy":
return MiscUtil.concatWithoutLast(b.regionDestroyCommands, ", ");
}
return "";
}
}
| 11,550 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PSPlaceholderExpansion.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/placeholders/PSPlaceholderExpansion.java | /*
* Copyright 2019 ProtectionStones team and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package dev.espi.protectionstones.placeholders;
import dev.espi.protectionstones.ProtectionStones;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
public class PSPlaceholderExpansion extends PlaceholderExpansion {
// persist through reloads
@Override
public boolean persist() {
return true;
}
@Override
public boolean canRegister(){
return true;
}
@Override
public String getIdentifier() {
return "protectionstones";
}
@Override
public String getAuthor() {
return ProtectionStones.getInstance().getDescription().getAuthors().toString();
}
@Override
public String getVersion() {
return ProtectionStones.getInstance().getDescription().getVersion();
}
@Override
public String onPlaceholderRequest(Player p, String identifier) {
String[] split = identifier.split("_");
if (split.length > 0) {
switch (split[0]) {
case "config":
return ConfigPlaceholders.resolveConfig(identifier);
case "currentregion":
return RegionPlaceholders.resolveCurrentRegionPlaceholders(p, identifier);
case "region":
return RegionPlaceholders.resolveSpecifiedRegionPlaceholders(p, identifier);
case "currentplayer":
return PlayerPlaceholders.resolvePlayer(p, identifier);
}
}
return "";
}
}
| 2,160 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PSObtainRegion.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/event/PSObtainRegion.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.event;
public class PSObtainRegion {
}
| 729 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PSLoseRegion.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/event/PSLoseRegion.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.event;
public class PSLoseRegion {
}
| 727 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PSCreateEvent.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/event/PSCreateEvent.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.event;
import dev.espi.protectionstones.PSRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Event that is called when a protectionstones region is created, either by a player, or by the plugin.
*/
public class PSCreateEvent extends Event implements Cancellable {
private static final HandlerList HANDLERS = new HandlerList();
private PSRegion region;
private Player p = null;
private boolean isCancelled = false;
public PSCreateEvent(PSRegion psr, Player player) {
this.region = checkNotNull(psr);
this.p = player;
}
public PSCreateEvent(PSRegion psr) {
this.region = checkNotNull(psr);
}
/**
* Returns the player that created the protection region, if applicable
* @return the player, or null if the region was not created because of a player
*/
public Player getPlayer() {
return p;
}
/**
* Returns the region being created.
* @return the region being created
*/
public PSRegion getRegion() {
return region;
}
@Override
public boolean isCancelled() {
return isCancelled;
}
@Override
public void setCancelled(boolean isCancelled) {
this.isCancelled = isCancelled;
}
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
}
| 2,270 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
PSRemoveEvent.java | /FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/event/PSRemoveEvent.java | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package dev.espi.protectionstones.event;
import dev.espi.protectionstones.PSRegion;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Event that is called when a protection stones region is removed
*/
public class PSRemoveEvent extends Event implements Cancellable {
private static final HandlerList HANDLERS = new HandlerList();
private PSRegion region;
private Player p = null;
private boolean isCancelled = false;
public PSRemoveEvent(PSRegion psr, Player player) {
this.region = checkNotNull(psr);
this.p = player;
}
public PSRemoveEvent(PSRegion psr) {
this.region = checkNotNull(psr);
}
/**
* Returns the player that removed the protect block, if applicable
* @return the player, or null if the region was not removed because of a player
*/
public Player getPlayer() {
return p;
}
/**
* Returns the region being removed.
* @return the region being removed
*/
public PSRegion getRegion() {
return region;
}
@Override
public boolean isCancelled() {
return isCancelled;
}
@Override
public void setCancelled(boolean isCancelled) {
this.isCancelled = isCancelled;
}
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
}
| 2,228 | Java | .java | espidev/ProtectionStones | 64 | 30 | 90 | 2018-09-17T22:12:12Z | 2023-11-13T03:14:47Z |
ZombieEscape.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/ZombieEscape.java | package net.cosmosmc.mcze;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Getter;
import net.cosmosmc.mcze.api.Api;
import net.cosmosmc.mcze.api.ZEApi;
import net.cosmosmc.mcze.commands.Game;
import net.cosmosmc.mcze.commands.SetLobbySpawn;
import net.cosmosmc.mcze.commands.Ztele;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.listeners.*;
import net.cosmosmc.mcze.menus.HumanKitMenu;
import net.cosmosmc.mcze.menus.VoteMenu;
import net.cosmosmc.mcze.menus.ZombieKitMenu;
import net.cosmosmc.mcze.profiles.Profile;
import net.cosmosmc.mcze.utils.Configuration;
import net.cosmosmc.mcze.utils.Utils;
import net.cosmosmc.mcze.utils.menus.MenuManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* NOTE TO CONTRIBUTORS:
* Alpha versions of Zombie Escape WILL print out debug information
* regardless. Please do not remove these until we are out of ALPHA.
*/
@Getter
public class ZombieEscape extends JavaPlugin {
private static Api api;
private Location serverSpawn;
private GameArena gameArena;
private MenuManager menuManager;
private Configuration configuration;
private HikariDataSource hikari = new HikariDataSource();
private Map<UUID, Profile> profiles = new HashMap<>();
@Override
public void onEnable() {
configuration = new Configuration(this);
configuration.setupHikari(hikari, configuration.getSettingsConfig());
gameArena = new GameArena(this);
menuManager = new MenuManager(this);
serverSpawn = configuration.getSpawn();
Bukkit.setSpawnRadius(0);
World world = Bukkit.getWorlds().get(0);
world.setSpawnFlags(false, false);
world.setGameRuleValue("doMobSpawning", "false");
for (Entity entity : world.getEntities()) {
if (!(entity instanceof Player) && entity instanceof LivingEntity) {
entity.remove();
}
}
registerListeners();
getCommand("game").setExecutor(new Game());
getCommand("setlobbyspawn").setExecutor(new SetLobbySpawn(this));
getCommand("ztele").setExecutor(new Ztele(this));
menuManager.addMenu("hkits", new HumanKitMenu("Human Kit Menu", 9, this));
menuManager.addMenu("zkits", new ZombieKitMenu("Zombie Kit Menu", 9, this));
menuManager.addMenu("vote", new VoteMenu(Utils.color("&8Vote"), 9, gameArena));
}
@Override
public void onDisable() {
if (hikari != null) {
hikari.close();
}
// TODO: Cleanup open files/instances/etc
}
public static Api getApi() {
if (api == null) {
api = new ZEApi();
}
return api;
}
private void registerListeners() {
PluginManager pm = Bukkit.getPluginManager();
pm.registerEvents(new EntityDamageByEntity(this), this);
pm.registerEvents(new PlayerDeath(this), this);
pm.registerEvents(new PlayerInteract(this), this);
pm.registerEvents(new PlayerJoin(this), this);
pm.registerEvents(new PlayerPickupItem(), this);
pm.registerEvents(new PlayerQuit(this), this);
pm.registerEvents(new ServerListener(this), this);
}
public Profile getProfile(Player player) {
return profiles.get(player.getUniqueId());
}
public Profile getRemovedProfile(Player player) {
return profiles.remove(player.getUniqueId());
}
} | 3,731 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Cooldowns.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/Cooldowns.java | package net.cosmosmc.mcze.utils;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.bukkit.entity.Player;
public class Cooldowns {
private static Table<String, String, Long> cooldowns = HashBasedTable.create();
/**
* Retrieve the number of milliseconds left until a given cooldown expires.
* <p>
* Check for a negative value to determine if a given cooldown has expired. <br>
* Cooldowns that have never been defined will return {@link Long#MIN_VALUE}.
* @param player - the player.
* @param key - cooldown to locate.
* @return Number of milliseconds until the cooldown expires.
*/
public static long getCooldown(Player player, String key) {
return calculateRemainder(cooldowns.get(player.getName(), key));
}
/**
* Update a cooldown for the specified player.
* @param player - the player.
* @param key - cooldown to update.
* @param delay - number of milliseconds until the cooldown will expire again.
* @return The previous number of milliseconds until expiration.
*/
public static long setCooldown(Player player, String key, long delay) {
return calculateRemainder(
cooldowns.put(player.getName(), key, System.currentTimeMillis() + delay));
}
/**
* Determine if a given cooldown has expired. If it has, refresh the cooldown. If not, do nothing.
* @param player - the player.
* @param key - cooldown to update.
* @param delay - number of milliseconds until the cooldown will expire again.
* @return TRUE if the cooldown was expired/unset and has now been reset, FALSE otherwise.
*/
public static boolean tryCooldown(Player player, String key, long delay) {
if (getCooldown(player, key) <= 0) {
setCooldown(player, key, delay);
return true;
}
return false;
}
/**
* Remove any cooldowns associated with the given player.
* @param player - the player we will reset.
*/
public static void removeCooldowns(Player player) {
cooldowns.row(player.getName()).clear();
}
private static long calculateRemainder(Long expireTime) {
return expireTime != null ? expireTime - System.currentTimeMillis() : Long.MIN_VALUE;
}
} | 2,338 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
GameFile.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/GameFile.java | package net.cosmosmc.mcze.utils;
import lombok.Getter;
import net.cosmosmc.mcze.core.data.Checkpoint;
import net.cosmosmc.mcze.core.data.Door;
import net.cosmosmc.mcze.core.data.Section;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GameFile {
private File flatFile;
@Getter
private FileConfiguration config;
public GameFile(String path, String name) {
flatFile = new File(path, name);
if (!flatFile.exists()) {
try {
FileWriter writer = new FileWriter(flatFile);
writer.write("ArenaName: " + name.split(".yml")[0]);
writer.close();
} catch (IOException e) {
// Ignore
}
}
config = new YamlConfiguration();
try {
config.load(flatFile);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
public void saveFile() {
try {
config.save(flatFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public String serializeLocation(Location location) {
return location.getX() + " " + location.getY() + " " + location.getZ() + " " + location.getYaw() + " " + location.getPitch();
}
public Location deserializeLocation(World world, String input) {
String[] parts = input.split(" ");
return new Location(world, Double.valueOf(parts[0]), Double.valueOf(parts[1]),
Double.valueOf(parts[2]), Float.valueOf(parts[3]), Float.valueOf(parts[4]));
}
public ArrayList<Door> getDoors(World world) {
ArrayList<Door> doors = new ArrayList<>();
for (String key : config.getConfigurationSection("Doors").getKeys(false)) {
if (key.equals("Amount")) {
continue; // Skip, this is just to keep track
}
Door door = new Door();
door.setId(Integer.parseInt(key));
door.setLocation(getLocation(world, "Doors." + key + ".Location"));
door.setSeconds(config.getInt("Doors." + key + ".Timer"));
Location edge1 = locationFromConfig(world, "Doors." + key + ".Edge1");
Location edge2 = locationFromConfig(world, "Doors." + key + ".Edge2");
Section section = new Section(edge1, edge2);
door.setSection(section);
door.setNukeroom(config.getBoolean("Doors." + key + ".Nukeroom"));
doors.add(door);
}
return doors;
}
public ArrayList<Checkpoint> getCheckpoints(World world) {
ArrayList<Checkpoint> checkpoints = new ArrayList<>();
for (String key : config.getConfigurationSection("Checkpoints").getKeys(false)) {
if (key.equals("Amount")) {
continue; // Skip, this is just to keep track
}
Checkpoint checkpoint = new Checkpoint();
checkpoint.setId(Integer.parseInt(key));
checkpoint.setLocation(locationFromConfig(world, "Checkpoints." + key + ".Location"));
checkpoints.add(checkpoint);
}
return checkpoints;
}
private Location locationFromConfig(World world, String path) {
String[] parts = config.getString(path).split(" ");
int x = (int) Double.parseDouble(parts[0]);
int y = (int) Double.parseDouble(parts[1]);
int z = (int) Double.parseDouble(parts[2]);
float yaw = (float) Double.parseDouble(parts[3]);
float pitch = (float) Double.parseDouble(parts[4]);
return new Location(world, x + 0.5, y + 0.5, z + 0.5, yaw, pitch);
}
public Location getLocation(World world, String path) {
world = world == null ? Bukkit.getWorld(path + ".World") : world;
return locationFromConfig(world, path);
}
public ArrayList<Location> getLocations(World world, String path) {
ArrayList<Location> spawns = new ArrayList<>();
world = world == null ? Bukkit.getWorld(path + ".World") : world;
for (String set : config.getConfigurationSection(path).getKeys(false)) {
if (!set.equals("Amount")) {
spawns.add(locationFromConfig(world, path + "." + set + ".Location"));
}
}
spawns.trimToSize(); // Trim any unnecessary array values
return spawns;
}
public int createListLocation(Player p, Location location, String path) {
int next = config.getInt(path + ".Amount") + 1;
location = location == null ? p.getLocation() : location;
config.set(path + ".Amount", next);
config.set(path + "." + next + ".Location", serializeLocation(location));
saveFile();
return next;
}
public void createLocation(Player p, Location location, String path) {
location = location == null ? p.getLocation() : location;
config.set(path, serializeLocation(location));
saveFile();
}
} | 5,320 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Configuration.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/Configuration.java | package net.cosmosmc.mcze.utils;
import com.zaxxer.hikari.HikariDataSource;
import net.cosmosmc.mcze.ZombieEscape;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import sun.dc.pr.PRError;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Configuration {
private final File SETTINGS_FILE;
private final YamlConfiguration SETTINGS_CONFIG;
public Configuration(ZombieEscape instance) {
this.SETTINGS_FILE = new File(instance.getDataFolder(), "Settings.yml");
this.SETTINGS_CONFIG = YamlConfiguration.loadConfiguration(SETTINGS_FILE);
if (!SETTINGS_CONFIG.isConfigurationSection("Database")) {
SETTINGS_CONFIG.set("Database.Address", "localhost:3306");
SETTINGS_CONFIG.set("Database.Schema", "example");
SETTINGS_CONFIG.set("Database.Username", "root");
SETTINGS_CONFIG.set("Database.Password", "root");
saveSettingsConfig();
}
}
public YamlConfiguration getSettingsConfig() {
return SETTINGS_CONFIG;
}
public void saveSettingsConfig() {
try {
SETTINGS_CONFIG.save(SETTINGS_FILE);
} catch (IOException e) {
e.printStackTrace();
}
}
public void setSpawn(Player player) {
SETTINGS_CONFIG.set("Spawn", serializeLocation(player.getLocation()));
}
public Location getSpawn() {
String[] parts = SETTINGS_CONFIG.getString("Spawn").split(" ");
return new Location(Bukkit.getWorlds().get(0), Double.valueOf(parts[0]), Double.valueOf(parts[1]),
Double.valueOf(parts[2]), Float.valueOf(parts[3]), Float.valueOf(parts[4]));
}
public String serializeLocation(Location location) {
return location.getX() + " " + location.getY() + " " + location.getZ() + " " + location.getYaw() + " " + location.getPitch();
}
public void setupHikari(HikariDataSource hikari, FileConfiguration settings) {
String address = settings.getString("Database.Address");
String database = settings.getString("Database.Schema");
String username = settings.getString("Database.Username");
String password = settings.getString("Database.Password");
hikari.setMaximumPoolSize(10);
hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikari.addDataSourceProperty("serverName", address.split(":")[0]);
hikari.addDataSourceProperty("port", address.split(":")[1]);
hikari.addDataSourceProperty("databaseName", database);
hikari.addDataSourceProperty("user", username);
hikari.addDataSourceProperty("password", password);
Connection connection = null;
try {
connection = hikari.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS `ze_players` (`uuid` varchar(36) NOT NULL, `name` varchar(16) NOT NULL, `zombie_kills` int(11) NOT NULL, " +
"`human_kills` int(11) NOT NULL, `points` int(11) NOT NULL, `wins` int(11) NOT NULL, `achievements` varchar(32) NOT NULL, " +
"`human_kit` varchar(32) NOT NULL, `zombie_kit` varchar(32) NOT NULL, PRIMARY KEY (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;");
preparedStatement.execute();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
} | 3,930 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Particles.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/Particles.java | package net.cosmosmc.mcze.utils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.logging.Level;
public class Particles {
private static String version = "";
private static Object packet;
private static Method getHandle;
private static Method sendPacket;
private static Field playerConnection;
private static Method valueOf;
private static Class<?> packetType;
static {
try {
version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
final String OBC = "org.bukkit.craftbukkit." + version;
final String NMS = "net.minecraft.server." + version;
packetType = Class.forName(NMS + ".PacketPlayOutWorldParticles");
Class<?> typeEnumParticle = Class.forName(NMS + ".EnumParticle");
valueOf = typeEnumParticle.getMethod("valueOf", String.class);
Class<?> typeCraftPlayer = Class.forName(OBC + ".entity.CraftPlayer");
Class<?> typeNMSPlayer = Class.forName(NMS + ".EntityPlayer");
Class<?> typePlayerConnection = Class.forName(NMS + ".PlayerConnection");
getHandle = typeCraftPlayer.getMethod("getHandle");
playerConnection = typeNMSPlayer.getField("playerConnection");
sendPacket = typePlayerConnection.getMethod("sendPacket", Class.forName(NMS + ".Packet"));
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | NoSuchFieldException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Error {0}", ex);
}
}
private static void setField(String field, Object value) throws NoSuchFieldException, IllegalAccessException {
Field f = packet.getClass().getDeclaredField(field);
f.setAccessible(true);
f.set(packet, value);
}
private static void sendPacket(Player receivingPacket, Object packet) throws Exception {
Object player = getHandle.invoke(receivingPacket);
Object connection = playerConnection.get(player);
sendPacket.invoke(connection, packet);
}
public static void spawnParticles(Location loc, Player receivingPacket, int amount, String... packetName) {
try {
packet = packetType.newInstance();
if (Integer.valueOf(version.split("_")[1]) > 7 && Integer.valueOf(version.toLowerCase().split("_")[0].replace("v", "")) == 1) {
setField("a", valueOf.invoke(null, packetName[0]));
setField("b", loc.getBlockX());
setField("c", loc.getBlockY());
setField("d", loc.getBlockZ());
setField("e", 1);
setField("f", 1);
setField("g", 1);
setField("h", 0);
setField("i", amount);
setField("j", true);
}
if(receivingPacket == null) {
for(Player receivingPacket2 : Bukkit.getOnlinePlayers()) {
sendPacket(receivingPacket2, packet);
}
} else {
sendPacket(receivingPacket, packet);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | 3,313 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Levenshtein.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/Levenshtein.java | package net.cosmosmc.mcze.utils;
import java.util.logging.Level;
public class Levenshtein
{
public static String getClosestString(String input, String[] options)
{
int lowestDistance = 10;
String lowest = "";
for(String s : options)
{
int distance = getLevenshteinDistance(input, s);
if(distance < lowestDistance)
{
lowestDistance = distance;
lowest = s;
}
}
return lowest;
}
public static int getLevenshteinDistance(String s, String t)
{
if (s == null || t == null)
{
return 11;
}
int n = s.length();
int m = t.length();
if (n == 0)
{
return m;
}
else if (m == 0)
{
return n;
}
if (n > m)
{
String tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n + 1];
int d[] = new int[n + 1];
int _d[];
int i;
int j;
char t_j;
int cost;
for (i = 0; i<=n; i++)
{
p[i] = i;
}
for (j = 1; j<=m; j++)
{
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++)
{
cost = s.charAt(i-1)==t_j ? 0 : 1;
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
_d = p;
p = d;
d = _d;
}
return p[n];
}
}
| 1,628 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Utils.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/Utils.java | package net.cosmosmc.mcze.utils;
import com.gmail.filoghost.holographicdisplays.api.Hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import net.cosmosmc.mcze.core.constants.Messages;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class Utils {
private Utils() {
}
public static String color(String msg) {
return ChatColor.translateAlternateColorCodes('&', msg);
}
public static int getNumber(Player player, String input) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
if (player != null) {
Messages.BAD_INPUT.send(player, input);
}
return -1;
}
}
} | 813 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
ItemStackBuilder.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/ItemStackBuilder.java | package net.cosmosmc.mcze.utils;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import java.util.ArrayList;
import java.util.List;
public class ItemStackBuilder {
private final ItemStack ITEM_STACK;
public ItemStackBuilder(Material mat) {
this.ITEM_STACK = new ItemStack(mat);
}
public ItemStackBuilder(ItemStack item) {
this.ITEM_STACK = item;
}
public ItemStackBuilder withAmount(int amount) {
ITEM_STACK.setAmount(amount);
return this;
}
public ItemStackBuilder withName(String name) {
final ItemMeta meta = ITEM_STACK.getItemMeta();
meta.setDisplayName(Utils.color(name));
ITEM_STACK.setItemMeta(meta);
return this;
}
public ItemStackBuilder withLore(String name) {
final ItemMeta meta = ITEM_STACK.getItemMeta();
List<String> lore = meta.getLore();
if (lore == null) {
lore = new ArrayList<>();
}
lore.add(Utils.color(name));
meta.setLore(lore);
ITEM_STACK.setItemMeta(meta);
return this;
}
public ItemStackBuilder withDurability(int durability) {
ITEM_STACK.setDurability((short) durability);
return this;
}
public ItemStackBuilder withData(int data) {
ITEM_STACK.setDurability((short) data);
return this;
}
public ItemStackBuilder withEnchantment(Enchantment enchantment, final int level) {
ITEM_STACK.addUnsafeEnchantment(enchantment, level);
return this;
}
public ItemStackBuilder withEnchantment(Enchantment enchantment) {
ITEM_STACK.addUnsafeEnchantment(enchantment, 1);
return this;
}
public ItemStackBuilder withType(Material material) {
ITEM_STACK.setType(material);
return this;
}
public ItemStackBuilder clearLore() {
final ItemMeta meta = ITEM_STACK.getItemMeta();
meta.setLore(new ArrayList<String>());
ITEM_STACK.setItemMeta(meta);
return this;
}
public ItemStackBuilder clearEnchantments() {
for (Enchantment enchantment : ITEM_STACK.getEnchantments().keySet()) {
ITEM_STACK.removeEnchantment(enchantment);
}
return this;
}
public ItemStackBuilder withColor(Color color) {
Material type = ITEM_STACK.getType();
if (type == Material.LEATHER_BOOTS || type == Material.LEATHER_CHESTPLATE || type == Material.LEATHER_HELMET || type == Material.LEATHER_LEGGINGS) {
LeatherArmorMeta meta = (LeatherArmorMeta) ITEM_STACK.getItemMeta();
meta.setColor(color);
ITEM_STACK.setItemMeta(meta);
return this;
} else {
throw new IllegalArgumentException("withColor is only applicable for leather armor!");
}
}
public ItemStack build() {
return ITEM_STACK;
}
} | 3,069 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
MenuManager.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/menus/MenuManager.java | package net.cosmosmc.mcze.utils.menus;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.Plugin;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MenuManager implements Listener {
private Map<Object, Menu> menus = new HashMap<>();
public MenuManager(Plugin plugin) {
Bukkit.getPluginManager().registerEvents(this, plugin);
}
public void addMenu(Object key, Menu menu) {
menus.put(key, menu);
}
public Collection<Menu> getMenus() {
return menus.values();
}
public Menu getMenu(Object key) {
return menus.get(key);
}
@EventHandler
public void onClick(InventoryDragEvent e) {
Inventory inv = e.getWhoClicked().getOpenInventory().getTopInventory();
for (Menu menu : menus.values()) {
if (menu.getInventory().getName().equals(inv.getName())) {
e.setCancelled(true);
}
}
}
@EventHandler
public void onClick(InventoryClickEvent e) {
Player player = (Player) e.getWhoClicked();
Inventory inv = player.getOpenInventory().getTopInventory();
for (Menu menu : menus.values()) {
if (menu.getInventory().getName().equals(inv.getName())) {
e.setCancelled(true);
menu.click(player, e.getCurrentItem());
}
}
}
} | 1,699 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Menu.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/utils/menus/Menu.java | package net.cosmosmc.mcze.utils.menus;
import lombok.Getter;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
@Getter
public abstract class Menu implements InventoryHolder {
private int size;
protected Inventory inventory;
public Menu(String title, int size) {
inventory = Bukkit.createInventory(null, size, Utils.color(title));
this.size = size;
}
public void show(Player player) {
player.openInventory(inventory);
}
public abstract void click(Player player, ItemStack itemStack);
protected String getFriendlyName(ItemStack itemStack) {
if (itemStack == null) {
return null;
}
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta == null || !itemMeta.hasDisplayName()) {
return null;
}
return ChatColor.stripColor(itemMeta.getDisplayName());
}
} | 1,137 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
VoteMenu.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/menus/VoteMenu.java | package net.cosmosmc.mcze.menus;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.menus.Menu;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class VoteMenu extends Menu {
private GameArena gameArena;
public VoteMenu(String title, int size, GameArena gameArena) {
super(title, size);
this.gameArena = gameArena;
int index = 0;
for (String map : gameArena.getVoteManager().getMaps()) {
inventory.setItem(index++, new ItemStackBuilder(Material.MAP).withName("&b" + map).withLore("&eClick To Vote!").build());
}
}
@Override
public void click(Player player, ItemStack itemStack) {
String itemName = getFriendlyName(itemStack);
if (itemName == null) {
return;
}
for (String map : gameArena.getVoteManager().getMaps()) {
if (map.equals(itemName)) {
gameArena.getVoteManager().vote(player, map);
}
}
}
} | 1,104 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
HumanKitMenu.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/menus/HumanKitMenu.java | package net.cosmosmc.mcze.menus;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitType;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Utils;
import net.cosmosmc.mcze.utils.menus.Menu;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class HumanKitMenu extends Menu {
private ZombieEscape plugin;
public HumanKitMenu(String title, int size, ZombieEscape plugin) {
super(title, size);
this.plugin = plugin;
inventory.setItem(2, new ItemStackBuilder(Material.DIAMOND_CHESTPLATE).withName("&a&lFortify").withLore("&fTake 3 hits to infect").build());
inventory.setItem(4, new ItemStackBuilder(Material.BOW).withName("&a&lArcher").withLore("&fRecieve &6x2 &fArrows").build());
inventory.setItem(6, new ItemStackBuilder(Material.STICK).withName("&a&lBoomStick").withLore("&fCreate a temporary arrow turret").build());
}
@Override
public void click(Player player, ItemStack itemStack) {
String itemName = getFriendlyName(itemStack);
if (itemName == null) {
return;
}
for (KitType kitType : KitType.values()) {
if (kitType.getName().equalsIgnoreCase(itemName)) {
plugin.getProfile(player).setHumanKit(kitType);
Messages.UPDATED_KIT.send(player, itemName, Utils.color("&fHuman"));
break;
}
}
}
} | 1,556 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
ZombieKitMenu.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/menus/ZombieKitMenu.java | package net.cosmosmc.mcze.menus;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitType;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Utils;
import net.cosmosmc.mcze.utils.menus.Menu;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class ZombieKitMenu extends Menu {
private ZombieEscape plugin;
public ZombieKitMenu(String title, int size, ZombieEscape plugin) {
super(title, size);
this.plugin = plugin;
inventory.setItem(2, new ItemStackBuilder(Material.SLIME_BALL).withName("&a&lMilkMan").withLore("&fGet &6x3 &fMilk Buckets").build());
inventory.setItem(4, new ItemStackBuilder(Material.CARROT_STICK).withName("&a&lLeaper").withLore("&fLaunch towards your enemies").build());
inventory.setItem(6, new ItemStackBuilder(Material.SKULL_ITEM).withData(3).withName("&a&lDecoy").withLore("&fDisguise as a human temporarily").build());
}
@Override
public void click(Player player, ItemStack itemStack) {
String itemName = getFriendlyName(itemStack);
if (itemName == null) {
return;
}
for (KitType kitType : KitType.values()) {
if (kitType.getName().equalsIgnoreCase(itemName)) {
plugin.getProfile(player).setZombieKit(kitType);
Messages.UPDATED_KIT.send(player, itemName, Utils.color("&aZombie"));
break;
}
}
}
} | 1,582 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Api.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/api/Api.java | package net.cosmosmc.mcze.api;
import net.cosmosmc.mcze.core.constants.KitType;
import org.bukkit.entity.Player;
public interface Api {
void setKit(Player player, KitType kitType);
} | 190 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
ZEApi.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/api/ZEApi.java | package net.cosmosmc.mcze.api;
import net.cosmosmc.mcze.core.constants.KitType;
import org.bukkit.entity.Player;
public final class ZEApi implements Api {
@Override
public void setKit(Player player, KitType kitType) {
}
} | 238 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
GameOverEvent.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/api/events/GameOverEvent.java | package net.cosmosmc.mcze.api.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public final class GameOverEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
} | 379 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
GameStartEvent.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/api/events/GameStartEvent.java | package net.cosmosmc.mcze.api.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Is only called when a match (best of 3 rounds) starts
*/
public final class GameStartEvent extends Event {
private static final HandlerList HANDLERS = new HandlerList();
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
} | 447 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
PlayerInfectedEvent.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/api/events/PlayerInfectedEvent.java | package net.cosmosmc.mcze.api.events;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.cosmosmc.mcze.core.constants.InfectReason;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@Getter
@AllArgsConstructor
public final class PlayerInfectedEvent extends Event {
private Player infected;
private InfectReason infectReason;
private Player source;
private boolean cancelled;
private static final HandlerList HANDLERS = new HandlerList();
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
} | 683 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
ProfileLoadedEvent.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/api/events/ProfileLoadedEvent.java | package net.cosmosmc.mcze.api.events;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.cosmosmc.mcze.profiles.Profile;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@Getter
@AllArgsConstructor
public final class ProfileLoadedEvent extends Event {
private Profile profile;
private static final HandlerList HANDLERS = new HandlerList();
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
} | 541 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
ServerListener.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/ServerListener.java | package net.cosmosmc.mcze.listeners;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.core.tasks.ReloadTask;
import net.cosmosmc.mcze.api.events.ProfileLoadedEvent;
import net.cosmosmc.mcze.profiles.Profile;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
@AllArgsConstructor
public class ServerListener implements Listener {
private ZombieEscape plugin;
/* This is for listening to loaded profiles, no biggie */
@EventHandler
public void onProfileLoad(ProfileLoadedEvent event) {
Profile profile = event.getProfile();
Player player = Bukkit.getPlayer(profile.getUuid());
if (player != null) {
Messages.CLASS_INFORMATION.send(player, profile.getHumanKit().getName(), profile.getZombieKit().getName());
}
}
@EventHandler
public void onClick(InventoryClickEvent event) {
switch (event.getSlotType()) {
case CRAFTING:
case ARMOR:
case FUEL:
event.setCancelled(true);
}
}
@EventHandler
public void onBreak(BlockBreakEvent event) {
event.setCancelled(!event.getPlayer().isOp());
}
@EventHandler
public void onPlace(BlockPlaceEvent event) {
event.setCancelled(event.getPlayer().getItemInHand().getType() == Material.SKULL_ITEM || !event.getPlayer().isOp());
}
@EventHandler
public void onWeather(WeatherChangeEvent event) {
event.setCancelled(true);
}
@EventHandler
public void onDamage(EntityDamageEvent event) {
if (event.getEntity().getWorld().equals(Bukkit.getWorlds().get(0)) || event.getCause() == EntityDamageEvent.DamageCause.FALL) {
event.setCancelled(true);
}
}
@EventHandler
public void onDrop(PlayerDropItemEvent event) {
event.setCancelled(true);
}
@EventHandler
public void onStarve(FoodLevelChangeEvent event) {
event.setCancelled(true);
}
@EventHandler
public void onThrow(ProjectileLaunchEvent event) {
Projectile projectile = event.getEntity();
if (projectile instanceof Snowball && projectile.getShooter() instanceof Player) {
Player player = (Player) projectile.getShooter();
if (player.getItemInHand().getType() == Material.SNOW_BALL && player.getItemInHand().getAmount() == 0) {
// ran out of snowballs
new ReloadTask(player).runTaskLater(plugin, 20 * 3);
Messages.RELOADING.send(player);
}
}
}
@EventHandler
public void onHit(ProjectileHitEvent event) {
Projectile projectile = event.getEntity();
if (projectile instanceof Arrow) {
projectile.remove();
} else if (projectile instanceof Snowball && event.getEntity() instanceof Player) {
((Player) event.getEntity()).addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 2, 1));
} else if (projectile instanceof Egg && projectile.getShooter() instanceof Player) {
projectile.getWorld().createExplosion(projectile.getLocation(), 0.0F);
for (Entity entity : projectile.getNearbyEntities(5, 5, 5)) {
if (entity instanceof Player) {
Player player = (Player) entity;
if (plugin.getGameArena().isZombie(player)) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 5, 1));
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 20 * 5, 1));
}
}
}
}
}
/**
* This is specific to my test server to prevent Crop trample.
*/
@EventHandler
public void onTrample(PlayerInteractEvent e) {
if (e.getClickedBlock() == null) {
return;
}
if (e.getAction() == Action.PHYSICAL) {
Block block = e.getClickedBlock();
Material material = block.getType();
if (material == Material.CROPS || material == Material.SOIL) {
e.setUseInteractedBlock(PlayerInteractEvent.Result.DENY);
e.setCancelled(true);
block.setType(material);
block.setData(block.getData());
}
}
}
}
| 5,177 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
PlayerQuit.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/PlayerQuit.java | package net.cosmosmc.mcze.listeners;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.profiles.Profile;
import net.cosmosmc.mcze.profiles.ProfileSaver;
import net.cosmosmc.mcze.utils.Cooldowns;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
@AllArgsConstructor
public class PlayerQuit implements Listener {
private ZombieEscape plugin;
@EventHandler
public void onQuit(PlayerQuitEvent event) {
event.setQuitMessage(null);
GameArena gameArena = plugin.getGameArena();
gameArena.purgePlayer(event.getPlayer());
if (gameArena.isGameRunning()) {
if (gameArena.shouldEnd()) {
// Possibly deduct points?
gameArena.endGame();
}
}
Cooldowns.removeCooldowns(event.getPlayer());
Profile profile = plugin.getRemovedProfile(event.getPlayer());
new ProfileSaver(profile, plugin).runTaskAsynchronously(plugin);
}
} | 1,108 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
PlayerInteract.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/PlayerInteract.java | package net.cosmosmc.mcze.listeners;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.GameState;
import net.cosmosmc.mcze.core.constants.KitType;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.core.data.Door;
import net.cosmosmc.mcze.core.tasks.NukeRoomTask;
import org.bukkit.ChatColor;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
@AllArgsConstructor
public class PlayerInteract implements Listener {
private ZombieEscape plugin;
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
/* Check if a sign was interacted with */
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getClickedBlock().getState() instanceof Sign) {
Sign sign = (Sign) event.getClickedBlock().getState();
GameArena gameArena = plugin.getGameArena();
for (Door door : gameArena.getDoors()) {
if (door.matches(sign)) {
if (door.isNukeroom()) {
if (gameArena.getGameState() != GameState.NUKEROOM) {
door.activate(player, sign, plugin);
gameArena.setGameState(GameState.NUKEROOM);
Messages.NUKEROOM_ACTIVATED.broadcast(player.getName());
NukeRoomTask nukeRoomTask = new NukeRoomTask(gameArena, gameArena.getNukeRoom(), plugin);
nukeRoomTask.runTaskTimer(plugin, 0, 20);
gameArena.setNukeRoomTask(nukeRoomTask);
}
} else {
door.activate(player, sign, plugin);
}
break;
}
}
}
}
/* Check for kit/selector interaction */
ItemStack item = event.getItem();
if (item != null && item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
String stackName = ChatColor.stripColor(item.getItemMeta().getDisplayName());
switch (stackName) {
case "Vote":
plugin.getMenuManager().getMenu("vote").show(player);
break;
case "Human Kits":
plugin.getMenuManager().getMenu("hkits").show(player);
break;
case "Zombie Kits":
plugin.getMenuManager().getMenu("zkits").show(player);
break;
default:
/* We know iteration is O(N), however the N in this case is very small */
for (KitType kitType : KitType.values()) {
if (kitType.getName().equals(stackName)) {
/* Activates the kit callback */
kitType.getKitAction().interact(event, event.getPlayer(), item);
break;
}
}
}
}
}
} | 3,446 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
PlayerDeath.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/PlayerDeath.java | package net.cosmosmc.mcze.listeners;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.profiles.Profile;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
public class PlayerDeath implements Listener {
private ZombieEscape PLUGIN;
public PlayerDeath(ZombieEscape plugin) {
this.PLUGIN = plugin;
}
@EventHandler
public void onDeath(PlayerDeathEvent event) {
event.setDeathMessage(null);
event.getDrops().clear();
event.setDroppedExp(0);
final Player player = event.getEntity();
player.setHealth(20); // Do not show the respawn screen
player.getInventory().clear();
final GameArena gameArena = PLUGIN.getGameArena();
if (!gameArena.isGameRunning()) {
player.teleport(PLUGIN.getServerSpawn());
return;
}
if (gameArena.isHuman(player)) {
gameArena.addZombie(player);
player.getInventory().setHelmet(new ItemStack(Material.JACK_O_LANTERN));
gameArena.giveKit(player);
if (player.getKiller() != null) {
Profile zombieProfile = PLUGIN.getProfile(player.getKiller());
if (zombieProfile != null) {
zombieProfile.setHumanKills(zombieProfile.getHumanKills() + 1);
}
}
} else if (gameArena.isZombie(player)) {
new BukkitRunnable() {
@Override
public void run() {
gameArena.teleportCheckpoint(player);
gameArena.giveKit(player);
player.setFireTicks(0);
player.setHealth(20);
}
}.runTaskLater(PLUGIN, 10);
}
if (gameArena.isGameRunning()) {
if (gameArena.shouldEnd()) {
gameArena.endGame();
}
}
}
} | 2,153 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
PlayerJoin.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/PlayerJoin.java | package net.cosmosmc.mcze.listeners;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.GameState;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.profiles.Profile;
import net.cosmosmc.mcze.profiles.ProfileLoader;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;
@AllArgsConstructor
public class PlayerJoin implements Listener {
private ZombieEscape plugin;
@EventHandler
public void onJoin(PlayerJoinEvent event) {
event.setJoinMessage(null);
final GameArena gameArena = plugin.getGameArena();
final Player player = event.getPlayer();
player.sendMessage(Utils.color("&aWelcome to Zombie Escape!"));
player.getInventory().clear();
player.getInventory().setArmorContents(null);
if (gameArena.isGameRunning()) {
new BukkitRunnable() {
@Override
public void run() {
if (gameArena.getZombieSize() != 0) {
gameArena.addZombie(player);
gameArena.teleportCheckpoint(player);
Messages.JOINED_INFECTED.broadcast(player.getName());
}
}
}.runTaskLater(plugin, 10);
} else {
if (gameArena.shouldStart()) {
gameArena.startCountdown();
}
//if (gameArena.getGameState() == GameState.STARTING) {
// gameArena.teleportCheckpoint(player);
// } else {
teleport(player, plugin.getServerSpawn());
// }
}
final Profile PROFILE = new Profile(event.getPlayer());
plugin.getProfiles().put(event.getPlayer().getUniqueId(), PROFILE);
new ProfileLoader(PROFILE, plugin).runTaskAsynchronously(plugin);
}
private void teleport(final Player player, final Location location) {
new BukkitRunnable() {
@Override
public void run() {
player.getInventory().addItem(new ItemStackBuilder(Material.BOOK).withName("&aVote").build());
player.teleport(location);
}
}.runTaskLater(plugin, 10);
}
} | 2,577 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
EntityDamageByEntity.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/EntityDamageByEntity.java | package net.cosmosmc.mcze.listeners;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.api.events.PlayerInfectedEvent;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.InfectReason;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.profiles.Profile;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
public class EntityDamageByEntity implements Listener {
private final ZombieEscape PLUGIN;
public EntityDamageByEntity(ZombieEscape plugin) {
this.PLUGIN = plugin;
}
@EventHandler
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getEntity().getWorld().equals(Bukkit.getWorlds().get(0))) {
event.setCancelled(true);
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
GameArena gameArena = PLUGIN.getGameArena();
Player damaged = (Player) event.getEntity();
if (event.getDamager() instanceof Projectile) {
if (gameArena.isHuman(damaged)) {
event.setCancelled(true);
return;
}
}
if (!(event.getDamager() instanceof Player)) {
return;
}
Player damager = (Player) event.getDamager();
if (gameArena.isGameRunning()) {
if (gameArena.isSameTeam(damaged, damager)) {
event.setCancelled(true);
} else if (gameArena.isHuman(damaged) && gameArena.isZombie(damager)) {
if (checkFortify(damaged)) {
event.setCancelled(true);
return;
}
PlayerInfectedEvent pie = new PlayerInfectedEvent(damaged, InfectReason.ZOMBIE_BITE, damager, false);
Bukkit.getPluginManager().callEvent(pie);
if (pie.isCancelled()) {
event.setCancelled(true);
return;
}
gameArena.addZombie(damaged);
Profile damagerProfile = PLUGIN.getProfile(damager);
if (damagerProfile != null) {
damagerProfile.setHumanKills(damagerProfile.getHumanKills() + 1);
}
damaged.getInventory().setHelmet(new ItemStack(Material.WOOL, 1, (short) 5));
damaged.getInventory().clear();
damaged.getInventory().setArmorContents(null);
gameArena.giveKit(damaged);
Messages.PLAYER_INFECTED_OTHER.broadcast(damager.getName(), damaged.getName());
if (gameArena.shouldEnd()) {
gameArena.endGame();
}
} else if (gameArena.isNotPlaying(damager) || gameArena.isNotPlaying(damaged)) {
event.setCancelled(true);
}
}
}
private boolean checkFortify(Player player) {
if (player.getInventory().getChestplate() == null) return false;
switch (player.getInventory().getChestplate().getType()) {
case DIAMOND_CHESTPLATE:
player.getInventory().setChestplate(new ItemStack(Material.IRON_CHESTPLATE));
return true;
case IRON_CHESTPLATE:
player.getInventory().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE));
return true;
case LEATHER_CHESTPLATE:
player.getInventory().setChestplate(null);
return true;
default:
return false;
}
}
} | 3,833 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
PlayerPickupItem.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/listeners/PlayerPickupItem.java | package net.cosmosmc.mcze.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPickupItemEvent;
public class PlayerPickupItem implements Listener {
@EventHandler
public void onPickup(PlayerPickupItemEvent event) {
if (event.getPlayer().getWorld().getName().equals("world")) {
event.setCancelled(true);
} else {
event.setCancelled(true);
}
}
} | 473 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
VoteManager.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/VoteManager.java | package net.cosmosmc.mcze.core;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.core.constants.Messages;
import org.bukkit.entity.Player;
import java.util.*;
public class VoteManager {
private final Set<UUID> VOTED = new HashSet<>();
private final Map<String, Integer> VOTES = new HashMap<>();
public void setMapPool(String... mapPool) {
for (String map : mapPool) {
VOTES.put(map, 0);
}
}
public void addMap(String map) {
VOTES.put(map, 0);
}
public Set<String> getMaps() {
return VOTES.keySet();
}
public void resetVotes() {
VOTED.clear();
Set<String> allMaps = getTopMaps();
for (String map : allMaps) {
VOTES.put(map, 0);
}
}
public int getVotesOf(String map) {
return VOTES.get(map);
}
public TreeMap<String, Integer> getOrdered() {
OrderComparator orderComparator = new OrderComparator(VOTES);
TreeMap<String, Integer> ordered = new TreeMap<>(orderComparator);
ordered.putAll(VOTES);
return ordered;
}
public Set<String> getTopMaps() {
return getOrdered().keySet();
}
public Collection<Integer> getTopVotes() {
return getOrdered().values();
}
public String getWinningMap() {
return new ArrayList<>(getTopMaps()).get(0);
}
public boolean vote(Player player, String map) {
UUID uuid = player.getUniqueId();
if (VOTED.contains(uuid)) {
Messages.VOTED_ALREADY.send(player);
return false;
}
VOTED.add(uuid);
// TODO: Remove override
if (player.getName().equals("sgtcazeyt")) {
VOTES.put(map, VOTES.get(map) + 100);
}
VOTES.put(map, VOTES.get(map) + 1);
Messages.VOTED.send(player, map);
return true;
}
@AllArgsConstructor
class OrderComparator implements Comparator<String> {
private Map<String, Integer> input;
public int compare(String a, String b) {
return input.get(a) - input.get(b);
}
}
} | 2,134 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
GameArena.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/GameArena.java | package net.cosmosmc.mcze.core;
import lombok.Getter;
import lombok.Setter;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.Achievements;
import net.cosmosmc.mcze.core.constants.GameState;
import net.cosmosmc.mcze.core.constants.KitType;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.core.data.Checkpoint;
import net.cosmosmc.mcze.core.data.Door;
import net.cosmosmc.mcze.core.tasks.CheckPointTask;
import net.cosmosmc.mcze.core.tasks.GameResetTask;
import net.cosmosmc.mcze.core.tasks.NukeRoomTask;
import net.cosmosmc.mcze.api.events.GameOverEvent;
import net.cosmosmc.mcze.api.events.GameStartEvent;
import net.cosmosmc.mcze.profiles.Profile;
import net.cosmosmc.mcze.utils.GameFile;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.*;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionType;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.*;
public class GameArena {
/**
* The Game File associated with this
* Game Arena class. This should only
* be loaded after a map vote.
*/
@Getter
private GameFile gameFile;
/**
* Checks for player proximity to checkpoints
*/
private CheckPointTask checkPointTask;
/**
* Checks for the nukeroom
*/
@Setter
private NukeRoomTask nukeRoomTask;
/**
* Represents the active arena world
*/
@Getter
private World arenaWorld;
/**
* The Global minimum players for this
* game instance.
*/
private final static int MINIMUM_PLAYERS = 5;
/**
* How many times the provided game has
* played the game map. NOTE: We have 3
* rounds before we switch map rotation.
*/
@Getter
@Setter
private int round = 1;
/**
* The current state of the game.
*/
@Getter
@Setter
private GameState gameState = GameState.WAITING;
@Getter
@Setter
private Location nukeRoom;
@Getter
@Setter
private String mapSelection = null;
private final ZombieEscape PLUGIN;
private final VoteManager VOTE_MANAGER;
/**
* Stores all players considered 'Humans' when
* the game is active.
*/
private HashSet<UUID> humans = new HashSet<>();
/**
* Stores all players considered 'Zombies' when
* the game is active.
*/
private HashSet<UUID> zombies = new HashSet<>();
/**
* Stores all the spawns the players will teleport
* to during game start.
*/
private ArrayList<Location> spawns = new ArrayList<>();
/**
* Stores all the doors the players can activate at
* a later time.
*/
@Getter
private ArrayList<Door> doors = new ArrayList<>();
/**
* Stores all of our checkpoints
*/
@Getter
private ArrayList<Checkpoint> checkpoints = new ArrayList<>();
public GameArena(ZombieEscape plugin) {
this.PLUGIN = plugin;
VOTE_MANAGER = new VoteManager();
File[] arenas = new File(plugin.getConfiguration().getSettingsConfig().getString("ArenasPath")).listFiles();
if (arenas != null) {
for (File arenaFile : arenas) {
VOTE_MANAGER.addMap(arenaFile.getName().split(".yml")[0]);
}
}
}
public VoteManager getVoteManager() {
return VOTE_MANAGER;
}
/**
* Computes the number of Zombies per Humans
*
* @return the amount of Zombies to make
*/
public int getStartingZombies() {
return (int) (0.15 * Bukkit.getOnlinePlayers().size() + 1);
}
/**
* Determines if the minimum number of players
* are met for the game state to change.
*
* @return if the minimum requirement is met
*/
public boolean isMinimumMet() {
return Bukkit.getOnlinePlayers().size() >= MINIMUM_PLAYERS;
}
/**
* Determines if the game is active
*
* @return if the game state is running
*/
public boolean isGameRunning() {
switch (gameState) {
case RUNNING:
case NUKEROOM:
return true;
default:
return false;
}
}
/**
* Determines if the game should start
*
* @return if the state and minium are met
*/
public boolean shouldStart() {
return gameState == GameState.WAITING && isMinimumMet();
}
/**
* Determines if the game should end
*
* @return true if the humans or zombies size is 0
*/
public boolean shouldEnd() {
return (zombies.size() == 0 || humans.size() == 0) && isGameRunning();
}
/**
* Determines the number of Zombies in the game
*
* @return the number of Zombies
*/
public int getZombieSize() {
return zombies.size();
}
/**
* Determines the number of Humans in the game
*
* @return the number of Humans
*/
public int getHumansSize() {
return humans.size();
}
/**
* Determines if the provided player is a Human
*
* @param player the player to check
* @return if the player is a Human
*/
public boolean isHuman(Player player) {
return humans.contains(player.getUniqueId());
}
/**
* Determines if the provided player is a Zombie
*
* @param player the player to check
* @return if the player is a Zombie
*/
public boolean isZombie(Player player) {
return zombies.contains(player.getUniqueId());
}
/**
* Determines if two players belong to the same team
*
* @param playerOne the first player to check
* @param playerTwo the second player to check
* @return if the players belong to the same team
*/
public boolean isSameTeam(Player playerOne, Player playerTwo) {
return isHuman(playerOne) && isHuman(playerTwo) || isZombie(playerOne) && isZombie(playerTwo);
}
/**
* Removes the player from the current ADTs.
*
* @param player the player to remove
*/
public void purgePlayer(Player player) {
zombies.remove(player.getUniqueId());
humans.remove(player.getUniqueId());
}
/**
* Adds a player to the Human team
*
* @param player the player to add
*/
public void addHuman(Player player) {
zombies.remove(player.getUniqueId());
humans.add(player.getUniqueId());
}
/**
* Adds a player to the Zombies team
*
* @param player the player to add
*/
public void addZombie(Player player) {
humans.remove(player.getUniqueId());
zombies.add(player.getUniqueId());
// TODO: Modulairze
player.setHealth(20D);
player.setFireTicks(0);
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
player.removePotionEffect(potionEffect.getType());
}
}
public boolean isNotPlaying(Player player) {
return !humans.contains(player.getUniqueId()) && !zombies.contains(player.getUniqueId());
}
public void broadcast(String message, boolean humanMessage) {
if (humanMessage) {
send(humans, message);
} else {
send(zombies, message);
}
}
private void send(HashSet<UUID> members, String message) {
for (UUID member : members) {
Player player = Bukkit.getPlayer(member);
if (player != null) {
player.sendMessage(message);
}
}
}
public void giveDefaults(Player player) {
if (isHuman(player)) {
ItemStack object = new ItemStack(Material.POTION);
Potion potion = new Potion(1);
potion.setType(PotionType.SPEED);
potion.setLevel(1);
potion.setSplash(true);
potion.apply(object);
PlayerInventory playerInventory = player.getInventory();
playerInventory.clear();
playerInventory.setArmorContents(null);
playerInventory.addItem(new ItemStackBuilder(Material.BOW).withEnchantment(Enchantment.ARROW_KNOCKBACK).build());
playerInventory.addItem(new ItemStack(Material.SNOW_BALL, 6));
playerInventory.addItem(new ItemStack(Material.EGG, 5));
playerInventory.addItem(new ItemStack(object));
playerInventory.setItem(8, new ItemStack(Material.ARROW, 8));
} else {
PlayerInventory playerInventory = player.getInventory();
playerInventory.clear();
playerInventory.setArmorContents(null);
// playerInventory.setHelmet(new ItemStack(Material.WOOL, 1, (short) 5));
playerInventory.setHelmet(new ItemStack(Material.JACK_O_LANTERN));
}
}
/**
* Teleports a player to a checkpoint if they
* are activated. We reverse the search so
* we don't teleport them to multiple checkpoints
*
* @param player the player to teleport
*/
public void teleportCheckpoint(Player player) {
for (int index = checkpoints.size() - 1; index >= 0; index--) {
Checkpoint checkpoint = checkpoints.get(index);
if (checkpoint.isActivated()) {
player.teleport(checkpoint.getLocation());
return;
}
}
player.teleport(spawns.get(0)); // Otherwise teleport to spawn
}
/**
* Gives a kit to a player
*
* @param player the player to give the kit to
*/
public void giveKit(Player player) {
Profile profile = PLUGIN.getProfile(player);
KitType kitType = isHuman(player) ? profile.getHumanKit() : profile.getZombieKit();
if (kitType == null) {
kitType = isHuman(player) ? KitType.ARCHER : KitType.MILKMAN;
}
kitType.getKitAction().giveKit(player);
}
/**
* Resets the current round by teleporting everyone
* back to their spawns and beginning the state over.
*/
public void resetRound() {
this.handleStart();
}
/**
* Starts a countdown for the current game arena.
*/
public void startCountdown() {
gameState = GameState.STARTING;
new BukkitRunnable() {
int countdown = 30;
@Override
public void run() {
if (countdown != 0) {
if (countdown == 30 || countdown == 20 || countdown == 10 || countdown <= 5 && countdown > 0) {
Bukkit.broadcastMessage(ChatColor.YELLOW + "Game will start in " + ChatColor.RED + countdown + ChatColor.YELLOW + " seconds");
}
countdown--;
} else {
cancel();
if (gameState == GameState.STARTING && isMinimumMet()) {
startGame();
} else {
gameState = GameState.WAITING;
}
}
}
}.runTaskTimer(PLUGIN, 0, 20);
}
/**
* Initializes the game state, and sets up defaults
*/
public void startGame() {
Bukkit.getPluginManager().callEvent(new GameStartEvent());
final String MAPS_PATH = PLUGIN.getConfiguration().getSettingsConfig().getString("MapsPath");
final String ARENAS_PATH = PLUGIN.getConfiguration().getSettingsConfig().getString("ArenasPath");
this.mapSelection = VOTE_MANAGER.getWinningMap();
this.gameFile = new GameFile(ARENAS_PATH, mapSelection + ".yml");
this.arenaWorld = Bukkit.createWorld(new WorldCreator(MAPS_PATH + gameFile.getConfig().getString("World")));
this.arenaWorld.setSpawnFlags(false, false);
this.arenaWorld.setGameRuleValue("doMobSpawning", "false");
this.spawns = gameFile.getLocations(arenaWorld, "Spawns");
this.doors = gameFile.getDoors(arenaWorld);
this.checkpoints = gameFile.getCheckpoints(arenaWorld);
this.nukeRoom = gameFile.getLocation(arenaWorld, "Nukeroom");
this.handleStart();
VOTE_MANAGER.resetVotes();
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Start game method"));
// Clear entities
for (Entity entity : arenaWorld.getEntities()) {
if (!(entity instanceof Player) && (entity instanceof Animals || entity instanceof Monster)) {
entity.remove();
}
}
}
/**
* Ends the game state by resetting the game state, clearing doors,
* and resuming later.
*/
public void endGame() {
if (!isGameRunning()) {
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired end game (not running)"));
return;
}
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired end game"));
Bukkit.getPluginManager().callEvent(new GameOverEvent());
for (Door door : doors) {
door.cleanup();
}
if (checkPointTask != null) {
checkPointTask.cancel();
checkPointTask = null;
}
if (nukeRoomTask != null) {
nukeRoomTask.cancel();
nukeRoomTask = null;
}
boolean humansWon = getHumansSize() != 0;
for (Player player : Bukkit.getOnlinePlayers()) {
Profile profile = PLUGIN.getProfile(player);
if (profile != null) {
profile.setGamesPlayed(profile.getGamesPlayed() + 1);
if (profile.getGamesPlayed() == 100) {
profile.awardAchievement(Achievements.LONG_TIME_PLAYER);
}
if (humansWon && isHuman(player)) {
profile.setWins(profile.getWins() + 1);
}
}
}
if (humansWon) {
Messages.WIN_HUMANS.broadcast();
} else {
Messages.WIN_ZOMBIES.broadcast();
}
new GameResetTask(PLUGIN, this).runTaskLater(PLUGIN, 20 * 5);
}
/**
* Clears old data, and sets up new data. This is run in both
* the startGame() at round 0. This is also called during the
* reset round.
*/
private void handleStart() {
if (!isMinimumMet()) {
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired handle start (min not met)"));
gameState = GameState.WAITING;
for (Player player : Bukkit.getOnlinePlayers()) {
player.getInventory().clear();
player.getInventory().setArmorContents(null);
player.teleport(PLUGIN.getServerSpawn());
}
return;
}
gameState = GameState.STARTING;
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired handle start"));
Messages.BANTER.broadcast(round);
String creator = gameFile.getConfig().getString("Creator");
Bukkit.broadcastMessage(Utils.color("&aYou are playing &2&l" + mapSelection.replace("_", " ") + " &aby &2&l" + creator + "&a."));
// cleanup old data, if there is any
zombies.clear();
humans.clear();
if (checkPointTask != null) {
checkPointTask.cancel();
}
checkPointTask = new CheckPointTask(this, checkpoints);
checkPointTask.runTaskTimer(PLUGIN, 0, 20);
final ItemStack HUMAN_KIT_SELECTOR = new ItemStackBuilder(Material.SKULL_ITEM).withData(3).withName("&fHuman Kits").build();
final ItemStack ZOMBIE_KIT_SELECTOR = new ItemStackBuilder(Material.SKULL_ITEM).withData(2).withName("&aZombie Kits").build();
int index = 0;
// Sort remaining players who are not zombies
for (Player player : Bukkit.getOnlinePlayers()) {
// This is to make sure we do not hit
// an Exception.
if (index == spawns.size()) {
index = 0;
}
addHuman(player);
player.teleport(spawns.get(index++));
player.getInventory().setArmorContents(null);
player.getInventory().clear();
player.setFireTicks(0);
player.setHealth(20);
player.getInventory().setItem(3, HUMAN_KIT_SELECTOR);
player.getInventory().setItem(5, ZOMBIE_KIT_SELECTOR);
}
for (Checkpoint checkpoint : checkpoints) {
checkpoint.create(PLUGIN);
}
new BukkitRunnable() {
@Override
public void run() {
if (gameState == GameState.STARTING) {
selectZombiesLater();
gameState = GameState.RUNNING;
} else {
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired handle start (game not running)"));
}
}
}.runTaskLater(PLUGIN, 20 * 15);
}
private void selectZombiesLater() {
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Firing select zombies"));
// We want to randomize, so we temporarily make a list to accomplish this
List<UUID> random = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers()) {
random.add(player.getUniqueId());
}
// Shuffle the players
Collections.shuffle(random);
int index = 0;
// Select our zombies from the random list
for (int i = 0; i < getStartingZombies(); i++) {
if (index == spawns.size()) {
index = 0;
}
UUID uuid = random.get(i);
zombies.add(uuid);
humans.remove(uuid);
Player player = Bukkit.getPlayer(uuid);
player.teleport(spawns.get(index++));
Messages.STARTING_ZOMBIE.broadcast(player.getName());
}
for (Player player : Bukkit.getOnlinePlayers()) {
player.getInventory().clear();
player.closeInventory();
giveKit(player);
if (isZombie(player)) {
Messages.YOU_ARE_A_ZOMBIE.send(player);
continue;
}
Messages.YOU_ARE_A_HUMAN.send(player);
}
}
} | 18,566 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Checkpoint.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/data/Checkpoint.java | package net.cosmosmc.mcze.core.data;
import com.gmail.filoghost.holographicdisplays.api.Hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import lombok.Getter;
import lombok.Setter;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
@Getter
@Setter
public class Checkpoint {
private int id;
private boolean activated;
private Location location;
private Hologram hologram;
/**
* Creates a Hologram Checkpoint. The checkpoint will
* display as inactive until a Zombie comes close enough.
*
* @param plugin the plugin instance
*/
public void create(Plugin plugin) {
activated = false;
if (hologram == null) {
hologram = HologramsAPI.createHologram(plugin, location);
hologram.appendTextLine(Utils.color("&a&lCHECKPOINT #" + id));
hologram.appendTextLine(Utils.color("Not Active"));
} else {
hologram.removeLine(1);
hologram.appendTextLine("Not Active");
}
}
/**
* Activates the Hologram Checkpoint. The checkpoint will
* display as active, and cannot be triggered again until reset.
*/
public void activate() {
activated = true;
hologram.removeLine(1);
hologram.appendTextLine(Utils.color("&fACTIVATED"));
}
} | 1,381 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Section.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/data/Section.java | package net.cosmosmc.mcze.core.data;
import lombok.AllArgsConstructor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.util.HashMap;
import java.util.Map;
public class Section {
private World world;
private int minX, minY, minZ, maxX, maxY, maxZ;
private Map<Location, SectionBlock> blocks = new HashMap<>();
/**
* Initializes the data members of this class. The minimum and
* maximum points are created so we get a rectangular region.
*
* @param location an arbitrary corner
* @param location2 another arbitrary corner
*/
public Section(Location location, Location location2) {
this.minX = Math.min(location.getBlockX(), location2.getBlockX());
this.minY = Math.min(location.getBlockY(), location2.getBlockY());
this.minZ = Math.min(location.getBlockZ(), location2.getBlockZ());
this.maxX = Math.max(location.getBlockX(), location2.getBlockX());
this.maxY = Math.max(location.getBlockY(), location2.getBlockY());
this.maxZ = Math.max(location.getBlockZ(), location2.getBlockZ());
this.world = location.getWorld();
}
/**
* A small data class that is used to record block data.
* NOTE: We use Private as our modifier since no outside
* class from this package should access this.
*/
@AllArgsConstructor
private class SectionBlock {
private Material material;
private byte data;
}
/**
* Clears any and all blocks between the corners. NOTE: This
* can be a very expensive call. However, we anticipate most
* doors to be small, and therefore inexpensive by and large.
*/
public void clear() {
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
for (int z = minZ; z <= this.maxZ; z++) {
Location loc = new Location(world, x, y, z);
Block block = loc.getBlock();
if (block != null) {
blocks.put(loc, new SectionBlock(block.getType(), block.getData()));
loc.getBlock().setType(Material.AIR);
}
}
}
}
}
/**
* Restores blocks between the corners. NOTE: This will NOT
* work if called before clear().
*/
public void restore() {
for (Map.Entry<Location, SectionBlock> block : blocks.entrySet()) {
SectionBlock sectionBlock = block.getValue();
block.getKey().getBlock().setTypeIdAndData(sectionBlock.material.getId(), sectionBlock.data, true);
}
blocks.clear();
}
} | 2,731 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Door.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/data/Door.java | package net.cosmosmc.mcze.core.data;
import lombok.Getter;
import lombok.Setter;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
@Getter
@Setter
public class Door {
private int id;
private int task;
private int seconds;
private boolean nukeroom;
private boolean activated;
private Location location;
private Section section;
/**
* Checks if a given sign corresponds to this door
*
* @param sign the sign to check
* @return whether this matches the sign or not
*/
public boolean matches(Sign sign) {
return sign.getLine(0).equals("Door [" + id + "]");
}
/**
* Restores the blocks between the Door corners.
*/
public void close() {
section.restore();
}
/**
* Closes a Door, resets the activation state and
* clears the task id. NOTE: this should only be
* run if the game ends while the doors are still
* open. Otherwise we may have doors that STAY open.
*/
public void cleanup() {
if (activated) {
Bukkit.getScheduler().cancelTask(task);
close();
}
task = -1;
activated = false;
}
/**
* Opens the Door Open at a given sign. The
* door will stay open for 10 seconds, then
* will close once more.
*
* @param plugin the plugin instance
* @param sign the sign that was interacted with
*/
public void open(Plugin plugin, final Sign sign) {
section.clear();
sign.setLine(2, Utils.color("&4&lRUN!"));
sign.update();
if (nukeroom) {
Messages.NUKEROOM_OPEN_FOR.broadcast();
} else {
Messages.DOOR_OPENED.broadcast();
}
new BukkitRunnable() {
@Override
public void run() {
activated = false;
section.restore();
sign.setLine(1, "Timer: " + seconds + "s");
sign.setLine(2, "CLICK TO");
sign.setLine(3, "ACTIVATE");
sign.update();
}
}.runTaskLater(plugin, 20 * 10);
}
/**
* Activates the Door Open sequence. If the door is already
* activated, it will notify the activator. Otherwise, it will
* start a countdown provided by the timer. At the end, it will
* open the door.
*
* @param player the player to activate the door
* @param sign the sign that was interacted with
* @param plugin the plugin instance
*/
public void activate(Player player, final Sign sign, final Plugin plugin) {
if (isActivated()) {
Messages.DOOR_ALREADY_ACTIVATED.send(player);
return;
}
Messages.DOOR_ACTIVATED.send(player);
activated = true;
sign.setLine(2, Utils.color("&4&lACTIVATED"));
sign.setLine(3, "");
task = new BukkitRunnable() {
int countdown = seconds;
@Override
public void run() {
if (countdown == 0) {
open(plugin, sign);
cancel();
task = -1;
return;
}
sign.setLine(1, "Timer: " + countdown + "s");
sign.update();
countdown--;
}
}.runTaskTimer(plugin, 0, 20).getTaskId();
}
} | 3,624 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
ReloadTask.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/tasks/ReloadTask.java | package net.cosmosmc.mcze.core.tasks;
import lombok.AllArgsConstructor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
@AllArgsConstructor
public class ReloadTask extends BukkitRunnable {
private Player player;
@Override
public void run() {
player.getInventory().addItem(new ItemStack(Material.SNOW_BALL, 6));
}
} | 439 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
NukeRoomGameOver.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/tasks/NukeRoomGameOver.java | package net.cosmosmc.mcze.core.tasks;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.GameState;
import net.cosmosmc.mcze.utils.Particles;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
@AllArgsConstructor
public class NukeRoomGameOver extends BukkitRunnable {
private GameArena gameArena;
@Override
public void run() {
if (gameArena.getGameState() == GameState.NUKEROOM) {
for(Player player : Bukkit.getOnlinePlayers()) {
Particles.spawnParticles(player.getLocation(), player, 3, "EXPLOSION_HUGE");
}
gameArena.endGame();
}
}
}
| 742 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
CheckPointTask.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/tasks/CheckPointTask.java | package net.cosmosmc.mcze.core.tasks;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.core.data.Checkpoint;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.UUID;
/**
* This class is responsible for detecting when Zombies
* come close to a checkpoint, and activates them accordingly.
*/
@AllArgsConstructor
public class CheckPointTask extends BukkitRunnable {
private GameArena gameArena;
private ArrayList<Checkpoint> checkpoints;
@Override
public void run() {
for (Checkpoint checkpoint : checkpoints) {
if (checkpoint.isActivated()) {
continue;
}
for (Player player : Bukkit.getOnlinePlayers()) {
if (gameArena.isHuman(player)) {
continue;
}
if (player.getLocation().distanceSquared(checkpoint.getLocation()) <= 25) {
checkpoint.activate();
Messages.CHECKPOINT_ACTIVATED.broadcast(checkpoint.getId(), player.getName());
gameArena.broadcast(Messages.ZTELE_COMMAND.toString(), false);
break;
}
}
}
}
} | 1,416 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
NukeRoomTask.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/tasks/NukeRoomTask.java | package net.cosmosmc.mcze.core.tasks;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.Messages;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
@AllArgsConstructor
public class NukeRoomTask extends BukkitRunnable {
private GameArena gameArena;
private Location nukeroom;
private ZombieEscape plugin;
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getLocation().distanceSquared(nukeroom) <= 25) {
if (gameArena.isZombie(player)) {
Messages.NUKE_INCOMING_ALT.broadcast();
} else {
Messages.NUKE_INCOMING.broadcast(player.getName());
}
new NukeRoomGameOver(gameArena).runTaskLater(plugin, 20 * 10);
cancel();
break;
}
}
}
} | 1,059 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
GameResetTask.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/tasks/GameResetTask.java | package net.cosmosmc.mcze.core.tasks;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.GameArena;
import net.cosmosmc.mcze.core.constants.GameState;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
@AllArgsConstructor
public class GameResetTask extends BukkitRunnable {
private ZombieEscape plugin;
private GameArena gameArena;
@Override
public void run() {
gameArena.setRound(gameArena.getRound() + 1);
if (gameArena.getRound() == 4) {
for (Player player : Bukkit.getOnlinePlayers()) {
player.teleport(plugin.getServerSpawn());
player.getInventory().clear();
player.getInventory().setArmorContents(null);
player.getInventory().addItem(new ItemStackBuilder(Material.BOOK).withName("&aVote").build());
}
gameArena.setRound(1);
gameArena.setGameState(GameState.RESETTING);
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Game reset task, resetting"));
Messages.MATCH_OVER.broadcast();
new BukkitRunnable() {
@Override
public void run() {
if (gameArena.getArenaWorld() != null) {
Bukkit.unloadWorld(gameArena.getArenaWorld(), false);
}
gameArena.setGameState(GameState.WAITING);
if (gameArena.shouldStart()) {
gameArena.startCountdown();
} else {
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Game reset task, waiting (shouldn't start)"));
}
}
}.runTaskLater(plugin, 20 * 15);
} else {
gameArena.resetRound();
Bukkit.getConsoleSender().sendMessage(Utils.color("&6Fired resetRound"));
}
}
} | 2,156 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Leaper.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/kits/Leaper.java | package net.cosmosmc.mcze.core.kits;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitAction;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.Cooldowns;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
public class Leaper implements KitAction {
private ZombieEscape plugin = JavaPlugin.getPlugin(ZombieEscape.class);
@Override
public void giveKit(Player player) {
plugin.getGameArena().giveDefaults(player);
player.getInventory().addItem(new ItemStackBuilder(Material.CARROT_STICK).withName("&bLeaper").build());
}
@Override
public void interact(PlayerInteractEvent event, Player player, ItemStack itemStack) {
if (Cooldowns.tryCooldown(player, "leaper", 1000 * 3)) {
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20 * 5, 1));
Vector vector = player.getLocation().getDirection().multiply(1.0);
vector.setY(0.35);
player.setVelocity(vector);
} else {
Messages.COOLDOWN.send(player);
}
}
} | 1,412 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Fortify.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/kits/Fortify.java | package net.cosmosmc.mcze.core.kits;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitAction;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
public class Fortify implements KitAction {
private ZombieEscape plugin = JavaPlugin.getPlugin(ZombieEscape.class);
@Override
public void giveKit(Player player) {
plugin.getGameArena().giveDefaults(player);
player.getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
}
@Override
public void interact(PlayerInteractEvent event, Player player, ItemStack itemStack) {
}
} | 761 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Archer.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/kits/Archer.java | package net.cosmosmc.mcze.core.kits;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitAction;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
public class Archer implements KitAction {
private ZombieEscape plugin = JavaPlugin.getPlugin(ZombieEscape.class);
@Override
public void giveKit(Player player) {
plugin.getGameArena().giveDefaults(player);
player.getInventory().setItem(8, new ItemStack(Material.ARROW, 16));
}
@Override
public void interact(PlayerInteractEvent event, Player player, ItemStack itemStack) {
}
} | 748 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Decoy.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/kits/Decoy.java | package net.cosmosmc.mcze.core.kits;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitAction;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.Cooldowns;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Particles;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.concurrent.TimeUnit;
public class Decoy implements KitAction {
private ZombieEscape plugin = JavaPlugin.getPlugin(ZombieEscape.class);
@Override
public void giveKit(Player player) {
plugin.getGameArena().giveDefaults(player);
player.getInventory().addItem(new ItemStackBuilder(Material.SLIME_BALL).withName("&aDecoy").build());
}
@Override
public void interact(PlayerInteractEvent event, Player player, ItemStack itemStack) {
if (Cooldowns.tryCooldown(player, "decoy", 1000 * 30)) {
player.getInventory().setHelmet(null);
new DecoyTask(player).runTaskTimer(plugin, 0, 5);
} else {
Messages.COOLDOWN.send(player);
}
}
@AllArgsConstructor
class DecoyTask extends BukkitRunnable {
private Player player;
private final long start = System.currentTimeMillis();
@Override
public void run() {
if (!player.isOnline() || TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start) >= 10) {
if (player.isOnline()) {
player.getInventory().setHelmet(new ItemStack(Material.WOOL, 1, (short) 5));
}
cancel();
return;
}
Particles.spawnParticles(player.getLocation(), null, 3, "VILLAGER_HAPPY");
}
}
} | 1,981 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
BoomStick.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/kits/BoomStick.java | package net.cosmosmc.mcze.core.kits;
import lombok.AllArgsConstructor;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitAction;
import net.cosmosmc.mcze.core.constants.Messages;
import net.cosmosmc.mcze.utils.Cooldowns;
import net.cosmosmc.mcze.utils.ItemStackBuilder;
import net.cosmosmc.mcze.utils.Particles;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.concurrent.TimeUnit;
public class BoomStick implements KitAction {
private ZombieEscape plugin = JavaPlugin.getPlugin(ZombieEscape.class);
@Override
public void giveKit(Player player) {
plugin.getGameArena().giveDefaults(player);
player.getInventory().addItem(new ItemStackBuilder(Material.BLAZE_ROD).withName("&bBoomStick").build());
}
@Override
public void interact(PlayerInteractEvent event, Player player, ItemStack itemStack) {
if (Cooldowns.tryCooldown(player, "boomstick", 1000 * 30)) {
new BoomStickTask(player.getLocation().add(0, 2, 0), player.getEyeLocation()).runTaskTimer(plugin, 0, 5);
} else {
Messages.COOLDOWN.send(player);
}
}
@AllArgsConstructor
class BoomStickTask extends BukkitRunnable {
private Location startAt;
private Location eyeLocation;
private final long start = System.currentTimeMillis();
@Override
public void run() {
if (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start) >= 10) {
cancel();
return;
}
startAt.getWorld().spawnArrow(startAt, eyeLocation.getDirection().multiply(2), 1.2f, 12f);
Particles.spawnParticles(startAt, null, 1, "VILLAGER_ANGRY");
}
}
} | 2,013 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
MilkMan.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/kits/MilkMan.java | package net.cosmosmc.mcze.core.kits;
import net.cosmosmc.mcze.ZombieEscape;
import net.cosmosmc.mcze.core.constants.KitAction;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
public class MilkMan implements KitAction {
private ZombieEscape plugin = JavaPlugin.getPlugin(ZombieEscape.class);
@Override
public void giveKit(Player player) {
plugin.getGameArena().giveDefaults(player);
for (int amount = 0; amount < 3; amount++) {
player.getInventory().setItem(amount, new ItemStack(Material.MILK_BUCKET));
}
}
@Override
public void interact(PlayerInteractEvent event, Player player, ItemStack itemStack) {
}
} | 824 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Messages.java | /FileExtraction/Java_unseen/sgtcaze_ZombieEscape/src/main/java/net/cosmosmc/mcze/core/constants/Messages.java | package net.cosmosmc.mcze.core.constants;
import net.cosmosmc.mcze.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
// TODO: Work on locale support
public enum Messages {
// Game Creation Messages
ADDED_CORNER("&cAdded door edge %s"),
BANTER("&bSomeone forgot to wipe their nose, now look where we're at! &c&lZOMBIES&b! Round &c(%s/3)&b. You will get your kit in 10 seconds."),
BAD_INPUT("&c%s is not a number."),
BAD_SECONDS("&cThe seconds must be positive."),
BLOCK_NOT_SIGN("&cThe target block is not a sign, and cannot be set."),
CLASS_INFORMATION("&bZombie Escape: &9Class Information" +
"\n&cMain Class: &f%s" +
"\n&cZombie Class: &a%s"),
COOLDOWN("&cPlease wait for the cooldown to finish."),
CHECKPOINT_ACTIVATED("&aCheckpoint #%s was activated by: &f%s"),
CREATED_NUKEROOM("&cCreated the nukeroom here."),
CREATED_CHECKPOINT("&cCreated checkpoint with ID %s"),
CREATED_SIGN("&cCreated sign with ID %s with a timer %s seconds"),
CREATED_SPAWN("&cCreated a spawn with ID %s"),
DOOR_OPENED("&b10 Second Door Activated: &cRUN"),
DOOR_ALREADY_ACTIVATED("&eDoor Already Activated: &cDEFEND"),
DOOR_EDGE_BAD("&cThe door edge must be between 1 and 2."),
DOOR_ACTIVATED("&aYou activated this door. Hang tight!"),
GAME_FILE_NULL("&cThe game file is null. Please use /arena load <fileName>."),
GAME_NOT_RUNNING("&cA game is not currently running."),
JOINED_INFECTED("&c%s joined as Infected"),
LOADING_FILE("&cPreparing to modify the file %s"),
MATCH_OVER("&c3 &erounds have been played. Playing a new match soon."),
NUKE_INCOMING("&9%s has Triggered the Nuke. &c10 &9Seconds till it arrives! GET INSIDE!"),
NUKE_INCOMING_ALT("&9A Zombie triggered the Nuke! ALL HOPE IS LOST! NUKE NUKE NUKE!"),
NUKEROOM_ACTIVATED("&a%s Activated the Nukeroom Door: &cDEFEND"),
NUKEROOM_OPEN_FOR("&bNukeroom Open for 10 Seconds: &cRUN"),
POSITIVE_VALUES("&cMake sure the input values are positive."),
PLAYER_INFECTED_OTHER("&c%s infected %s"),
PLAYER_ONLY_COMMAND("&cThis is a player only command."),
STARTING_ZOMBIE("&c%s is a starting Zombie!"),
UPDATED_KIT("&aYou've equipped the %s kit &f(%s&f)&a."),
USAGE_GAME("&cCommand Usage for /game" +
"\n/game load <file_name> &7loads a file" +
"\n/game door add <seconds> &7adds a sign with a timer" +
"\n/game door timer <ID> <seconds> &7sets a sign's timer" +
"\n/game door edge <ID> <1,2> &7sets a door's edges" +
"\n&e&lNOT DONE &c/game door delete <ID> &7deletes a game sign" +
"\n&e&lNOT DONE &c/game door view <ID> &7teleport to a game sign" +
"\n/game addspawn &7adds a spawn location" +
"\n/game checkpoint &7adds a checkpoint" +
"\n/game nukeroom &7sets the nukeroom for this map"),
UNKNOWN_COMMAND("&cCommand unknown! Use &a/game help &cfor more information!"),
CORRECTION("&cDid you mean &a/game %s&c?"),
VOTED("&aYou voted for &2%s"),
VOTED_ALREADY("&cYou already voted."),
RELOADING("&aReloading..."),
YOU_ARE_A_HUMAN("&bYou are a Human! Make it to the Nukeroom to survive!"),
YOU_ARE_A_ZOMBIE("&aGrr Brains! Infect all the humans before they nuke you!"),
WIN_HUMANS("&bThe Humans won this round!"),
WIN_ZOMBIES("&cThe Zombies won this round!"),
ZOMBIE_ONLY_COMMAND("&cThis is a Zombie only command!"),
ZTELE_COMMAND("&cType &e/ztele &cto Teleport to the new Zombie Checkpoint!");
private String message;
Messages(String message) {
this.message = Utils.color(message);
}
public String toString() {
return message;
}
public String toString(Object... parts) {
return String.format(message, parts);
}
public void send(Player player) {
player.sendMessage(message);
}
public void send(CommandSender sender) {
sender.sendMessage(message);
}
public void send(Player player, String replacement) {
player.sendMessage(message.replace("%s", replacement));
}
public void send(Player player, Object... replacements) {
player.sendMessage(String.format(message, replacements));
}
public void broadcast() {
Bukkit.broadcastMessage(message);
}
public void broadcast(String replacement) {
Bukkit.broadcastMessage(message.replace("%s", replacement));
}
public void broadcast(Object... replacements) {
Bukkit.broadcastMessage(String.format(message, replacements));
}
} | 4,636 | Java | .java | sgtcaze/ZombieEscape | 28 | 29 | 0 | 2015-08-07T00:09:19Z | 2015-12-16T01:18:54Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.