chore: switch to using clang format

This commit is contained in:
Sekwah 2024-06-16 04:50:56 +01:00
parent c0cdcc327d
commit 79c935a931
95 changed files with 1742 additions and 1640 deletions

11
.clang-format Normal file
View File

@ -0,0 +1,11 @@
BasedOnStyle: Google
IndentWidth: 4
TabWidth: 4
UseTab: Never
AllowShortFunctionsOnASingleLine: None
BreakBeforeBraces: Attach
ConstructorInitializerAllOnOneLineOrOnePerLine: true
BreakConstructorInitializers: BeforeComma
AlignAfterOpenBracket: Align
PenaltyBreakBeforeFirstCallParameter: 1
ColumnLimit: 80

View File

@ -18,12 +18,6 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Set up JDK 11
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '11'
- uses: dorny/paths-filter@v2 - uses: dorny/paths-filter@v2
id: filter id: filter
with: with:

View File

@ -1,7 +1,7 @@
# See https://pre-commit.com for more information # See https://pre-commit.com for more information
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1 rev: v4.6.0
hooks: hooks:
- id: trailing-whitespace - id: trailing-whitespace
- id: end-of-file-fixer - id: end-of-file-fixer
@ -11,7 +11,7 @@ repos:
- id: check-case-conflict - id: check-case-conflict
- repo: https://github.com/Lucas-C/pre-commit-hooks - repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.1.10 rev: v1.5.5
hooks: hooks:
- id: remove-crlf - id: remove-crlf
- id: remove-tabs - id: remove-tabs
@ -19,9 +19,13 @@ repos:
- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks
rev: v2.13.0 rev: v2.13.0
hooks: hooks:
- id: pretty-format-java
args: [--autofix, --aosp, --google-java-formatter-version=1.16.0]
- id: pretty-format-yaml - id: pretty-format-yaml
args: [--autofix] args: [--autofix]
- id: pretty-format-toml - id: pretty-format-toml
args: [--autofix] args: [--autofix]
- repo: https://github.com/pocc/pre-commit-hooks
rev: v1.3.5
hooks:
- id: clang-format
args: [-i, --style=file]

View File

@ -20,12 +20,10 @@ import com.sekwah.advancedportals.core.tags.activation.*;
import com.sekwah.advancedportals.core.util.GameScheduler; import com.sekwah.advancedportals.core.util.GameScheduler;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
public class AdvancedPortalsCore { public class AdvancedPortalsCore {
public static final String version = "1.0.0"; public static final String version = "1.0.0";
private final InfoLogger infoLogger; private final InfoLogger infoLogger;
@ -34,8 +32,8 @@ public class AdvancedPortalsCore {
private final AdvancedPortalsModule module; private final AdvancedPortalsModule module;
/** /**
* Use this to enable or alter certain features for different versions. If there is an issue * Use this to enable or alter certain features for different versions. If
* parsing it for any reason it will be set to 0.0.0 * there is an issue parsing it for any reason it will be set to 0.0.0
*/ */
private final int[] mcVersion; private final int[] mcVersion;
@ -63,21 +61,21 @@ public class AdvancedPortalsCore {
// TEMP REMOVE THIS THIS IS JUST FOR DEV // TEMP REMOVE THIS THIS IS JUST FOR DEV
@Inject private IPlayerDataRepository tempDataRepository; @Inject private IPlayerDataRepository tempDataRepository;
public AdvancedPortalsCore( public AdvancedPortalsCore(String mcVersion, File dataStorageLoc,
String mcVersion, InfoLogger infoLogger,
File dataStorageLoc, ServerContainer serverContainer) {
InfoLogger infoLogger,
ServerContainer serverContainer) {
instance = this; instance = this;
this.serverContainer = serverContainer; this.serverContainer = serverContainer;
this.dataStorage = new DataStorage(dataStorageLoc); this.dataStorage = new DataStorage(dataStorageLoc);
this.infoLogger = infoLogger; this.infoLogger = infoLogger;
int[] mcVersionTemp; int[] mcVersionTemp;
infoLogger.info("Loading Advanced Portals Core v" + version + " for MC: " + mcVersion); infoLogger.info("Loading Advanced Portals Core v" + version
+ " for MC: " + mcVersion);
try { try {
mcVersionTemp = mcVersionTemp = Arrays.stream(mcVersion.split("\\."))
Arrays.stream(mcVersion.split("\\.")).mapToInt(Integer::parseInt).toArray(); .mapToInt(Integer::parseInt)
.toArray();
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
infoLogger.info("Failed to parse MC version: " + mcVersion); infoLogger.info("Failed to parse MC version: " + mcVersion);
e.printStackTrace(); e.printStackTrace();
@ -92,13 +90,13 @@ public class AdvancedPortalsCore {
} }
/** /**
* For some platforms we could do this on construction but this just allows for a bit more * For some platforms we could do this on construction but this just allows
* control * for a bit more control
*/ */
public void onEnable() { public void onEnable() {
// Force values to get injected, either because the initial ones were created too early or // Force values to get injected, either because the initial ones were
// to ensure they are not null. // created too early or to ensure they are not null. Do it here to give
// Do it here to give implementations a chance to interact with the module. // implementations a chance to interact with the module.
Injector injector = module.getInjector(); Injector injector = module.getInjector();
injector.injectMembers(this); injector.injectMembers(this);
injector.injectMembers(Lang.instance); injector.injectMembers(Lang.instance);
@ -124,7 +122,8 @@ public class AdvancedPortalsCore {
this.tagRegistry.registerTag(new PermissionTag()); this.tagRegistry.registerTag(new PermissionTag());
} }
/** */ /**
*/
public void registerCommands() { public void registerCommands() {
this.registerPortalCommand(commandRegister); this.registerPortalCommand(commandRegister);
this.registerDestinationCommand(commandRegister); this.registerDestinationCommand(commandRegister);
@ -133,43 +132,61 @@ public class AdvancedPortalsCore {
private void registerPortalCommand(CommandRegister commandRegister) { private void registerPortalCommand(CommandRegister commandRegister) {
this.portalCommand = new CommandWithSubCommands(this); this.portalCommand = new CommandWithSubCommands(this);
this.portalCommand.registerSubCommand("version", new VersionSubCommand()); this.portalCommand.registerSubCommand("version",
this.portalCommand.registerSubCommand("langupdate", new LangUpdateSubCommand()); new VersionSubCommand());
this.portalCommand.registerSubCommand("reload", new ReloadPortalSubCommand()); this.portalCommand.registerSubCommand("langupdate",
this.portalCommand.registerSubCommand("selector", new SelectorSubCommand(), "wand"); new LangUpdateSubCommand());
this.portalCommand.registerSubCommand("portalblock", new PortalBlockSubCommand()); this.portalCommand.registerSubCommand("reload",
this.portalCommand.registerSubCommand("endportalblock", new EndPortalBlockSubCommand()); new ReloadPortalSubCommand());
this.portalCommand.registerSubCommand("endgatewayblock", new EndGatewayBlockSubCommand()); this.portalCommand.registerSubCommand("selector",
this.portalCommand.registerSubCommand("create", new CreatePortalSubCommand()); new SelectorSubCommand(), "wand");
this.portalCommand.registerSubCommand("remove", new RemovePortalSubCommand()); this.portalCommand.registerSubCommand("portalblock",
this.portalCommand.registerSubCommand("list", new ListPortalsSubCommand()); new PortalBlockSubCommand());
this.portalCommand.registerSubCommand("show", new ShowPortalSubCommand()); this.portalCommand.registerSubCommand("endportalblock",
new EndPortalBlockSubCommand());
this.portalCommand.registerSubCommand("endgatewayblock",
new EndGatewayBlockSubCommand());
this.portalCommand.registerSubCommand("create",
new CreatePortalSubCommand());
this.portalCommand.registerSubCommand("remove",
new RemovePortalSubCommand());
this.portalCommand.registerSubCommand("list",
new ListPortalsSubCommand());
this.portalCommand.registerSubCommand("show",
new ShowPortalSubCommand());
commandRegister.registerCommand("portal", this.portalCommand); commandRegister.registerCommand("portal", this.portalCommand);
} }
private void registerDestinationCommand(CommandRegister commandRegister) { private void registerDestinationCommand(CommandRegister commandRegister) {
this.destiCommand = new CommandWithSubCommands(this); this.destiCommand = new CommandWithSubCommands(this);
this.destiCommand.registerSubCommand("create", new CreateDestiSubCommand()); this.destiCommand.registerSubCommand("create",
this.destiCommand.registerSubCommand("remove", new RemoveDestiSubCommand()); new CreateDestiSubCommand());
this.destiCommand.registerSubCommand("teleport", new TeleportDestiSubCommand(), "tp"); this.destiCommand.registerSubCommand("remove",
new RemoveDestiSubCommand());
this.destiCommand.registerSubCommand(
"teleport", new TeleportDestiSubCommand(), "tp");
this.destiCommand.registerSubCommand("list", new ListDestiSubCommand()); this.destiCommand.registerSubCommand("list", new ListDestiSubCommand());
this.destiCommand.registerSubCommand("show", new ShowDestiSubCommand()); this.destiCommand.registerSubCommand("show", new ShowDestiSubCommand());
commandRegister.registerCommand("destination", this.destiCommand); commandRegister.registerCommand("destination", this.destiCommand);
} }
public boolean registerPortalCommand(String arg, SubCommand subCommand, String... aliasArgs) { public boolean registerPortalCommand(String arg, SubCommand subCommand,
return this.portalCommand.registerSubCommand(arg, subCommand, aliasArgs); String... aliasArgs) {
return this.portalCommand.registerSubCommand(arg, subCommand,
aliasArgs);
} }
public boolean registerDestiCommand(String arg, SubCommand subCommand, String... aliasArgs) { public boolean registerDestiCommand(String arg, SubCommand subCommand,
String... aliasArgs) {
return this.destiCommand.registerSubCommand(arg, subCommand, aliasArgs); return this.destiCommand.registerSubCommand(arg, subCommand, aliasArgs);
} }
/** /**
* Loads the portal config into the memory and saves from the memory to check in case certain * Loads the portal config into the memory and saves from the memory to
* things have changed (basically if values are missing or whatever) * check in case certain things have changed (basically if values are
* missing or whatever)
*/ */
public void loadPortalConfig() { public void loadPortalConfig() {
this.configRepository.loadConfig(this.dataStorage); this.configRepository.loadConfig(this.dataStorage);

View File

@ -6,30 +6,24 @@ import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.connector.containers.WorldContainer; import com.sekwah.advancedportals.core.connector.containers.WorldContainer;
import com.sekwah.advancedportals.core.data.BlockAxis; import com.sekwah.advancedportals.core.data.BlockAxis;
import com.sekwah.advancedportals.core.data.Direction; import com.sekwah.advancedportals.core.data.Direction;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.repository.ConfigRepository; import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.services.PortalServices; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.services.PlayerDataServices; import com.sekwah.advancedportals.core.services.PlayerDataServices;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.GameScheduler; import com.sekwah.advancedportals.core.util.GameScheduler;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.Objects; import java.util.Objects;
public class CoreListeners { public class CoreListeners {
@Inject private PlayerDataServices playerDataServices;
@Inject @Inject private PortalServices portalServices;
private PlayerDataServices playerDataServices;
@Inject @Inject private ConfigRepository configRepository;
private PortalServices portalServices;
@Inject @Inject private GameScheduler gameScheduler;
private ConfigRepository configRepository;
@Inject
private GameScheduler gameScheduler;
public void playerJoin(PlayerContainer player) { public void playerJoin(PlayerContainer player) {
this.playerDataServices.setJoinCooldown(player); this.playerDataServices.setJoinCooldown(player);
@ -56,19 +50,24 @@ public class CoreListeners {
} }
/** /**
* If the block is indirectly broken it will also take null for the player e.g. with tnt * If the block is indirectly broken it will also take null for the player
* e.g. with tnt
* *
* @player player causing the event (or null if not a player) * @player player causing the event (or null if not a player)
* @param blockPos * @param blockPos
* @param blockMaterial * @param blockMaterial
* @return if the block is allowed to break * @return if the block is allowed to break
*/ */
public boolean blockBreak(PlayerContainer player, BlockLocation blockPos, String blockMaterial, String itemInHandMaterial, String itemInHandName) { public boolean blockBreak(PlayerContainer player, BlockLocation blockPos,
if(player == null) { String blockMaterial, String itemInHandMaterial,
String itemInHandName) {
if (player == null) {
return !portalServices.inPortalRegionProtected(blockPos); return !portalServices.inPortalRegionProtected(blockPos);
} }
if(!(PortalPermissions.BUILD.hasPermission(player) || !portalServices.inPortalRegionProtected(blockPos))) { if (!(PortalPermissions.BUILD.hasPermission(player)
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("portal.nobuild")); || !portalServices.inPortalRegionProtected(blockPos))) {
player.sendMessage(Lang.translate("messageprefix.negative")
+ Lang.translate("portal.nobuild"));
return false; return false;
} }
return true; return true;
@ -80,33 +79,36 @@ public class CoreListeners {
* @param blockMaterial * @param blockMaterial
* @return if the block is allowed to be placed * @return if the block is allowed to be placed
*/ */
public boolean blockPlace(PlayerContainer player, BlockLocation blockPos, String blockMaterial, String itemInHandMaterial, String itemInHandName) { public boolean blockPlace(PlayerContainer player, BlockLocation blockPos,
if(player != null && PortalPermissions.BUILD.hasPermission(player)) { String blockMaterial, String itemInHandMaterial,
String itemInHandName) {
if (player != null && PortalPermissions.BUILD.hasPermission(player)) {
WorldContainer world = player.getWorld(); WorldContainer world = player.getWorld();
if(itemInHandName.equals("\u00A75Portal Block Placer")) { if (itemInHandName.equals("\u00A75Portal Block Placer")) {
world.setBlock(blockPos, "NETHER_PORTAL"); world.setBlock(blockPos, "NETHER_PORTAL");
for (Direction direction : Direction.values()) { for (Direction direction : Direction.values()) {
var checkLoc = new BlockLocation(blockPos, direction); var checkLoc = new BlockLocation(blockPos, direction);
if (world.getBlock(checkLoc).equals("NETHER_PORTAL")) { if (world.getBlock(checkLoc).equals("NETHER_PORTAL")) {
world.setBlockAxis(blockPos, world.getBlockAxis(checkLoc)); world.setBlockAxis(blockPos,
world.getBlockAxis(checkLoc));
break; break;
} }
} }
return true; return true;
} } else if (itemInHandName.equals(
else if(itemInHandName.equals("\u00A78End Portal Block Placer")) { "\u00A78End Portal Block Placer")) {
world.setBlock(blockPos, "END_PORTAL"); world.setBlock(blockPos, "END_PORTAL");
return true; return true;
} } else if (itemInHandName.equals("\u00A78Gateway Block Placer")) {
else if(itemInHandName.equals("\u00A78Gateway Block Placer")) {
world.setBlock(blockPos, "END_GATEWAY"); world.setBlock(blockPos, "END_GATEWAY");
return true; return true;
} }
return true; return true;
} }
if(portalServices.inPortalRegionProtected(blockPos)) { if (portalServices.inPortalRegionProtected(blockPos)) {
if(player != null) { if (player != null) {
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("portal.nobuild")); player.sendMessage(Lang.translate("messageprefix.negative")
+ Lang.translate("portal.nobuild"));
} }
return false; return false;
} }
@ -119,7 +121,8 @@ public class CoreListeners {
* @param blockPos * @param blockPos
* @return * @return
*/ */
public boolean blockInteract(PlayerContainer player, BlockLocation blockPos) { public boolean blockInteract(PlayerContainer player,
BlockLocation blockPos) {
return true; return true;
} }
@ -129,25 +132,33 @@ public class CoreListeners {
* @param leftClick true = left click, false = right click * @param leftClick true = left click, false = right click
* @return if player is allowed to interact with block * @return if player is allowed to interact with block
*/ */
public boolean playerInteractWithBlock(PlayerContainer player, String blockMaterialname, String itemMaterialName, String itemName, public boolean playerInteractWithBlock(PlayerContainer player,
BlockLocation blockLoc, boolean leftClick) { String blockMaterialname,
if(itemName != null && (player.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(player)) && String itemMaterialName,
itemMaterialName.equalsIgnoreCase(this.configRepository.getSelectorMaterial()) String itemName,
&& (!this.configRepository.getUseOnlySpecialAxe() || itemName.equals("\u00A7ePortal Region Selector"))) { BlockLocation blockLoc,
this.playerDataServices.playerSelectorActivate(player, blockLoc, leftClick); boolean leftClick) {
if (itemName != null
&& (player.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(player))
&& itemMaterialName.equalsIgnoreCase(
this.configRepository.getSelectorMaterial())
&& (!this.configRepository.getUseOnlySpecialAxe()
|| itemName.equals("\u00A7ePortal Region Selector"))) {
this.playerDataServices.playerSelectorActivate(player, blockLoc,
leftClick);
return false; return false;
} } else if (itemName != null && leftClick
else if(itemName != null && leftClick && && Objects.equals(itemMaterialName, "PURPLE_WOOL")
Objects.equals(itemMaterialName, "PURPLE_WOOL") && && itemName.equals("\u00A75Portal Block Placer")
itemName.equals("\u00A75Portal Block Placer") && PortalPermissions.BUILD.hasPermission(player)) { && PortalPermissions.BUILD.hasPermission(player)) {
if(!Objects.equals(blockMaterialname, "NETHER_PORTAL")) { if (!Objects.equals(blockMaterialname, "NETHER_PORTAL")) {
return false; return false;
} }
WorldContainer world = player.getWorld(); WorldContainer world = player.getWorld();
if(world.getBlockAxis(blockLoc) == BlockAxis.X) { if (world.getBlockAxis(blockLoc) == BlockAxis.X) {
world.setBlockAxis(blockLoc, BlockAxis.Z); world.setBlockAxis(blockLoc, BlockAxis.Z);
} } else {
else {
world.setBlockAxis(blockLoc, BlockAxis.X); world.setBlockAxis(blockLoc, BlockAxis.X);
} }
return false; return false;
@ -166,14 +177,15 @@ public class CoreListeners {
public boolean entityPortalEvent(EntityContainer entity) { public boolean entityPortalEvent(EntityContainer entity) {
var pos = entity.getBlockLoc(); var pos = entity.getBlockLoc();
if(entity instanceof PlayerContainer player) { if (entity instanceof PlayerContainer player) {
var playerData = playerDataServices.getPlayerData(player); var playerData = playerDataServices.getPlayerData(player);
if(playerData.isNetherPortalCooldown()) { if (playerData.isNetherPortalCooldown()) {
return false; return false;
} }
} }
var feetInPortal = portalServices.inPortalRegion(pos, 1); var feetInPortal = portalServices.inPortalRegion(pos, 1);
var headInPortal = portalServices.inPortalRegion(pos.addY((int) entity.getHeight()), 1); var headInPortal = portalServices.inPortalRegion(
pos.addY((int) entity.getHeight()), 1);
return !(feetInPortal || headInPortal); return !(feetInPortal || headInPortal);
} }
} }

View File

@ -1,7 +1,6 @@
package com.sekwah.advancedportals.core.commands; package com.sekwah.advancedportals.core.commands;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import java.util.List; import java.util.List;
/** /**
@ -11,13 +10,14 @@ import java.util.List;
* https://docs.spongepowered.org/stable/en/plugin/commands/arguments.html#custom-command-elements * https://docs.spongepowered.org/stable/en/plugin/commands/arguments.html#custom-command-elements
*/ */
public interface CommandTemplate { public interface CommandTemplate {
void onCommand(CommandSenderContainer sender, String commandExecuted,
void onCommand(CommandSenderContainer sender, String commandExecuted, String[] args); String[] args);
/** /**
* Fired when someone asks for a tab complete action. * Fired when someone asks for a tab complete action.
* *
* @param sender whoever triggered the command e.g. command block, server or player * @param sender whoever triggered the command e.g. command block, server or
* player
* @param args arguments for the command * @param args arguments for the command
* @return a lot of strings that are possible completions * @return a lot of strings that are possible completions
*/ */

View File

@ -4,14 +4,12 @@ import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.registry.SubCommandRegistry; import com.sekwah.advancedportals.core.registry.SubCommandRegistry;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class CommandWithSubCommands implements CommandTemplate { public class CommandWithSubCommands implements CommandTemplate {
private final SubCommandRegistry subCommandRegistry; private final SubCommandRegistry subCommandRegistry;
private final int subCommandsPerPage = 7; private final int subCommandsPerPage = 7;
@ -22,128 +20,163 @@ public class CommandWithSubCommands implements CommandTemplate {
this.pluginCore = advancedPortalsCore; this.pluginCore = advancedPortalsCore;
} }
public boolean registerSubCommand(String arg, SubCommand subCommand, String... aliasArgs) { public boolean registerSubCommand(String arg, SubCommand subCommand,
String... aliasArgs) {
pluginCore.getModule().getInjector().injectMembers(subCommand); pluginCore.getModule().getInjector().injectMembers(subCommand);
boolean hasRegistered = false; boolean hasRegistered = false;
for(String additionalArg : aliasArgs) { for (String additionalArg : aliasArgs) {
hasRegistered = this.subCommandRegistry.registerSubCommand(additionalArg,subCommand) || hasRegistered; hasRegistered = this.subCommandRegistry.registerSubCommand(
additionalArg, subCommand)
|| hasRegistered;
} }
boolean result = this.subCommandRegistry.registerSubCommand(arg,subCommand) || hasRegistered; boolean result =
if(subCommand instanceof SubCommand.SubCommandOnInit init) { this.subCommandRegistry.registerSubCommand(arg, subCommand)
|| hasRegistered;
if (subCommand instanceof SubCommand.SubCommandOnInit init) {
init.registered(); init.registered();
} }
return result; return result;
} }
public ArrayList<String> getSubCommands(){ public ArrayList<String> getSubCommands() {
return this.subCommandRegistry.getSubCommands(); return this.subCommandRegistry.getSubCommands();
} }
public boolean isArgRegistered(String arg){ public boolean isArgRegistered(String arg) {
return this.subCommandRegistry.isArgRegistered(arg); return this.subCommandRegistry.isArgRegistered(arg);
} }
public SubCommand getSubCommand(String arg){ public SubCommand getSubCommand(String arg) {
return this.subCommandRegistry.getSubCommand(arg); return this.subCommandRegistry.getSubCommand(arg);
} }
@Override @Override
public void onCommand(CommandSenderContainer sender, String commandExecuted, String[] args) { public void onCommand(CommandSenderContainer sender, String commandExecuted,
if(args.length > 0) { String[] args) {
if(args[0].equalsIgnoreCase("help")) { if (args.length > 0) {
if (args[0].equalsIgnoreCase("help")) {
int helpPage = 1; int helpPage = 1;
String[] subCommands = this.subCommandRegistry.getSubCommands().toArray(new String[0]); String[] subCommands =
int pages = (int) Math.ceil(subCommands.length / (float) this.subCommandsPerPage); this.subCommandRegistry.getSubCommands().toArray(
String command = commandExecuted.substring(0, 1).toUpperCase() + commandExecuted.substring(1).toLowerCase(); new String[0]);
if(args.length > 1) { int pages = (int) Math.ceil(subCommands.length
/ (float) this.subCommandsPerPage);
String command = commandExecuted.substring(0, 1).toUpperCase()
+ commandExecuted.substring(1).toLowerCase();
if (args.length > 1) {
try { try {
helpPage = Integer.parseInt(args[1]); helpPage = Integer.parseInt(args[1]);
if(helpPage > pages) { if (helpPage > pages) {
helpPage = pages; helpPage = pages;
} }
if(helpPage <= 0) { if (helpPage <= 0) {
helpPage = 1; helpPage = 1;
} }
} } catch (NumberFormatException e) {
catch(NumberFormatException e) {
String subCommand = args[1].toLowerCase(); String subCommand = args[1].toLowerCase();
if(this.subCommandRegistry.isArgRegistered(subCommand)) { if (this.subCommandRegistry.isArgRegistered(
subCommand)) {
sender.sendMessage(""); sender.sendMessage("");
var helpTitle = Lang.centeredTitle(Lang.translateInsertVariables("command.help.subcommandheader", var helpTitle = Lang.centeredTitle(
command, subCommand)); Lang.translateInsertVariables(
"command.help.subcommandheader", command,
subCommand));
sender.sendMessage(helpTitle); sender.sendMessage(helpTitle);
sender.sendMessage("\u00A77" + this.getSubCommand(subCommand).getDetailedHelpText()); sender.sendMessage("\u00A77"
} + this.getSubCommand(subCommand)
else { .getDetailedHelpText());
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translateInsertVariables("command.help.invalidhelp", args[1])); } else {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translateInsertVariables(
"command.help.invalidhelp", args[1]));
} }
return; return;
} }
} }
sender.sendMessage(""); sender.sendMessage("");
var helpTitle = Lang.centeredTitle(Lang.translateInsertVariables("command.help.header", var helpTitle =
command, helpPage, pages)); Lang.centeredTitle(Lang.translateInsertVariables(
"command.help.header", command, helpPage, pages));
sender.sendMessage(helpTitle); sender.sendMessage(helpTitle);
sender.sendMessage("\u00A7a█\u00A77 = Permission \u00A7c█\u00A77 = No Permission"); sender.sendMessage(
"\u00A7a█\u00A77 = Permission \u00A7c█\u00A77 "
+ "= No Permission");
int subCommandOffset = (helpPage - 1) * this.subCommandsPerPage; int subCommandOffset = (helpPage - 1) * this.subCommandsPerPage;
int displayEnd = subCommandOffset + this.subCommandsPerPage; int displayEnd = subCommandOffset + this.subCommandsPerPage;
if(displayEnd > subCommands.length) { if (displayEnd > subCommands.length) {
displayEnd = subCommands.length; displayEnd = subCommands.length;
} }
for(; subCommandOffset < displayEnd; subCommandOffset++) { for (; subCommandOffset < displayEnd; subCommandOffset++) {
SubCommand subCommand = this.getSubCommand(subCommands[subCommandOffset]); SubCommand subCommand =
String colorCode = "\u00A7" + (subCommand.hasPermission(sender) ? "a" : "c"); this.getSubCommand(subCommands[subCommandOffset]);
sender.sendMessage("\u00A7e/" + commandExecuted + " " + subCommands[subCommandOffset] String colorCode = "\u00A7"
+ colorCode + " - " + subCommand.getBasicHelpText()); + (subCommand.hasPermission(sender) ? "a" : "c");
sender.sendMessage("\u00A7e/" + commandExecuted + " "
+ subCommands[subCommandOffset]
+ colorCode + " - "
+ subCommand.getBasicHelpText());
} }
} } else {
else { for (String subCommandName :
for(String subCommandName : this.subCommandRegistry.getSubCommands()) { this.subCommandRegistry.getSubCommands()) {
if(subCommandName.equalsIgnoreCase(args[0])) { if (subCommandName.equalsIgnoreCase(args[0])) {
SubCommand subCommand = this.getSubCommand(subCommandName); SubCommand subCommand =
if(subCommand.hasPermission(sender)) { this.getSubCommand(subCommandName);
if (subCommand.hasPermission(sender)) {
subCommand.onCommand(sender, args); subCommand.onCommand(sender, args);
} } else {
else { sender.sendMessage(
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translateInsertVariables("command.subcommand.nopermission", Lang.translate("messageprefix.negative")
+ Lang.translateInsertVariables(
"command.subcommand.nopermission",
commandExecuted)); commandExecuted));
} }
return; return;
} }
} }
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.subcommand.invalid")); sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.subcommand.invalid"));
} }
} } else {
else { sender.sendMessage(Lang.translate("messageprefix.negative")
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translateInsertVariables("command.noargs", commandExecuted)); + Lang.translateInsertVariables(
"command.noargs", commandExecuted));
} }
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
if(args.length > 1) { String[] args) {
if(args[0].equalsIgnoreCase("help")) { if (args.length > 1) {
List<String> allowedCommands = new ArrayList<>(this.subCommandRegistry.getSubCommands()); if (args[0].equalsIgnoreCase("help")) {
int pages = (int) Math.ceil(allowedCommands.size() / (float) this.subCommandsPerPage); List<String> allowedCommands =
new ArrayList<>(this.subCommandRegistry.getSubCommands());
int pages = (int) Math.ceil(allowedCommands.size()
/ (float) this.subCommandsPerPage);
for (int i = 1; i <= pages; i++) { for (int i = 1; i <= pages; i++) {
allowedCommands.add(String.valueOf(i)); allowedCommands.add(String.valueOf(i));
} }
Collections.sort(allowedCommands); Collections.sort(allowedCommands);
return this.filterTabResults(allowedCommands, args[args.length - 1]); return this.filterTabResults(allowedCommands,
} args[args.length - 1]);
else { } else {
for (String subCommandName : this.subCommandRegistry.getSubCommands()) { for (String subCommandName :
this.subCommandRegistry.getSubCommands()) {
if (subCommandName.equalsIgnoreCase(args[0])) { if (subCommandName.equalsIgnoreCase(args[0])) {
SubCommand subCommand = this.getSubCommand(subCommandName); SubCommand subCommand =
this.getSubCommand(subCommandName);
if (subCommand.hasPermission(sender)) { if (subCommand.hasPermission(sender)) {
List<String> tabComplete = this.filterTabResults(this.getSubCommand(subCommandName).onTabComplete(sender, args), List<String> tabComplete = this.filterTabResults(
args[args.length - 1]); this.getSubCommand(subCommandName)
if(tabComplete != null) { .onTabComplete(sender, args),
args[args.length - 1]);
if (tabComplete != null) {
return tabComplete; return tabComplete;
} } else {
else {
return Collections.emptyList(); return Collections.emptyList();
} }
} else { } else {
@ -152,12 +185,12 @@ public class CommandWithSubCommands implements CommandTemplate {
} }
} }
} }
} } else {
else {
List<String> allowedCommands = new ArrayList<>(); List<String> allowedCommands = new ArrayList<>();
for (String subCommandName : this.subCommandRegistry.getSubCommands()) { for (String subCommandName :
this.subCommandRegistry.getSubCommands()) {
SubCommand subCommand = this.getSubCommand(subCommandName); SubCommand subCommand = this.getSubCommand(subCommandName);
if(subCommand.hasPermission(sender)) { if (subCommand.hasPermission(sender)) {
allowedCommands.add(subCommandName); allowedCommands.add(subCommandName);
} }
} }
@ -169,11 +202,11 @@ public class CommandWithSubCommands implements CommandTemplate {
} }
public List<String> filterTabResults(List<String> tabList, String lastArg) { public List<String> filterTabResults(List<String> tabList, String lastArg) {
if(tabList == null) { if (tabList == null) {
return null; return null;
} }
return tabList.stream() return tabList.stream()
.filter(arg -> arg.startsWith(lastArg)) .filter(arg -> arg.startsWith(lastArg))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }

View File

@ -1,16 +1,14 @@
package com.sekwah.advancedportals.core.commands; package com.sekwah.advancedportals.core.commands;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import java.util.List; import java.util.List;
public interface SubCommand { public interface SubCommand {
/** /**
* @param sender * @param sender
* @param args arguments including the subcommand that has been specified. * @param args arguments including the subcommand that has been specified.
* @return if the command has worked (if false it will just display a message from the command * @return if the command has worked (if false it will just display a
* suggesting to check help) * message from the command suggesting to check help)
*/ */
void onCommand(CommandSenderContainer sender, String[] args); void onCommand(CommandSenderContainer sender, String[] args);

View File

@ -5,7 +5,6 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.serializeddata.DataTag; import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.util.TagReader; import com.sekwah.advancedportals.core.util.TagReader;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -13,34 +12,36 @@ import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public abstract class CreateTaggedSubCommand implements SubCommand { public abstract class CreateTaggedSubCommand implements SubCommand {
protected abstract List<Tag> getRelatedTags(); protected abstract List<Tag> getRelatedTags();
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
if(TagReader.isClosedString(args)) { if (TagReader.isClosedString(args)) {
return List.of(); return List.of();
} }
List<Tag> allTags = this.getRelatedTags(); List<Tag> allTags = this.getRelatedTags();
List<String> suggestions = new ArrayList<>(); List<String> suggestions = new ArrayList<>();
if(args.length > 0) { if (args.length > 0) {
var lastArg = args[args.length - 1]; var lastArg = args[args.length - 1];
// Check if the split results in exactly 2 or if its 1 and ends with : // Check if the split results in exactly 2 or if its 1 and ends
// with :
var split = lastArg.split(":"); var split = lastArg.split(":");
if(split.length == 2 || (split.length == 1 && lastArg.endsWith(":"))) { if (split.length == 2
// Loop over tags in allTags and check if the first half of split is equal to the tag name or alias || (split.length == 1 && lastArg.endsWith(":"))) {
for(Tag tag : allTags) { // Loop over tags in allTags and check if the first half of
// split is equal to the tag name or alias
for (Tag tag : allTags) {
// Check if the last tag starts with the tag name or alias // Check if the last tag starts with the tag name or alias
var startsWith = false; var startsWith = false;
if(lastArg.startsWith(tag.getName())) { if (lastArg.startsWith(tag.getName())) {
startsWith = true; startsWith = true;
} else { } else {
var aliases = tag.getAliases(); var aliases = tag.getAliases();
if(aliases != null) { if (aliases != null) {
for (String alias : aliases) { for (String alias : aliases) {
if(lastArg.startsWith(alias)) { if (lastArg.startsWith(alias)) {
startsWith = true; startsWith = true;
break; break;
} }
@ -48,33 +49,52 @@ public abstract class CreateTaggedSubCommand implements SubCommand {
} }
} }
if(tag instanceof Tag.AutoComplete autoComplete && startsWith) { if (tag instanceof Tag.AutoComplete autoComplete
&& startsWith) {
var argData = split.length == 2 ? split[1] : ""; var argData = split.length == 2 ? split[1] : "";
var tagSuggestions = autoComplete.autoComplete(argData); var tagSuggestions = autoComplete.autoComplete(argData);
if(tagSuggestions != null) { if (tagSuggestions != null) {
if(tag instanceof Tag.Split splitTag) { if (tag instanceof Tag.Split splitTag) {
var multiTagSplit = splitTag.splitString(); var multiTagSplit = splitTag.splitString();
boolean endsWithSplit = argData.endsWith(multiTagSplit); boolean endsWithSplit =
argData.endsWith(multiTagSplit);
String[] items = argData.split(multiTagSplit); String[] items = argData.split(multiTagSplit);
Set<String> existingItems = Arrays.stream(items, 0, endsWithSplit ? items.length : items.length - 1) Set<String> existingItems =
Arrays
.stream(items, 0,
endsWithSplit
? items.length
: items.length - 1)
.map(String::trim) .map(String::trim)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
String partialInput = endsWithSplit ? "" : items[items.length - 1].trim(); String partialInput = endsWithSplit
String baseString = endsWithSplit ? argData : argData.substring(0, argData.lastIndexOf(multiTagSplit) + 1); ? ""
: items[items.length - 1].trim();
String baseString = endsWithSplit
? argData
: argData.substring(
0,
argData.lastIndexOf(multiTagSplit)
+ 1);
tagSuggestions = tagSuggestions.stream() tagSuggestions =
tagSuggestions
.stream()
// Remove already listed items // Remove already listed items
.filter(s -> !existingItems.contains(s)) .filter(s -> !existingItems.contains(s))
// Remove items that don't match the currently typed input // Remove items that don't match the
// currently typed input
.filter(s -> s.startsWith(partialInput)) .filter(s -> s.startsWith(partialInput))
// Remap so the auto completes actually show // Remap so the auto completes actually
// show
.map(s -> baseString + s) .map(s -> baseString + s)
.toList(); .toList();
} }
// Loop over suggestions and add split[0] + ":" to the start // Loop over suggestions and add split[0] + ":" to
// the start
for (String tagSuggestion : tagSuggestions) { for (String tagSuggestion : tagSuggestions) {
suggestions.add(split[0] + ":" + tagSuggestion); suggestions.add(split[0] + ":" + tagSuggestion);
} }
@ -88,28 +108,30 @@ public abstract class CreateTaggedSubCommand implements SubCommand {
ArrayList<DataTag> tagsFromArgs = TagReader.getTagsFromArgs(args); ArrayList<DataTag> tagsFromArgs = TagReader.getTagsFromArgs(args);
allTags.stream().filter(tag -> { allTags.stream()
for (DataTag argTag : tagsFromArgs) { .filter(tag -> {
if(argTag.NAME.equals(tag.getName())) { for (DataTag argTag : tagsFromArgs) {
return false; if (argTag.NAME.equals(tag.getName())) {
} return false;
var aliases = tag.getAliases(); }
if(aliases != null) { var aliases = tag.getAliases();
for (String alias : aliases) { if (aliases != null) {
if(argTag.NAME.equals(alias)) { for (String alias : aliases) {
return false; if (argTag.NAME.equals(alias)) {
return false;
}
} }
} }
} }
} return true;
return true; })
}).forEach(tag -> { .forEach(tag -> {
suggestions.add(tag.getName()); suggestions.add(tag.getName());
var aliases = tag.getAliases(); var aliases = tag.getAliases();
if(aliases != null) { if (aliases != null) {
suggestions.addAll(Arrays.stream(aliases).toList()); suggestions.addAll(Arrays.stream(aliases).toList());
} }
}); });
// Loop over all suggestions and add : to the end // Loop over all suggestions and add : to the end
for (int i = 0; i < suggestions.size(); i++) { for (int i = 0; i < suggestions.size(); i++) {
@ -125,24 +147,34 @@ public abstract class CreateTaggedSubCommand implements SubCommand {
for (var dataTag : dataTags) { for (var dataTag : dataTags) {
for (Tag tag : relatedTags) { for (Tag tag : relatedTags) {
if(tag instanceof Tag.Split splitTag) { if (tag instanceof Tag.Split splitTag) {
var splitString = splitTag.splitString(); var splitString = splitTag.splitString();
if(splitString != null) { if (splitString != null) {
List<String> newValues = new ArrayList<>(); List<String> newValues = new ArrayList<>();
for(String split : dataTag.VALUES) { for (String split : dataTag.VALUES) {
newValues.addAll(Arrays.stream(split.split(splitString)).map(String::trim).toList()); newValues.addAll(
Arrays.stream(split.split(splitString))
.map(String::trim)
.toList());
} }
dataTag = new DataTag(dataTag.NAME, newValues.toArray(new String[0])); dataTag = new DataTag(dataTag.NAME,
newValues.toArray(new String[0]));
} }
} }
if (dataTag.NAME.equals(tag.getName())) { if (dataTag.NAME.equals(tag.getName())) {
// DataTag name matches the tag's main name, add as is // DataTag name matches the tag's main name, add as is
processedTags.add(dataTag); processedTags.add(dataTag);
break; break;
} else if (tag.getAliases() != null && Arrays.asList(tag.getAliases()).contains(dataTag.NAME)) { } else if (tag.getAliases() != null
// There is currently an edge case where if someone uses multiple aliases or names for tags at the same time, it'll only use the last one applied to the mapping. && Arrays.asList(tag.getAliases())
// DataTag name matches an alias, create a new DataTag with the main name .contains(dataTag.NAME)) {
processedTags.add(new DataTag(tag.getName(), dataTag.VALUES)); // There is currently an edge case where if someone uses
// multiple aliases or names for tags at the same time,
// it'll only use the last one applied to the mapping.
// DataTag name matches an alias, create a new DataTag with
// the main name
processedTags.add(
new DataTag(tag.getName(), dataTag.VALUES));
break; break;
} }
} }
@ -153,24 +185,26 @@ public abstract class CreateTaggedSubCommand implements SubCommand {
dataTags.addAll(processedTags); dataTags.addAll(processedTags);
// Sort the tags by name however make sure name is first // Sort the tags by name however make sure name is first
dataTags.sort((o1, o2) -> { dataTags.sort((o1, o2) -> {
if(o1.NAME.equals("name")) { if (o1.NAME.equals("name")) {
return -1; return -1;
} }
if(o2.NAME.equals("name")) { if (o2.NAME.equals("name")) {
return 1; return 1;
} }
return o1.NAME.compareTo(o2.NAME); return o1.NAME.compareTo(o2.NAME);
}); });
} }
protected void printTags(CommandSenderContainer sender,
protected void printTags(CommandSenderContainer sender, List<DataTag> dataTags) { List<DataTag> dataTags) {
for (DataTag tag : dataTags) { for (DataTag tag : dataTags) {
if(tag.VALUES.length == 1) { if (tag.VALUES.length == 1) {
sender.sendMessage(" \u00A7a" + tag.NAME + "\u00A77:\u00A7e" + tag.VALUES[0]); sender.sendMessage(" \u00A7a" + tag.NAME + "\u00A77:\u00A7e"
+ tag.VALUES[0]);
} else { } else {
for (int i = 0; i < tag.VALUES.length; i++) { for (int i = 0; i < tag.VALUES.length; i++) {
sender.sendMessage(" \u00A7a" + tag.NAME + "\u00A77[" + i + "]:\u00A7e" + tag.VALUES[i]); sender.sendMessage(" \u00A7a" + tag.NAME + "\u00A77[" + i
+ "]:\u00A7e" + tag.VALUES[i]);
} }
} }
} }

View File

@ -12,13 +12,11 @@ import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.util.TagReader; import com.sekwah.advancedportals.core.util.TagReader;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class CreateDestiSubCommand extends CreateTaggedSubCommand { public class CreateDestiSubCommand extends CreateTaggedSubCommand {
@Inject TagRegistry tagRegistry; @Inject TagRegistry tagRegistry;
@Inject DestinationServices destinationServices; @Inject DestinationServices destinationServices;
@ -29,34 +27,34 @@ public class CreateDestiSubCommand extends CreateTaggedSubCommand {
PlayerContainer player = sender.getPlayerContainer(); PlayerContainer player = sender.getPlayerContainer();
if (player == null) { if (player == null) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.create.destination.console")); + Lang.translate("command.create.destination.console"));
return; return;
} }
ArrayList<DataTag> destinationTags = TagReader.getTagsFromArgs(args); ArrayList<DataTag> destinationTags =
TagReader.getTagsFromArgs(args);
// Find the tag with the "name" NAME // Find the tag with the "name" NAME
DataTag nameTag = DataTag nameTag = destinationTags.stream()
destinationTags.stream() .filter(tag -> tag.NAME.equals("name"))
.filter(tag -> tag.NAME.equals("name")) .findFirst()
.findFirst() .orElse(null);
.orElse(null);
// If the tag is null, check if arg[1] has a : to check it's not a tag. // If the tag is null, check if arg[1] has a : to check it's not a
// tag.
if (nameTag == null && !args[1].contains(":")) { if (nameTag == null && !args[1].contains(":")) {
nameTag = new DataTag("name", args[1]); nameTag = new DataTag("name", args[1]);
destinationTags.add(nameTag); destinationTags.add(nameTag);
} }
if (nameTag == null) { if (nameTag == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
+ Lang.translate("command.error.noname"));
return; return;
} }
sender.sendMessage( sender.sendMessage(Lang.centeredTitle(
Lang.centeredTitle(Lang.translate("command.create.destination.prep"))); Lang.translate("command.create.destination.prep")));
sender.sendMessage(""); sender.sendMessage("");
sender.sendMessage(Lang.translate("command.create.tags")); sender.sendMessage(Lang.translate("command.create.tags"));
@ -65,22 +63,21 @@ public class CreateDestiSubCommand extends CreateTaggedSubCommand {
this.printTags(sender, destinationTags); this.printTags(sender, destinationTags);
} }
sender.sendMessage(""); sender.sendMessage("");
Destination destination = Destination destination = destinationServices.createDesti(
destinationServices.createDesti(player, player.getLoc(), destinationTags); player, player.getLoc(), destinationTags);
if (destination != null) { if (destination != null) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.create.destination.complete")); + Lang.translate("command.create.destination.complete"));
} else { } else {
sender.sendMessage(""); sender.sendMessage("");
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.create.destination.error")); + Lang.translate("command.create.destination.error"));
} }
} else { } else {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
+ Lang.translate("command.error.noname"));
} }
} }
@ -94,8 +91,10 @@ public class CreateDestiSubCommand extends CreateTaggedSubCommand {
var tags = tagRegistry.getTags(); var tags = tagRegistry.getTags();
// Filter tags that support Destination // Filter tags that support Destination
return tags.stream() return tags.stream()
.filter(tag -> Arrays.asList(tag.getTagTypes()).contains(Tag.TagType.DESTINATION)) .filter(tag
.toList(); -> Arrays.asList(tag.getTagTypes())
.contains(Tag.TagType.DESTINATION))
.toList();
} }
@Override @Override

View File

@ -5,23 +5,19 @@ import com.sekwah.advancedportals.core.commands.SubCommand;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.services.DestinationServices; import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ListDestiSubCommand implements SubCommand { public class ListDestiSubCommand implements SubCommand {
@Inject DestinationServices portalServices; @Inject DestinationServices portalServices;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.list") + Lang.translate("command.destination.list") + " "
+ " " + portalServices.getDestinationNames().stream().sorted().collect(
+ portalServices.getDestinationNames().stream() Collectors.joining(", ")));
.sorted()
.collect(Collectors.joining(", ")));
} }
@Override @Override
@ -30,7 +26,8 @@ public class ListDestiSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -6,25 +6,24 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.services.DestinationServices; import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class RemoveDestiSubCommand implements SubCommand { public class RemoveDestiSubCommand implements SubCommand {
@Inject DestinationServices destinationServices; @Inject DestinationServices destinationServices;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (args.length > 1) { if (args.length > 1) {
if (destinationServices.removeDestination(args[1], sender.getPlayerContainer())) { if (destinationServices.removeDestination(
args[1], sender.getPlayerContainer())) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.remove.complete")); + Lang.translate("command.destination.remove.complete"));
} else { } else {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.remove.error")); + Lang.translate("command.destination.remove.error"));
} }
} else { } else {
sender.sendMessage(Lang.translate("command.destination.noname")); sender.sendMessage(Lang.translate("command.destination.noname"));
@ -37,7 +36,8 @@ public class RemoveDestiSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
if (args.length > 2) { if (args.length > 2) {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -13,17 +13,16 @@ import com.sekwah.advancedportals.core.services.PlayerDataServices;
import com.sekwah.advancedportals.core.util.Debug; import com.sekwah.advancedportals.core.util.Debug;
import com.sekwah.advancedportals.core.util.GameScheduler; import com.sekwah.advancedportals.core.util.GameScheduler;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.awt.*; import java.awt.*;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
/** /**
* This will be different from the old show command and I believe it is 1.16+ till the latest * This will be different from the old show command and I believe it is 1.16+
* version as of writing this. * till the latest version as of writing this.
*/ */
public class ShowDestiSubCommand implements SubCommand, SubCommand.SubCommandOnInit { public class ShowDestiSubCommand
implements SubCommand, SubCommand.SubCommandOnInit {
@Inject PlayerDataServices tempDataServices; @Inject PlayerDataServices tempDataServices;
@Inject GameScheduler gameScheduler; @Inject GameScheduler gameScheduler;
@ -40,20 +39,21 @@ public class ShowDestiSubCommand implements SubCommand, SubCommand.SubCommandOnI
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (core.getMcVersion()[1] < 16) { if (core.getMcVersion()[1] < 16) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.show.unsupported")); + Lang.translate("command.portal.show.unsupported"));
return; return;
} }
var tempData = tempDataServices.getPlayerData(sender.getPlayerContainer()); var tempData =
tempDataServices.getPlayerData(sender.getPlayerContainer());
if (tempData.isDestiVisible()) { if (tempData.isDestiVisible()) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.show.disabled")); + Lang.translate("command.destination.show.disabled"));
} else { } else {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.show.enabled")); + Lang.translate("command.destination.show.enabled"));
} }
tempData.setDestiVisible(!tempData.isDestiVisible()); tempData.setDestiVisible(!tempData.isDestiVisible());
} }
@ -64,7 +64,8 @@ public class ShowDestiSubCommand implements SubCommand, SubCommand.SubCommandOnI
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }
@ -80,30 +81,26 @@ public class ShowDestiSubCommand implements SubCommand, SubCommand.SubCommandOnI
@Override @Override
public void registered() { public void registered() {
gameScheduler.intervalTickEvent( gameScheduler.intervalTickEvent("show_portal", () -> {
"show_portal", for (PlayerContainer player : serverContainer.getPlayers()) {
() -> { var tempData = tempDataServices.getPlayerData(player);
for (PlayerContainer player : serverContainer.getPlayers()) { if (!tempData.isDestiVisible()) {
var tempData = tempDataServices.getPlayerData(player); continue;
if (!tempData.isDestiVisible()) { }
continue;
}
for (Destination destination : destinationServices.getDestinations()) { for (Destination destination :
var pos = destination.getLoc(); destinationServices.getDestinations()) {
if (Objects.equals(pos.getWorldName(), player.getWorldName()) var pos = destination.getLoc();
&& pos.distanceTo(player.getLoc()) < config.getVisibleRange()) { if (Objects.equals(pos.getWorldName(),
Debug.addMarker( player.getWorldName())
player, && pos.distanceTo(player.getLoc())
pos.toBlockPos(), < config.getVisibleRange()) {
Debug.addMarker(player, pos.toBlockPos(),
destination.getArgValues("name")[0], destination.getArgValues("name")[0],
new Color(100, 100, 100, 100), new Color(100, 100, 100, 100), 1300);
1300);
}
}
} }
}, }
1, }
20); }, 1, 20);
} }
} }

View File

@ -6,27 +6,26 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.services.DestinationServices; import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class TeleportDestiSubCommand implements SubCommand { public class TeleportDestiSubCommand implements SubCommand {
@Inject DestinationServices destinationServices; @Inject DestinationServices destinationServices;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (args.length > 1) { if (args.length > 1) {
if (destinationServices.teleportToDestination(args[1], sender.getPlayerContainer())) { if (destinationServices.teleportToDestination(
args[1], sender.getPlayerContainer())) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.teleport.success") + Lang.translate("command.destination.teleport.success")
.replaceAll("@destiname", args[1])); .replaceAll("@destiname", args[1]));
} else { } else {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.teleport.error") + Lang.translate("command.destination.teleport.error")
.replaceAll("@destiname", args[1])); .replaceAll("@destiname", args[1]));
} }
} else { } else {
sender.sendMessage(Lang.translate("command.destination.noname")); sender.sendMessage(Lang.translate("command.destination.noname"));
@ -39,7 +38,8 @@ public class TeleportDestiSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
if (args.length > 2) { if (args.length > 2) {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -16,13 +16,11 @@ import com.sekwah.advancedportals.core.util.InfoLogger;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.util.TagReader; import com.sekwah.advancedportals.core.util.TagReader;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class CreatePortalSubCommand extends CreateTaggedSubCommand { public class CreatePortalSubCommand extends CreateTaggedSubCommand {
@Inject PortalServices portalServices; @Inject PortalServices portalServices;
@Inject TagRegistry tagRegistry; @Inject TagRegistry tagRegistry;
@ -36,9 +34,8 @@ public class CreatePortalSubCommand extends CreateTaggedSubCommand {
if (args.length > 1) { if (args.length > 1) {
PlayerContainer player = sender.getPlayerContainer(); PlayerContainer player = sender.getPlayerContainer();
if (player == null) { if (player == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.create.console"));
+ Lang.translate("command.create.console"));
return; return;
} }
@ -46,31 +43,31 @@ public class CreatePortalSubCommand extends CreateTaggedSubCommand {
// Find the tag with the "name" NAME // Find the tag with the "name" NAME
DataTag nameTag = DataTag nameTag =
portalTags.stream() portalTags.stream()
.filter( .filter(tag -> {
tag -> { this.infoLogger.info("Tag: " + tag.NAME);
this.infoLogger.info("Tag: " + tag.NAME); this.infoLogger.info(
this.infoLogger.info( "Equals: " + tag.NAME.equals(NameTag.TAG_NAME));
"Equals: " + tag.NAME.equals(NameTag.TAG_NAME)); return tag.NAME.equals(NameTag.TAG_NAME);
return tag.NAME.equals(NameTag.TAG_NAME); })
}) .findFirst()
.findFirst() .orElse(null);
.orElse(null);
// If the tag is null, check if arg[1] has a : to check it's not a tag. // If the tag is null, check if arg[1] has a : to check it's not a
// tag.
if (nameTag == null && !args[1].contains(":")) { if (nameTag == null && !args[1].contains(":")) {
nameTag = new DataTag("name", args[1]); nameTag = new DataTag("name", args[1]);
portalTags.add(nameTag); portalTags.add(nameTag);
} }
if (nameTag == null) { if (nameTag == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
+ Lang.translate("command.error.noname"));
return; return;
} }
sender.sendMessage(Lang.centeredTitle(Lang.translate("command.create.portal.prep"))); sender.sendMessage(Lang.centeredTitle(
Lang.translate("command.create.portal.prep")));
sender.sendMessage(""); sender.sendMessage("");
sender.sendMessage(Lang.translate("command.create.tags")); sender.sendMessage(Lang.translate("command.create.tags"));
@ -81,38 +78,37 @@ public class CreatePortalSubCommand extends CreateTaggedSubCommand {
sender.sendMessage(""); sender.sendMessage("");
var triggerBlockTag = var triggerBlockTag =
portalTags.stream() portalTags.stream()
.filter(tag -> tag.NAME.equals(TriggerBlockTag.TAG_NAME)) .filter(tag -> tag.NAME.equals(TriggerBlockTag.TAG_NAME))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
if (triggerBlockTag == null) { if (triggerBlockTag == null) {
portalTags.add( portalTags.add(new DataTag(TriggerBlockTag.TAG_NAME,
new DataTag(TriggerBlockTag.TAG_NAME, config.getDefaultTriggerBlock())); config.getDefaultTriggerBlock()));
} }
AdvancedPortal portal = portalServices.createPortal(player, portalTags); AdvancedPortal portal =
portalServices.createPortal(player, portalTags);
if (portal != null) { if (portal != null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.positive")
Lang.translate("messageprefix.positive") + Lang.translate("command.create.complete"));
+ Lang.translate("command.create.complete"));
sender.sendMessage(Lang.translate("command.create.tags")); sender.sendMessage(Lang.translate("command.create.tags"));
this.printTags(sender, portal.getArgs()); this.printTags(sender, portal.getArgs());
} else { } else {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.create.error"));
+ Lang.translate("command.create.error"));
} }
} else { } else {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.error.notags"));
+ Lang.translate("command.error.notags"));
} }
} }
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(sender); return sender.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(sender);
} }
@Override @Override
@ -120,8 +116,10 @@ public class CreatePortalSubCommand extends CreateTaggedSubCommand {
var tags = tagRegistry.getTags(); var tags = tagRegistry.getTags();
// Filter tags that support Destination // Filter tags that support Destination
return tags.stream() return tags.stream()
.filter(tag -> Arrays.asList(tag.getTagTypes()).contains(Tag.TagType.PORTAL)) .filter(tag
.toList(); -> Arrays.asList(tag.getTagTypes())
.contains(Tag.TagType.PORTAL))
.toList();
} }
@Override @Override

View File

@ -7,39 +7,36 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class EndGatewayBlockSubCommand implements SubCommand { public class EndGatewayBlockSubCommand implements SubCommand {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer(); PlayerContainer player = sender.getPlayerContainer();
if (player == null) { if (player == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
+ Lang.translate("command.playeronly"));
} else { } else {
player.giveItem( player.giveItem(
"BLACK_WOOL", "BLACK_WOOL", "\u00A78Gateway Block Placer",
"\u00A78Gateway Block Placer", "\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A77This wool is made of a magical substance", "\u00A7r\u00A7eRight Click\u00A77: Place portal block");
"\u00A7r\u00A7eRight Click\u00A77: Place portal block"); sender.sendMessage(Lang.translate("messageprefix.positive")
sender.sendMessage( + Lang.translate("command.gatewayblock"));
Lang.translate("messageprefix.positive")
+ Lang.translate("command.gatewayblock"));
} }
} }
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(sender); return sender.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(sender);
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -7,39 +7,36 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class EndPortalBlockSubCommand implements SubCommand { public class EndPortalBlockSubCommand implements SubCommand {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer(); PlayerContainer player = sender.getPlayerContainer();
if (player == null) { if (player == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
+ Lang.translate("command.playeronly"));
} else { } else {
player.giveItem( player.giveItem(
"BLACK_WOOL", "BLACK_WOOL", "\u00A78End Portal Block Placer",
"\u00A78End Portal Block Placer", "\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A77This wool is made of a magical substance", "\u00A7r\u00A7eRight Click\u00A77: Place portal block");
"\u00A7r\u00A7eRight Click\u00A77: Place portal block"); sender.sendMessage(Lang.translate("messageprefix.positive")
sender.sendMessage( + Lang.translate("command.endportalblock"));
Lang.translate("messageprefix.positive")
+ Lang.translate("command.endportalblock"));
} }
} }
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(sender); return sender.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(sender);
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -7,7 +7,6 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.repository.ConfigRepository; import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
@ -18,76 +17,76 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class LangUpdateSubCommand implements SubCommand { public class LangUpdateSubCommand implements SubCommand {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@Inject private ConfigRepository configRepository; @Inject private ConfigRepository configRepository;
public LangUpdateSubCommand() {} public LangUpdateSubCommand() {
}
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (args.length > 1 && args[1].equalsIgnoreCase("overwrite")) { if (args.length > 1 && args[1].equalsIgnoreCase("overwrite")) {
this.portalsCore this.portalsCore.getDataStorage().copyDefaultFile(
.getDataStorage() "lang/" + configRepository.getTranslation() + ".lang", true);
.copyDefaultFile("lang/" + configRepository.getTranslation() + ".lang", true); sender.sendMessage(Lang.translate("messageprefix.positive")
sender.sendMessage( + Lang.translate("translatedata.replaced"));
Lang.translate("messageprefix.positive")
+ Lang.translate("translatedata.replaced"));
Lang.loadLanguage(configRepository.getTranslation()); Lang.loadLanguage(configRepository.getTranslation());
} else { } else {
// TODO check what keys are missing and append them to the end of the file, check the // TODO check what keys are missing and append them to the end of
// translation first then GB // the file, check the translation first then GB
Lang lang = Lang.instance; Lang lang = Lang.instance;
Map<String, String> internalTranslation = Map<String, String> internalTranslation =
lang.getInternalLanguageMap(Lang.DEFAULT_LANG); lang.getInternalLanguageMap(Lang.DEFAULT_LANG);
internalTranslation.putAll( internalTranslation.putAll(
lang.getInternalLanguageMap(configRepository.getTranslation())); lang.getInternalLanguageMap(configRepository.getTranslation()));
Map<String, String> currentTranslation = Map<String, String> currentTranslation =
lang.getLanguageMap(configRepository.getTranslation()); lang.getLanguageMap(configRepository.getTranslation());
// Remove everything to leave just the missing keys // Remove everything to leave just the missing keys
for (Map.Entry<String, String> entry : currentTranslation.entrySet()) { for (Map.Entry<String, String> entry :
currentTranslation.entrySet()) {
internalTranslation.remove(entry.getKey()); internalTranslation.remove(entry.getKey());
} }
List<String> newTranslations = new ArrayList<>(); List<String> newTranslations = new ArrayList<>();
for (Map.Entry<String, String> entry : internalTranslation.entrySet()) { for (Map.Entry<String, String> entry :
internalTranslation.entrySet()) {
newTranslations.add(entry.getKey() + "=" + entry.getValue()); newTranslations.add(entry.getKey() + "=" + entry.getValue());
} }
String appendText = String.join("\n", newTranslations); String appendText = String.join("\n", newTranslations);
InputStream translationFile = InputStream translationFile =
this.portalsCore this.portalsCore.getDataStorage().loadResource(
.getDataStorage() "lang/" + configRepository.getTranslation() + ".lang");
.loadResource("lang/" + configRepository.getTranslation() + ".lang");
String result = String result =
new BufferedReader(new InputStreamReader(translationFile)) new BufferedReader(new InputStreamReader(translationFile))
.lines() .lines()
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
InputStream withExtras = InputStream withExtras = new ByteArrayInputStream(
new ByteArrayInputStream(result.concat("\n").concat(appendText).getBytes()); result.concat("\n").concat(appendText).getBytes());
this.portalsCore this.portalsCore.getDataStorage().writeResource(
.getDataStorage() withExtras,
.writeResource( "lang/" + configRepository.getTranslation() + ".lang");
withExtras, "lang/" + configRepository.getTranslation() + ".lang");
Lang.loadLanguage(configRepository.getTranslation()); Lang.loadLanguage(configRepository.getTranslation());
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translateInsertVariables( + Lang.translateInsertVariables("translatedata.updated",
"translatedata.updated", newTranslations.size())); newTranslations.size()));
} }
} }
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.LANG_UPDATE.hasPermission(sender); return sender.isOp()
|| PortalPermissions.LANG_UPDATE.hasPermission(sender);
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -5,23 +5,19 @@ import com.sekwah.advancedportals.core.commands.SubCommand;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.services.PortalServices; import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ListPortalsSubCommand implements SubCommand { public class ListPortalsSubCommand implements SubCommand {
@Inject PortalServices portalServices; @Inject PortalServices portalServices;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.portal.list") + Lang.translate("command.portal.list") + " "
+ " " + portalServices.getPortalNames().stream().sorted().collect(
+ portalServices.getPortalNames().stream() Collectors.joining(", ")));
.sorted()
.collect(Collectors.joining(", ")));
} }
@Override @Override
@ -30,7 +26,8 @@ public class ListPortalsSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -7,44 +7,39 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class PortalBlockSubCommand implements SubCommand { public class PortalBlockSubCommand implements SubCommand {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer(); PlayerContainer player = sender.getPlayerContainer();
if (player == null) { if (player == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
+ Lang.translate("command.playeronly"));
} else { } else {
player.giveItem( player.giveItem(
"PURPLE_WOOL", "PURPLE_WOOL", "\u00A75Portal Block Placer",
"\u00A75Portal Block Placer", "\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A77This wool is made of a magical substance", "\u00A7r\u00A7e" + Lang.translate("items.interact.left")
"\u00A7r\u00A7e" + "\u00A77: Rotate portal block",
+ Lang.translate("items.interact.left") "\u00A7r\u00A7e" + Lang.translate("items.interact.right")
+ "\u00A77: Rotate portal block", + "\u00A77: Place portal block");
"\u00A7r\u00A7e" sender.sendMessage(Lang.translate("messageprefix.positive")
+ Lang.translate("items.interact.right") + Lang.translate("command.portalblock"));
+ "\u00A77: Place portal block");
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.portalblock"));
} }
} }
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(sender); return sender.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(sender);
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -9,11 +9,9 @@ import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.services.DestinationServices; import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.services.PortalServices; import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class ReloadPortalSubCommand implements SubCommand { public class ReloadPortalSubCommand implements SubCommand {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@Inject PortalServices portalServices; @Inject PortalServices portalServices;
@ -28,9 +26,8 @@ public class ReloadPortalSubCommand implements SubCommand {
portalServices.loadPortals(); portalServices.loadPortals();
destinationServices.loadDestinations(); destinationServices.loadDestinations();
Lang.loadLanguage(configRepository.getTranslation()); Lang.loadLanguage(configRepository.getTranslation());
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.positive")
Lang.translate("messageprefix.positive") + Lang.translate("command.reload.reloaded"));
+ Lang.translate("command.reload.reloaded"));
} }
@Override @Override
@ -39,7 +36,8 @@ public class ReloadPortalSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -6,24 +6,23 @@ import com.sekwah.advancedportals.core.connector.containers.CommandSenderContain
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.services.PortalServices; import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class RemovePortalSubCommand implements SubCommand { public class RemovePortalSubCommand implements SubCommand {
@Inject PortalServices portalServices; @Inject PortalServices portalServices;
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (args.length > 1) { if (args.length > 1) {
if (portalServices.removePortal(args[1], sender.getPlayerContainer())) { if (portalServices.removePortal(args[1],
sender.getPlayerContainer())) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translate("command.portal.remove.complete")); + Lang.translate("command.portal.remove.complete"));
} else { } else {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.remove.error")); + Lang.translate("command.portal.remove.error"));
} }
} else { } else {
sender.sendMessage(Lang.translate("command.portal.remove.noname")); sender.sendMessage(Lang.translate("command.portal.remove.noname"));
@ -32,11 +31,13 @@ public class RemovePortalSubCommand implements SubCommand {
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(sender); return sender.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(sender);
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return portalServices.getPortalNames(); return portalServices.getPortalNames();
} }

View File

@ -8,11 +8,9 @@ import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions; import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.repository.ConfigRepository; import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class SelectorSubCommand implements SubCommand { public class SelectorSubCommand implements SubCommand {
@Inject private ConfigRepository configRepo; @Inject private ConfigRepository configRepo;
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@ -21,36 +19,34 @@ public class SelectorSubCommand implements SubCommand {
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer(); PlayerContainer player = sender.getPlayerContainer();
if (player == null) { if (player == null) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
+ Lang.translate("command.playeronly"));
} else { } else {
player.giveItem( player.giveItem(
configRepo.getSelectorMaterial(), configRepo.getSelectorMaterial(),
"\u00A7e" + Lang.translate("items.selector.name"), "\u00A7e" + Lang.translate("items.selector.name"),
"\u00A7r\u00A77This wand with has the power to help", "\u00A7r\u00A77This wand with has the power to help",
"\u00A7r\u00A77 create portals bistowed upon it!", "\u00A7r\u00A77 create portals bistowed upon it!", "",
"", "\u00A7r\u00A7e" + Lang.translate("items.interact.left")
"\u00A7r\u00A7e" + "\u00A77: "
+ Lang.translate("items.interact.left") + Lang.translateInsertVariables("items.selector.pos", "1"),
+ "\u00A77: " "\u00A7r\u00A7e" + Lang.translate("items.interact.right")
+ Lang.translateInsertVariables("items.selector.pos", "1"), + "\u00A77: "
"\u00A7r\u00A7e" + Lang.translateInsertVariables("items.selector.pos", "2"));
+ Lang.translate("items.interact.right") sender.sendMessage(Lang.translate("messageprefix.positive")
+ "\u00A77: " + Lang.translate("command.selector"));
+ Lang.translateInsertVariables("items.selector.pos", "2"));
sender.sendMessage(
Lang.translate("messageprefix.positive") + Lang.translate("command.selector"));
} }
} }
@Override @Override
public boolean hasPermission(CommandSenderContainer sender) { public boolean hasPermission(CommandSenderContainer sender) {
return sender.isOp() || PortalPermissions.CREATE_PORTAL.hasPermission(sender); return sender.isOp()
|| PortalPermissions.CREATE_PORTAL.hasPermission(sender);
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -15,17 +15,16 @@ import com.sekwah.advancedportals.core.tags.activation.NameTag;
import com.sekwah.advancedportals.core.util.Debug; import com.sekwah.advancedportals.core.util.Debug;
import com.sekwah.advancedportals.core.util.GameScheduler; import com.sekwah.advancedportals.core.util.GameScheduler;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.awt.*; import java.awt.*;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
/** /**
* This will be different from the old show command and I believe it is 1.16+ till the latest * This will be different from the old show command and I believe it is 1.16+
* version as of writing this. * till the latest version as of writing this.
*/ */
public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOnInit { public class ShowPortalSubCommand
implements SubCommand, SubCommand.SubCommandOnInit {
static final int SHOW_TICKS = 1010; static final int SHOW_TICKS = 1010;
boolean alternate_show_trigger = true; boolean alternate_show_trigger = true;
@ -57,20 +56,20 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (core.getMcVersion()[1] < 16) { if (core.getMcVersion()[1] < 16) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.show.unsupported")); + Lang.translate("command.portal.show.unsupported"));
return; return;
} }
var tempData = playerDataServices.getPlayerData(sender.getPlayerContainer()); var tempData =
playerDataServices.getPlayerData(sender.getPlayerContainer());
if (tempData.isPortalVisible()) { if (tempData.isPortalVisible()) {
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.show.disabled")); + Lang.translate("command.portal.show.disabled"));
} else { } else {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.positive")
Lang.translate("messageprefix.positive") + Lang.translate("command.portal.show.enabled"));
+ Lang.translate("command.portal.show.enabled"));
} }
tempData.setPortalVisible(!tempData.isPortalVisible()); tempData.setPortalVisible(!tempData.isPortalVisible());
} }
@ -81,7 +80,8 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }
@ -97,110 +97,88 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
@Override @Override
public void registered() { public void registered() {
gameScheduler.intervalTickEvent( gameScheduler.intervalTickEvent("show_portal", () -> {
"show_portal", alternate_show_trigger = !alternate_show_trigger;
() -> { for (PlayerContainer player : serverContainer.getPlayers()) {
alternate_show_trigger = !alternate_show_trigger; var tempData = playerDataServices.getPlayerData(player);
for (PlayerContainer player : serverContainer.getPlayers()) { if (!tempData.isPortalVisible()) {
var tempData = playerDataServices.getPlayerData(player); continue;
if (!tempData.isPortalVisible()) { }
continue;
}
if (tempData.getPos1() != null if (tempData.getPos1() != null && tempData.getPos2() != null
&& tempData.getPos2() != null && tempData.getPos1().getWorldName().equals(
&& tempData.getPos1().getWorldName().equals(player.getWorldName()) player.getWorldName())
&& tempData.getPos2() && tempData.getPos2().getWorldName().equals(
.getWorldName() player.getWorldName())) {
.equals(player.getWorldName())) { debugVisuals(player, tempData.getPos1(), tempData.getPos2(),
debugVisuals( SELECTION_COLOR, SHOW_TICKS);
player, }
tempData.getPos1(),
tempData.getPos2(),
SELECTION_COLOR,
SHOW_TICKS);
}
if (tempData.getPos1() != null if (tempData.getPos1() != null
&& tempData.getPos1() && tempData.getPos1().getWorldName().equals(
.getWorldName() player.getWorldName())) {
.equals(player.getWorldName())) { Debug.addMarker(player, tempData.getPos1(), "Pos1",
Debug.addMarker( POS1_COLOR, SHOW_TICKS);
player, tempData.getPos1(), "Pos1", POS1_COLOR, SHOW_TICKS); }
} if (tempData.getPos2() != null
if (tempData.getPos2() != null && tempData.getPos2().getWorldName().equals(
&& tempData.getPos2() player.getWorldName())) {
.getWorldName() Debug.addMarker(player, tempData.getPos2(), "Pos2",
.equals(player.getWorldName())) { POS2_COLOR, SHOW_TICKS);
Debug.addMarker( }
player, tempData.getPos2(), "Pos2", POS2_COLOR, SHOW_TICKS);
}
var world = player.getWorld(); var world = player.getWorld();
for (var portal : portalServices.getPortals()) { for (var portal : portalServices.getPortals()) {
if (Objects.equals( if (Objects.equals(portal.getMinLoc().getWorldName(),
portal.getMinLoc().getWorldName(), player.getWorldName())
player.getWorldName()) && portal.isLocationInPortal(
&& portal.isLocationInPortal( player.getLoc(), config.getVisibleRange())) {
player.getLoc(), config.getVisibleRange())) { BlockLocation minLoc = portal.getMinLoc();
BlockLocation minLoc = portal.getMinLoc(); BlockLocation maxLoc = portal.getMaxLoc();
BlockLocation maxLoc = portal.getMaxLoc(); int midX = (minLoc.getPosX() + maxLoc.getPosX()) / 2;
int midX = (minLoc.getPosX() + maxLoc.getPosX()) / 2; int midZ = (minLoc.getPosZ() + maxLoc.getPosZ()) / 2;
int midZ = (minLoc.getPosZ() + maxLoc.getPosZ()) / 2; BlockLocation midPoint =
BlockLocation midPoint = new BlockLocation(minLoc.getWorldName(), midX,
new BlockLocation( maxLoc.getPosY(), midZ);
minLoc.getWorldName(), Color color;
midX, if (portal.isTriggerBlock(world.getBlock(midPoint))) {
maxLoc.getPosY(), color = TRIGGER_OUTLINE_COLOR;
midZ); } else {
Color color; if (midPoint.getPosX() == minLoc.getPosX()
if (portal.isTriggerBlock(world.getBlock(midPoint))) { || midPoint.getPosX() == maxLoc.getPosX()
color = TRIGGER_OUTLINE_COLOR; || midPoint.getPosZ() == minLoc.getPosZ()
} else { || midPoint.getPosZ() == maxLoc.getPosZ())
if (midPoint.getPosX() == minLoc.getPosX() color = OUTLINE_COLOR;
|| midPoint.getPosX() == maxLoc.getPosX() else
|| midPoint.getPosZ() == minLoc.getPosZ() color = new Color(0, 0, 0, 0);
|| midPoint.getPosZ() == maxLoc.getPosZ()) }
color = OUTLINE_COLOR; debugVisuals(player, portal, OUTLINE_COLOR, SHOW_TICKS,
else color = new Color(0, 0, 0, 0); TRIGGER_COLOR);
} var name = portal.getArgValues(NameTag.TAG_NAME);
debugVisuals( if (name != null && name.length > 0) {
player, portal, OUTLINE_COLOR, SHOW_TICKS, TRIGGER_COLOR); Debug.addMarker(player, midPoint, name[0], color,
var name = portal.getArgValues(NameTag.TAG_NAME); SHOW_TICKS);
if (name != null && name.length > 0) {
Debug.addMarker(player, midPoint, name[0], color, SHOW_TICKS);
}
}
} }
} }
}, }
1, }
20); }, 1, 20);
} }
private void debugVisuals( private void debugVisuals(PlayerContainer player, BlockLocation pos1,
PlayerContainer player, BlockLocation pos1, BlockLocation pos2, Color color, int time) { BlockLocation pos2, Color color, int time) {
debugVisuals(player, pos1, pos2, color, time, null, null); debugVisuals(player, pos1, pos2, color, time, null, null);
} }
private void debugVisuals( private void debugVisuals(PlayerContainer player, AdvancedPortal portal,
PlayerContainer player, Color color, int time, Color triggerColor) {
AdvancedPortal portal, debugVisuals(player, portal.getMinLoc(), portal.getMaxLoc(), color,
Color color, time, triggerColor, portal);
int time,
Color triggerColor) {
debugVisuals(
player, portal.getMinLoc(), portal.getMaxLoc(), color, time, triggerColor, portal);
} }
private void debugVisuals( private void debugVisuals(PlayerContainer player, BlockLocation pos1,
PlayerContainer player, BlockLocation pos2, Color color, int time,
BlockLocation pos1, Color triggerColor, AdvancedPortal portal) {
BlockLocation pos2,
Color color,
int time,
Color triggerColor,
AdvancedPortal portal) {
int minX = Math.min(pos1.getPosX(), pos2.getPosX()); int minX = Math.min(pos1.getPosX(), pos2.getPosX());
int minY = Math.min(pos1.getPosY(), pos2.getPosY()); int minY = Math.min(pos1.getPosY(), pos2.getPosY());
int minZ = Math.min(pos1.getPosZ(), pos2.getPosZ()); int minZ = Math.min(pos1.getPosZ(), pos2.getPosZ());
@ -221,105 +199,83 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
for (int x = minX; x <= maxX; x++) { for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) { for (int y = minY; y <= maxY; y++) {
for (int z = minZ; z <= maxZ; z++) { for (int z = minZ; z <= maxZ; z++) {
var pos = new BlockLocation(pos1.getWorldName(), x, y, z); var pos =
boolean isTrigger = new BlockLocation(pos1.getWorldName(), x, y, z);
portal != null && portal.isTriggerBlock(world.getBlock(pos)); boolean isTrigger = portal != null
boolean isOutline = && portal.isTriggerBlock(world.getBlock(pos));
(y == minY || y == maxY) boolean isOutline = (y == minY || y == maxY)
&& (x == minX || x == maxX || z == minZ && (x == minX || x == maxX || z == minZ
|| z == maxZ) || z == maxZ)
|| (z == minZ || z == maxZ) && (x == minX || x == maxX); || (z == minZ || z == maxZ)
&& (x == minX || x == maxX);
if (isTrigger && isOutline && alternate_show_trigger) { if (isTrigger && isOutline && alternate_show_trigger) {
Debug.addMarker(player, pos, "", TRIGGER_OUTLINE_COLOR, time); Debug.addMarker(player, pos, "",
TRIGGER_OUTLINE_COLOR, time);
} else if (isOutline) { } else if (isOutline) {
Debug.addMarker(player, pos, "", color, time); Debug.addMarker(player, pos, "", color, time);
} else if (isTrigger) { } else if (isTrigger) {
if (alternate_show_trigger) if (alternate_show_trigger)
Debug.addMarker(player, pos, "", triggerColor, time); Debug.addMarker(player, pos, "", triggerColor,
time);
} }
} }
} }
} }
} else { } else {
for (int x = minX; x <= maxX; x++) { for (int x = minX; x <= maxX; x++) {
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), x, minY, minZ), new BlockLocation(pos1.getWorldName(), x, minY, minZ), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), x, minY, maxZ), new BlockLocation(pos1.getWorldName(), x, minY, maxZ), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), x, maxY, minZ), new BlockLocation(pos1.getWorldName(), x, maxY, minZ), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), x, maxY, maxZ), new BlockLocation(pos1.getWorldName(), x, maxY, maxZ), "",
"", color, time);
color,
time);
} }
for (int z = minZ + 1; z < maxZ; z++) { for (int z = minZ + 1; z < maxZ; z++) {
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), minX, minY, z), new BlockLocation(pos1.getWorldName(), minX, minY, z), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), maxX, minY, z), new BlockLocation(pos1.getWorldName(), maxX, minY, z), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), minX, maxY, z), new BlockLocation(pos1.getWorldName(), minX, maxY, z), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), maxX, maxY, z), new BlockLocation(pos1.getWorldName(), maxX, maxY, z), "",
"", color, time);
color,
time);
} }
for (int y = minY + 1; y < maxY; y++) { for (int y = minY + 1; y < maxY; y++) {
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), minX, y, minZ), new BlockLocation(pos1.getWorldName(), minX, y, minZ), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), maxX, y, minZ), new BlockLocation(pos1.getWorldName(), maxX, y, minZ), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), minX, y, maxZ), new BlockLocation(pos1.getWorldName(), minX, y, maxZ), "",
"", color, time);
color,
time);
Debug.addMarker( Debug.addMarker(
player, player,
new BlockLocation(pos1.getWorldName(), maxX, y, maxZ), new BlockLocation(pos1.getWorldName(), maxX, y, maxZ), "",
"", color, time);
color,
time);
} }
} }
} }

View File

@ -4,17 +4,14 @@ import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.commands.SubCommand; import com.sekwah.advancedportals.core.commands.SubCommand;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.List; import java.util.List;
public class VersionSubCommand implements SubCommand { public class VersionSubCommand implements SubCommand {
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.positive")
Lang.translate("messageprefix.positive") + " Advanced Portals v"
+ " Advanced Portals v" + AdvancedPortalsCore.version);
+ AdvancedPortalsCore.version);
} }
@Override @Override
@ -23,7 +20,8 @@ public class VersionSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -3,7 +3,6 @@ package com.sekwah.advancedportals.core.connector.commands;
import com.sekwah.advancedportals.core.commands.CommandTemplate; import com.sekwah.advancedportals.core.commands.CommandTemplate;
public abstract class CommandHandler { public abstract class CommandHandler {
private final CommandTemplate commandExecutor; private final CommandTemplate commandExecutor;
public CommandHandler(CommandTemplate commandExecutor) { public CommandHandler(CommandTemplate commandExecutor) {

View File

@ -3,7 +3,6 @@ package com.sekwah.advancedportals.core.connector.commands;
import com.sekwah.advancedportals.core.commands.CommandTemplate; import com.sekwah.advancedportals.core.commands.CommandTemplate;
public interface CommandRegister { public interface CommandRegister {
/** /**
* Registers the command to the appropriate system * Registers the command to the appropriate system
* *

View File

@ -1,7 +1,6 @@
package com.sekwah.advancedportals.core.connector.containers; package com.sekwah.advancedportals.core.connector.containers;
public interface CommandSenderContainer { public interface CommandSenderContainer {
void sendMessage(String message); void sendMessage(String message);
boolean isOp(); boolean isOp();

View File

@ -5,7 +5,6 @@ import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.serializeddata.Vector; import com.sekwah.advancedportals.core.serializeddata.Vector;
public interface EntityContainer { public interface EntityContainer {
PlayerLocation getLoc(); PlayerLocation getLoc();
double getHeight(); double getHeight();

View File

@ -1,12 +1,13 @@
package com.sekwah.advancedportals.core.connector.containers; package com.sekwah.advancedportals.core.connector.containers;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import java.util.UUID; import java.util.UUID;
/** Just a temporary container for whenever advanced portals needs to get data from a player */ /**
* Just a temporary container for whenever advanced portals needs to get data
* from a player
*/
public interface PlayerContainer extends EntityContainer { public interface PlayerContainer extends EntityContainer {
UUID getUUID(); UUID getUUID();
void sendMessage(String message); void sendMessage(String message);
@ -28,7 +29,8 @@ public interface PlayerContainer extends EntityContainer {
* @param material * @param material
* @param data * @param data
*/ */
void sendFakeBlockWithData(BlockLocation blockPos, String material, byte data); void sendFakeBlockWithData(BlockLocation blockPos, String material,
byte data);
void giveItem(String material, String itemName, String... itemDescription); void giveItem(String material, String itemName, String... itemDescription);

View File

@ -4,7 +4,6 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
public interface ServerContainer { public interface ServerContainer {
WorldContainer getWorld(String name); WorldContainer getWorld(String name);
PlayerContainer getPlayer(String name); PlayerContainer getPlayer(String name);

View File

@ -4,7 +4,6 @@ import com.sekwah.advancedportals.core.data.BlockAxis;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
public interface WorldContainer { public interface WorldContainer {
void setBlock(BlockLocation location, String material); void setBlock(BlockLocation location, String material);
String getBlock(BlockLocation location); String getBlock(BlockLocation location);

View File

@ -1,7 +1,3 @@
package com.sekwah.advancedportals.core.data; package com.sekwah.advancedportals.core.data;
public enum BlockAxis { public enum BlockAxis { X, Y, Z }
X,
Y,
Z
}

View File

@ -8,24 +8,23 @@ import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation; import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.warphandler.ActivationData; import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
* Possibly look at adding the ability to add some tags to destinations such as permissions. Would * Possibly look at adding the ability to add some tags to destinations such as
* make it easier to add permissions to block access to certain areas and such. Could be a different * permissions. Would make it easier to add permissions to block access to
* permission system or just it takes the tags on the destination and automatically applies them * certain areas and such. Could be a different permission system or just it
* when a portal wants to warp to there. (Of course it would not work cross server unless the data * takes the tags on the destination and automatically applies them when a
* was communicated and checked first however that could affect performance and would definitely * portal wants to warp to there. (Of course it would not work cross server
* affect speed) * unless the data was communicated and checked first however that could affect
* performance and would definitely affect speed)
* *
* @author sekwah41 * @author sekwah41
*/ */
public class Destination implements TagTarget { public class Destination implements TagTarget {
@Inject transient TagRegistry tagRegistry; @Inject transient TagRegistry tagRegistry;
private PlayerLocation loc; private PlayerLocation loc;
@ -53,7 +52,8 @@ public class Destination implements TagTarget {
} }
@Override @Override
public void addArg(String argName, String argValues) {} public void addArg(String argName, String argValues) {
}
public void setArgValues(DataTag portalTag) { public void setArgValues(DataTag portalTag) {
this.setArgValues(portalTag.NAME, portalTag.VALUES); this.setArgValues(portalTag.NAME, portalTag.VALUES);
@ -77,16 +77,19 @@ public class Destination implements TagTarget {
destiTags[i++] = new DataTag(entry.getKey(), entry.getValue()); destiTags[i++] = new DataTag(entry.getKey(), entry.getValue());
} }
for (DataTag destiTag : destiTags) { for (DataTag destiTag : destiTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(destiTag.NAME); Tag.Activation activationHandler =
tagRegistry.getActivationHandler(destiTag.NAME);
if (activationHandler != null) { if (activationHandler != null) {
activationHandler.preActivated( activationHandler.preActivated(
this, player, data, this.getArgValues(destiTag.NAME)); this, player, data, this.getArgValues(destiTag.NAME));
} }
} }
for (DataTag destiTag : destiTags) { for (DataTag destiTag : destiTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(destiTag.NAME); Tag.Activation activationHandler =
tagRegistry.getActivationHandler(destiTag.NAME);
if (activationHandler != null) { if (activationHandler != null) {
activationHandler.activated(this, player, data, this.getArgValues(destiTag.NAME)); activationHandler.activated(this, player, data,
this.getArgValues(destiTag.NAME));
} }
} }
return true; return true;
@ -99,10 +102,11 @@ public class Destination implements TagTarget {
destiTags[i++] = new DataTag(entry.getKey(), entry.getValue()); destiTags[i++] = new DataTag(entry.getKey(), entry.getValue());
} }
for (DataTag destiTag : destiTags) { for (DataTag destiTag : destiTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(destiTag.NAME); Tag.Activation activationHandler =
tagRegistry.getActivationHandler(destiTag.NAME);
if (activationHandler != null) { if (activationHandler != null) {
activationHandler.postActivated( activationHandler.postActivated(
this, player, data, this.getArgValues(destiTag.NAME)); this, player, data, this.getArgValues(destiTag.NAME));
} }
} }
} }

View File

@ -3,19 +3,16 @@ package com.sekwah.advancedportals.core.effect;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
public interface WarpEffect { public interface WarpEffect {
enum Action { enum Action {
ENTER, ENTER,
EXIT; EXIT;
} }
interface Sound extends WarpEffect { interface Sound extends WarpEffect {
void onWarpSound(PlayerContainer player, Action action); void onWarpSound(PlayerContainer player, Action action);
} }
interface Visual extends WarpEffect { interface Visual extends WarpEffect {
void onWarpVisual(PlayerContainer player, Action action); void onWarpVisual(PlayerContainer player, Action action);
} }
} }

View File

@ -17,14 +17,11 @@ import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.serializeddata.config.Config; import com.sekwah.advancedportals.core.serializeddata.config.Config;
import com.sekwah.advancedportals.core.serializeddata.config.ConfigProvider; import com.sekwah.advancedportals.core.serializeddata.config.ConfigProvider;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class AdvancedPortalsModule extends AbstractModule { public class AdvancedPortalsModule extends AbstractModule {
private Injector injector; private Injector injector;
private AdvancedPortalsCore advancedPortalsCore; private AdvancedPortalsCore advancedPortalsCore;
private DataStorage dataStorage; private DataStorage dataStorage;
@ -35,19 +32,31 @@ public class AdvancedPortalsModule extends AbstractModule {
this.advancedPortalsCore = advancedPortalsCore; this.advancedPortalsCore = advancedPortalsCore;
} }
/** https://github.com/google/guice/wiki/Bindings */ /**
* https://github.com/google/guice/wiki/Bindings
*/
@Override @Override
protected void configure() { protected void configure() {
bind(IPortalRepository.class).to(PortalRepositoryImpl.class).in(Scopes.SINGLETON); bind(IPortalRepository.class)
bind(IDestinationRepository.class).to(DestinationRepositoryImpl.class).in(Scopes.SINGLETON); .to(PortalRepositoryImpl.class)
bind(IPlayerDataRepository.class).to(PlayerDataRepositoryImpl.class).in(Scopes.SINGLETON); .in(Scopes.SINGLETON);
bind(ConfigRepository.class).to(ConfigRepositoryImpl.class).in(Scopes.SINGLETON); bind(IDestinationRepository.class)
.to(DestinationRepositoryImpl.class)
.in(Scopes.SINGLETON);
bind(IPlayerDataRepository.class)
.to(PlayerDataRepositoryImpl.class)
.in(Scopes.SINGLETON);
bind(ConfigRepository.class)
.to(ConfigRepositoryImpl.class)
.in(Scopes.SINGLETON);
// Instances // Instances
bind(AdvancedPortalsCore.class).toInstance(advancedPortalsCore); bind(AdvancedPortalsCore.class).toInstance(advancedPortalsCore);
bind(InfoLogger.class).toInstance(advancedPortalsCore.getInfoLogger()); bind(InfoLogger.class).toInstance(advancedPortalsCore.getInfoLogger());
bind(DataStorage.class).toInstance(advancedPortalsCore.getDataStorage()); bind(DataStorage.class)
bind(ServerContainer.class).toInstance(advancedPortalsCore.getServerContainer()); .toInstance(advancedPortalsCore.getDataStorage());
bind(ServerContainer.class)
.toInstance(advancedPortalsCore.getServerContainer());
// Providers // Providers
bind(Config.class).toProvider(ConfigProvider.class); bind(Config.class).toProvider(ConfigProvider.class);

View File

@ -2,22 +2,26 @@ package com.sekwah.advancedportals.core.permissions;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import java.util.List; import java.util.List;
public class PortalPermissions { public class PortalPermissions {
private static final PermissionBuilder PERMISSIONS =
new PermissionBuilder("advancedportals");
private static final PermissionBuilder PERMISSIONS = new PermissionBuilder("advancedportals"); public static final PermissionBuilder BUILD =
PERMISSIONS.createChild("build");
public static final PermissionBuilder BUILD = PERMISSIONS.createChild("build"); public static final PermissionBuilder DESTI =
public static final PermissionBuilder DESTI = PERMISSIONS.createChild("desti"); PERMISSIONS.createChild("desti");
public static final PermissionBuilder CREATE_PORTAL = PERMISSIONS.createChild("createportal"); public static final PermissionBuilder CREATE_PORTAL =
public static final PermissionBuilder LANG_UPDATE = PERMISSIONS.createChild("langupdate"); PERMISSIONS.createChild("createportal");
public static final PermissionBuilder RELOAD = PERMISSIONS.createChild("reload"); public static final PermissionBuilder LANG_UPDATE =
PERMISSIONS.createChild("langupdate");
public static final PermissionBuilder RELOAD =
PERMISSIONS.createChild("reload");
/** /**
* this will not currently build the permissions for the files, but maybe at some point. It'll * this will not currently build the permissions for the files, but maybe at
* just make it easier though. * some point. It'll just make it easier though.
*/ */
public static class PermissionBuilder { public static class PermissionBuilder {
private final String permissionTag; private final String permissionTag;

View File

@ -13,14 +13,12 @@ import com.sekwah.advancedportals.core.tags.activation.TriggerBlockTag;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.ActivationData; import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.*; import java.util.*;
/** /**
* @author sekwah41 * @author sekwah41
*/ */
public class AdvancedPortal implements TagTarget { public class AdvancedPortal implements TagTarget {
@Inject private transient TagRegistry tagRegistry; @Inject private transient TagRegistry tagRegistry;
private BlockLocation maxLoc; private BlockLocation maxLoc;
@ -38,11 +36,9 @@ public class AdvancedPortal implements TagTarget {
this.maxLoc = new BlockLocation(); this.maxLoc = new BlockLocation();
} }
public AdvancedPortal( public AdvancedPortal(BlockLocation minLoc, BlockLocation maxLoc,
BlockLocation minLoc, TagRegistry tagRegistry,
BlockLocation maxLoc, PlayerDataServices playerDataServices) {
TagRegistry tagRegistry,
PlayerDataServices playerDataServices) {
this.tagRegistry = tagRegistry; this.tagRegistry = tagRegistry;
this.playerDataServices = playerDataServices; this.playerDataServices = playerDataServices;
this.updateBounds(minLoc, maxLoc); this.updateBounds(minLoc, maxLoc);
@ -105,24 +101,28 @@ public class AdvancedPortal implements TagTarget {
}*/ }*/
/** /**
* @param player The player on the server attempting to use an advanced portal * @param player The player on the server attempting to use an advanced
* @param moveActivated if the portal was activated by a move event (won't trigger knockback) * portal
* @param moveActivated if the portal was activated by a move event (won't
* trigger knockback)
* @return * @return
*/ */
public boolean activate(PlayerContainer player, boolean moveActivated) { public boolean activate(PlayerContainer player, boolean moveActivated) {
var playerData = playerDataServices.getPlayerData(player); var playerData = playerDataServices.getPlayerData(player);
if (playerData.isInPortal()) return false; if (playerData.isInPortal())
return false;
playerData.setInPortal(true); playerData.setInPortal(true);
if (playerData.hasJoinCooldown()) { if (playerData.hasJoinCooldown()) {
var cooldown = (int) Math.ceil(playerData.getJoinCooldownLeft() / 1000D); var cooldown =
player.sendMessage( (int) Math.ceil(playerData.getJoinCooldownLeft() / 1000D);
Lang.translateInsertVariables( player.sendMessage(Lang.translateInsertVariables(
"portal.cooldown.join", "portal.cooldown.join", cooldown,
cooldown, Lang.translate(cooldown == 1 ? "time.second"
Lang.translate(cooldown == 1 ? "time.second" : "time.seconds"))); : "time.seconds")));
if (configRepository.playFailSound()) { if (configRepository.playFailSound()) {
var rand = new Random(); var rand = new Random();
player.playSound("block.portal.travel", 0.05f, rand.nextFloat() * 0.4F + 0.8F); player.playSound("block.portal.travel", 0.05f,
rand.nextFloat() * 0.4F + 0.8F);
} }
return false; return false;
} }
@ -135,28 +135,33 @@ public class AdvancedPortal implements TagTarget {
} }
for (DataTag portalTag : portalTags) { for (DataTag portalTag : portalTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(portalTag.NAME); Tag.Activation activationHandler =
tagRegistry.getActivationHandler(portalTag.NAME);
if (activationHandler != null) { if (activationHandler != null) {
if (!activationHandler.preActivated( if (!activationHandler.preActivated(
this, player, data, this.getArgValues(portalTag.NAME))) { this, player, data,
this.getArgValues(portalTag.NAME))) {
return false; return false;
} }
} }
} }
for (DataTag portalTag : portalTags) { for (DataTag portalTag : portalTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(portalTag.NAME); Tag.Activation activationHandler =
tagRegistry.getActivationHandler(portalTag.NAME);
if (activationHandler != null) { if (activationHandler != null) {
if (!activationHandler.activated( if (!activationHandler.activated(
this, player, data, this.getArgValues(portalTag.NAME))) { this, player, data,
this.getArgValues(portalTag.NAME))) {
return false; return false;
} }
} }
} }
for (DataTag portalTag : portalTags) { for (DataTag portalTag : portalTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(portalTag.NAME); Tag.Activation activationHandler =
tagRegistry.getActivationHandler(portalTag.NAME);
if (activationHandler != null) { if (activationHandler != null) {
activationHandler.postActivated( activationHandler.postActivated(
this, player, data, this.getArgValues(portalTag.NAME)); this, player, data, this.getArgValues(portalTag.NAME));
} }
} }
if (data.hasActivated()) { if (data.hasActivated()) {
@ -184,12 +189,12 @@ public class AdvancedPortal implements TagTarget {
double playerZ = loc.getPosZ(); double playerZ = loc.getPosZ();
return Objects.equals(loc.getWorldName(), this.minLoc.getWorldName()) return Objects.equals(loc.getWorldName(), this.minLoc.getWorldName())
&& playerX >= this.minLoc.getPosX() - additionalArea && playerX >= this.minLoc.getPosX() - additionalArea
&& playerX < this.maxLoc.getPosX() + 1 + additionalArea && playerX < this.maxLoc.getPosX() + 1 + additionalArea
&& playerY >= this.minLoc.getPosY() - additionalArea && playerY >= this.minLoc.getPosY() - additionalArea
&& playerY < this.maxLoc.getPosY() + 1 + additionalArea && playerY < this.maxLoc.getPosY() + 1 + additionalArea
&& playerZ >= this.minLoc.getPosZ() - additionalArea && playerZ >= this.minLoc.getPosZ() - additionalArea
&& playerZ < this.maxLoc.getPosZ() + 1 + additionalArea; && playerZ < this.maxLoc.getPosZ() + 1 + additionalArea;
} }
public void setArgValues(DataTag portalTag) { public void setArgValues(DataTag portalTag) {

View File

@ -4,5 +4,6 @@ public enum CommandErrorCode {
INSUFFICIENT_ARGUMENTS(""), INSUFFICIENT_ARGUMENTS(""),
NO_PERMISSION(""); NO_PERMISSION("");
CommandErrorCode(String message) {} CommandErrorCode(String message) {
}
} }

View File

@ -4,17 +4,13 @@ import com.google.common.collect.ImmutableList;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
public interface CommandHandler { public interface CommandHandler {
void onExecute( void onExecute(String commandName, String parentCommand,
String commandName, CommandSenderContainer sender, ImmutableList<String> args);
String parentCommand,
CommandSenderContainer sender,
ImmutableList<String> args);
default void onCommandFailure( default void onCommandFailure(String[] command,
String[] command, CommandSenderContainer sender,
CommandSenderContainer sender, CommandException exception,
CommandException exception, ImmutableList<String> args) {
ImmutableList<String> args) {
sender.sendMessage(exception.getMessage()); sender.sendMessage(exception.getMessage());
} }
} }

View File

@ -1,6 +1,5 @@
package com.sekwah.advancedportals.core.registry; package com.sekwah.advancedportals.core.registry;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
public class RegisterBuilder<T extends CommandHandler> { public class RegisterBuilder<T extends CommandHandler> {
@ -8,14 +7,14 @@ public class RegisterBuilder<T extends CommandHandler> {
return new RegisterBuilder(); return new RegisterBuilder();
} }
private RegisterBuilder() {} private RegisterBuilder() {
}
private boolean allowPermissionInheritance; private boolean allowPermissionInheritance;
private String scanDirectory; private String scanDirectory;
private final Class<T> genericType = private final Class<T> genericType =
(Class<T>) (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0];
.getActualTypeArguments()[0];
public RegisterBuilder<T> inheritPermissions(boolean allowInheritance) { public RegisterBuilder<T> inheritPermissions(boolean allowInheritance) {
allowPermissionInheritance = allowInheritance; allowPermissionInheritance = allowInheritance;

View File

@ -3,24 +3,26 @@ package com.sekwah.advancedportals.core.registry;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.sekwah.advancedportals.core.commands.SubCommand; import com.sekwah.advancedportals.core.commands.SubCommand;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Do not register to here. Register to the sprcific subcommand registry classes. * Do not register to here. Register to the sprcific subcommand registry
* classes.
* *
* <p>Designed to let addons add new command sections to access, edit or add new functonality. * <p>Designed to let addons add new command sections to access, edit or add
* new functonality.
* *
* @author sekwah41 * @author sekwah41
*/ */
public class SubCommandRegistry { public class SubCommandRegistry {
protected Map<String, SubCommand> subCommandMap = new HashMap<>(); protected Map<String, SubCommand> subCommandMap = new HashMap<>();
/** List of subcommand names which should be in order alphabetically */ /**
* List of subcommand names which should be in order alphabetically
*/
protected ArrayList<String> subCommands = new ArrayList<>(); protected ArrayList<String> subCommands = new ArrayList<>();
@Inject private InfoLogger infoLogger; @Inject private InfoLogger infoLogger;
@ -31,14 +33,15 @@ public class SubCommandRegistry {
* @return if the subcommand is registered or not * @return if the subcommand is registered or not
*/ */
public boolean registerSubCommand(String arg, SubCommand subCommand) { public boolean registerSubCommand(String arg, SubCommand subCommand) {
if (subCommand == null) { if (subCommand == null) {
this.infoLogger.warning("The subcommand '" + arg + "' cannot be null."); this.infoLogger.warning("The subcommand '" + arg
+ "' cannot be null.");
return false; return false;
} }
if (this.subCommandMap.containsKey(arg)) { if (this.subCommandMap.containsKey(arg)) {
this.infoLogger.warning("The subcommand '" + arg + "' already exists."); this.infoLogger.warning("The subcommand '" + arg
+ "' already exists.");
return false; return false;
} }
@ -59,7 +62,8 @@ public class SubCommandRegistry {
} }
/** /**
* I may be wrong but for larger lists containsKey is faster with a hashmap than arraylist. * I may be wrong but for larger lists containsKey is faster with a hashmap
* than arraylist.
* *
* <p>Though im not sure at what size it becomes more efficient. * <p>Though im not sure at what size it becomes more efficient.
* *

View File

@ -3,19 +3,16 @@ package com.sekwah.advancedportals.core.registry;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.sekwah.advancedportals.core.AdvancedPortalsCore; import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.*; import java.util.*;
/** /**
* Allows a portal to register a tag and add a handler. If a plugin wants to add functionality * Allows a portal to register a tag and add a handler. If a plugin wants to
* to someone elses tag then they should use the events. * add functionality to someone elses tag then they should use the events.
* *
* @author sekwah41 * @author sekwah41
*/ */
public class TagRegistry { public class TagRegistry {
@Inject AdvancedPortalsCore portalsCore;
@Inject
AdvancedPortalsCore portalsCore;
private final ArrayList<String> literalTags = new ArrayList<>(); private final ArrayList<String> literalTags = new ArrayList<>();
@ -25,8 +22,7 @@ public class TagRegistry {
private final Map<String, Tag.Creation> creationTags = new HashMap<>(); private final Map<String, Tag.Creation> creationTags = new HashMap<>();
private final Map<String, Tag.TagStatus> statusTags = new HashMap<>(); private final Map<String, Tag.TagStatus> statusTags = new HashMap<>();
@Inject @Inject private AdvancedPortalsCore pluginCore;
private AdvancedPortalsCore pluginCore;
/** /**
* Portals to trigger when a portal is activated * Portals to trigger when a portal is activated
@ -68,17 +64,19 @@ public class TagRegistry {
this.tags.add(tag); this.tags.add(tag);
// Check literal tags for clashes // Check literal tags for clashes
if(this.literalTags.contains(tagName)) { if (this.literalTags.contains(tagName)) {
this.portalsCore.getInfoLogger().warning("A tag with the name " + tagName + " already exists."); this.portalsCore.getInfoLogger().warning(
"A tag with the name " + tagName + " already exists.");
return false; return false;
} }
var aliases = tag.getAliases(); var aliases = tag.getAliases();
this.literalTags.add(tagName); this.literalTags.add(tagName);
if(aliases != null) { if (aliases != null) {
for (String alias : aliases) { for (String alias : aliases) {
if(this.literalTags.contains(alias)) { if (this.literalTags.contains(alias)) {
this.portalsCore.getInfoLogger().warning("A tag with the alias " + alias + " already exists."); this.portalsCore.getInfoLogger().warning(
"A tag with the alias " + alias + " already exists.");
return false; return false;
} }
} }
@ -103,7 +101,6 @@ public class TagRegistry {
return true; return true;
} }
public List<Tag> getTags() { public List<Tag> getTags() {
// TODO Make a copy of the list to prevent issues with modification // TODO Make a copy of the list to prevent issues with modification

View File

@ -1,8 +1,9 @@
package com.sekwah.advancedportals.core.registry; package com.sekwah.advancedportals.core.registry;
/** Something that a tag can be executed on. */ /**
* Something that a tag can be executed on.
*/
public interface TagTarget { public interface TagTarget {
/** /**
* Get the values for the arg * Get the values for the arg
* *

View File

@ -4,7 +4,6 @@ import com.google.inject.Inject;
import com.sekwah.advancedportals.core.AdvancedPortalsCore; import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.effect.WarpEffect; import com.sekwah.advancedportals.core.effect.WarpEffect;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -12,15 +11,11 @@ import java.util.Map;
* @author sekwah41 * @author sekwah41
*/ */
public class WarpEffectRegistry { public class WarpEffectRegistry {
private Map<String, WarpEffect> warpEffects = new HashMap(); private Map<String, WarpEffect> warpEffects = new HashMap();
@Inject @Inject private AdvancedPortalsCore portalsCore;
private AdvancedPortalsCore portalsCore;
@Inject @Inject private InfoLogger infoLogger;
private InfoLogger infoLogger;
/** /**
* Register a new warp effect. * Register a new warp effect.
@ -30,50 +25,49 @@ public class WarpEffectRegistry {
* @return if the effect was registered * @return if the effect was registered
*/ */
public void registerEffect(String name, WarpEffect effect) { public void registerEffect(String name, WarpEffect effect) {
if (name == null) {
if(name == null){
this.infoLogger.warning("Effect name cannot be null"); this.infoLogger.warning("Effect name cannot be null");
return; return;
} }
if(this.warpEffects.containsKey(name)){ if (this.warpEffects.containsKey(name)) {
this.infoLogger.warning("Effect with the name: " + name + " already exists"); this.infoLogger.warning("Effect with the name: " + name
+ " already exists");
return; return;
} }
this.warpEffects.put(name, effect); this.warpEffects.put(name, effect);
} }
public WarpEffect.Visual getVisualEffect(String name){ public WarpEffect.Visual getVisualEffect(String name) {
if(this.warpEffects.containsKey(name)) { if (this.warpEffects.containsKey(name)) {
var effect = this.warpEffects.get(name); var effect = this.warpEffects.get(name);
if(effect instanceof WarpEffect.Visual visual){ if (effect instanceof WarpEffect.Visual visual) {
return visual; return visual;
} } else {
else{ this.infoLogger.warning("Effect called " + name
this.infoLogger.warning("Effect called " + name + " is not a visual effect"); + " is not a visual effect");
return null; return null;
} }
} } else {
else{ this.infoLogger.warning("No effect called " + name
this.infoLogger.warning("No effect called " + name + " was registered"); + " was registered");
return null; return null;
} }
} }
public WarpEffect.Sound getSoundEffect(String name){ public WarpEffect.Sound getSoundEffect(String name) {
if(this.warpEffects.containsKey(name)) { if (this.warpEffects.containsKey(name)) {
var effect = this.warpEffects.get(name); var effect = this.warpEffects.get(name);
if(effect instanceof WarpEffect.Sound sound){ if (effect instanceof WarpEffect.Sound sound) {
return sound; return sound;
} } else {
else{ this.infoLogger.warning("Effect called " + name
this.infoLogger.warning("Effect called " + name + " is not a sound effect"); + " is not a sound effect");
return null; return null;
} }
} } else {
else{ this.infoLogger.warning("No effect called " + name
this.infoLogger.warning("No effect called " + name + " was registered"); + " was registered");
return null; return null;
} }
} }
} }

View File

@ -3,7 +3,6 @@ package com.sekwah.advancedportals.core.repository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage; import com.sekwah.advancedportals.core.serializeddata.DataStorage;
public interface ConfigRepository { public interface ConfigRepository {
boolean getUseOnlySpecialAxe(); boolean getUseOnlySpecialAxe();
String getTranslation(); String getTranslation();

View File

@ -3,7 +3,6 @@ package com.sekwah.advancedportals.core.repository;
import java.util.List; import java.util.List;
public interface IJsonRepository<T> { public interface IJsonRepository<T> {
boolean save(String name, T t); boolean save(String name, T t);
boolean containsKey(String name); boolean containsKey(String name);

View File

@ -4,12 +4,10 @@ import com.google.inject.Singleton;
import com.sekwah.advancedportals.core.repository.ConfigRepository; import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage; import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.serializeddata.config.Config; import com.sekwah.advancedportals.core.serializeddata.config.Config;
import java.util.HashMap; import java.util.HashMap;
@Singleton @Singleton
public class ConfigRepositoryImpl implements ConfigRepository { public class ConfigRepositoryImpl implements ConfigRepository {
private HashMap<String, Config> configs; private HashMap<String, Config> configs;
private Config config; private Config config;
private DataStorage dataStorage; private DataStorage dataStorage;
@ -19,11 +17,9 @@ public class ConfigRepositoryImpl implements ConfigRepository {
} }
public <T> T getValue(String output) { public <T> T getValue(String output) {
try { try {
return (T) configs.get(output); return (T) configs.get(output);
} catch (ClassCastException ignored) { } catch (ClassCastException ignored) {
} }
return null; return null;
} }

View File

@ -5,10 +5,8 @@ import com.sekwah.advancedportals.core.destination.Destination;
import com.sekwah.advancedportals.core.repository.IDestinationRepository; import com.sekwah.advancedportals.core.repository.IDestinationRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage; import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.tags.activation.NameTag; import com.sekwah.advancedportals.core.tags.activation.NameTag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Singleton; import javax.inject.Singleton;
@Singleton @Singleton
@ -19,7 +17,8 @@ public class DestinationRepositoryImpl implements IDestinationRepository {
@Override @Override
public boolean save(String name, Destination destination) { public boolean save(String name, Destination destination) {
return dataStorage.storeFile(destination, fileLocation + name + ".yaml"); return dataStorage.storeFile(destination,
fileLocation + name + ".yaml");
} }
public boolean containsKey(String name) { public boolean containsKey(String name) {
@ -32,7 +31,8 @@ public class DestinationRepositoryImpl implements IDestinationRepository {
} }
public Destination get(String name) { public Destination get(String name) {
return dataStorage.loadFile(Destination.class, fileLocation + name + ".yaml"); return dataStorage.loadFile(Destination.class,
fileLocation + name + ".yaml");
} }
@Override @Override
@ -49,7 +49,8 @@ public class DestinationRepositoryImpl implements IDestinationRepository {
// Forces the name tag to be up-to-date on load // Forces the name tag to be up-to-date on load
String[] name = destination.getArgValues(NameTag.TAG_NAME); String[] name = destination.getArgValues(NameTag.TAG_NAME);
if (name != null && name.length > 0) { if (name != null && name.length > 0) {
destination.setArgValues(NameTag.TAG_NAME, new String[] {fileName}); destination.setArgValues(NameTag.TAG_NAME,
new String[] {fileName});
} }
destinations.add(destination); destinations.add(destination);
} }

View File

@ -4,11 +4,9 @@ import com.google.inject.Inject;
import com.sekwah.advancedportals.core.repository.IPlayerDataRepository; import com.sekwah.advancedportals.core.repository.IPlayerDataRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage; import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.serializeddata.PlayerData; import com.sekwah.advancedportals.core.serializeddata.PlayerData;
import java.util.List; import java.util.List;
public class PlayerDataRepositoryImpl implements IPlayerDataRepository { public class PlayerDataRepositoryImpl implements IPlayerDataRepository {
private final String fileLocation = "playerData/"; private final String fileLocation = "playerData/";
@Inject DataStorage dataStorage; @Inject DataStorage dataStorage;
@ -30,7 +28,8 @@ public class PlayerDataRepositoryImpl implements IPlayerDataRepository {
@Override @Override
public PlayerData get(String name) { public PlayerData get(String name) {
return dataStorage.loadFile(PlayerData.class, fileLocation + name + ".yaml"); return dataStorage.loadFile(PlayerData.class,
fileLocation + name + ".yaml");
} }
@Override @Override

View File

@ -7,21 +7,20 @@ import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.repository.IPortalRepository; import com.sekwah.advancedportals.core.repository.IPortalRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage; import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.tags.activation.NameTag; import com.sekwah.advancedportals.core.tags.activation.NameTag;
import java.util.*; import java.util.*;
@Singleton @Singleton
public class PortalRepositoryImpl implements IPortalRepository { public class PortalRepositoryImpl implements IPortalRepository {
private final String fileLocation = "portals/"; private final String fileLocation = "portals/";
@Inject DataStorage dataStorage; @Inject DataStorage dataStorage;
/** /**
* In memory copy of the portal files as they will be accessed every movement tick. * In memory copy of the portal files as they will be accessed every
* movement tick.
* *
* <p>If we need to get it by name we can just load it from the file, but this is good for * <p>If we need to get it by name we can just load it from the file, but
* looping fast for the player move events. * this is good for looping fast for the player move events.
*/ */
private List<AdvancedPortal> portals = new ArrayList<>(); private List<AdvancedPortal> portals = new ArrayList<>();
@ -42,9 +41,13 @@ public class PortalRepositoryImpl implements IPortalRepository {
@Override @Override
public AdvancedPortal get(String name) { public AdvancedPortal get(String name) {
var portal = dataStorage.loadFile(AdvancedPortal.class, fileLocation + name + ".yaml"); var portal = dataStorage.loadFile(AdvancedPortal.class,
fileLocation + name + ".yaml");
if (portal != null) { if (portal != null) {
AdvancedPortalsCore.getInstance().getModule().getInjector().injectMembers(portal); AdvancedPortalsCore.getInstance()
.getModule()
.getInjector()
.injectMembers(portal);
} }
return portal; return portal;
} }
@ -59,12 +62,14 @@ public class PortalRepositoryImpl implements IPortalRepository {
List<AdvancedPortal> portals = new ArrayList<>(); List<AdvancedPortal> portals = new ArrayList<>();
List<String> allFiles = dataStorage.listAllFiles(fileLocation, false); List<String> allFiles = dataStorage.listAllFiles(fileLocation, false);
for (String fileName : allFiles) { for (String fileName : allFiles) {
AdvancedPortal portal = AdvancedPortal portal = dataStorage.loadFile(
dataStorage.loadFile(AdvancedPortal.class, fileLocation + fileName); AdvancedPortal.class, fileLocation + fileName);
// Forces the name tag to be up-to-date on load // Forces the name tag to be up-to-date on load
String[] name = portal.getArgValues(NameTag.TAG_NAME); String[] name = portal.getArgValues(NameTag.TAG_NAME);
if (name != null && name.length > 0) { if (name != null && name.length > 0) {
portal.setArgValues(NameTag.TAG_NAME, new String[] {fileName.replace(".yaml", "")}); portal.setArgValues(
NameTag.TAG_NAME,
new String[] {fileName.replace(".yaml", "")});
} }
portals.add(portal); portals.add(portal);
} }

View File

@ -3,8 +3,8 @@ package com.sekwah.advancedportals.core.serializeddata;
import com.sekwah.advancedportals.core.data.Direction; import com.sekwah.advancedportals.core.data.Direction;
public class BlockLocation { public class BlockLocation {
// These should be treated as final, they only are not for serialization
// These should be treated as final, they only are not for serialization purposes // purposes
private final int posX; private final int posX;
private final int posY; private final int posY;
@ -51,10 +51,9 @@ public class BlockLocation {
} }
public boolean equals(BlockLocation location) { public boolean equals(BlockLocation location) {
return location.posX == this.posX return location.posX == this.posX && location.posY == this.posY
&& location.posY == this.posY && location.posZ == this.posZ
&& location.posZ == this.posZ && location.worldName.equals(this.worldName);
&& location.worldName.equals(this.worldName);
} }
public double distanceTo(BlockLocation pos) { public double distanceTo(BlockLocation pos) {
@ -73,6 +72,7 @@ public class BlockLocation {
} }
public BlockLocation addY(int offsetY) { public BlockLocation addY(int offsetY) {
return new BlockLocation(this.worldName, this.posX, (this.posY + offsetY), this.posZ); return new BlockLocation(this.worldName, this.posX,
(this.posY + offsetY), this.posZ);
} }
} }

View File

@ -3,22 +3,19 @@ package com.sekwah.advancedportals.core.serializeddata;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.sekwah.advancedportals.core.AdvancedPortalsCore; import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.inspector.TagInspector;
import org.yaml.snakeyaml.nodes.Tag;
import java.io.*; import java.io.*;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.inspector.TagInspector;
import org.yaml.snakeyaml.nodes.Tag;
public class DataStorage { public class DataStorage {
private final File dataFolder; private final File dataFolder;
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
@ -30,10 +27,10 @@ public class DataStorage {
} }
private Yaml getYaml(Class<? extends Object> clazz) { private Yaml getYaml(Class<? extends Object> clazz) {
LoaderOptions loaderOptions = new LoaderOptions(); LoaderOptions loaderOptions = new LoaderOptions();
TagInspector tagInspector = tag -> tag.getClassName().equals(clazz.getName()); TagInspector tagInspector =
tag -> tag.getClassName().equals(clazz.getName());
loaderOptions.setTagInspector(tagInspector); loaderOptions.setTagInspector(tagInspector);
@ -44,7 +41,10 @@ public class DataStorage {
representer.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); representer.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
var constructor = new ReflectiveConstructor(clazz, loaderOptions); var constructor = new ReflectiveConstructor(clazz, loaderOptions);
AdvancedPortalsCore.getInstance().getModule().getInjector().injectMembers(constructor); AdvancedPortalsCore.getInstance()
.getModule()
.getInjector()
.injectMembers(constructor);
return new Yaml(constructor, representer); return new Yaml(constructor, representer);
} }
@ -64,16 +64,15 @@ public class DataStorage {
if (yamlResource == null) { if (yamlResource == null) {
try { try {
return dataHolder.getDeclaredConstructor().newInstance(); return dataHolder.getDeclaredConstructor().newInstance();
} catch (InstantiationException } catch (InstantiationException | IllegalAccessException
| IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
| NoSuchMethodException
| InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
Yaml yaml = getYaml(dataHolder); Yaml yaml = getYaml(dataHolder);
try (BufferedReader bufReader = new BufferedReader(new InputStreamReader(yamlResource))) { try (BufferedReader bufReader =
new BufferedReader(new InputStreamReader(yamlResource))) {
return yaml.loadAs(bufReader, dataHolder); return yaml.loadAs(bufReader, dataHolder);
} catch (Exception e) { } catch (Exception e) {
infoLogger.warning("Failed to load file: " + location); infoLogger.warning("Failed to load file: " + location);
@ -85,7 +84,8 @@ public class DataStorage {
public boolean storeFile(Object dataHolder, String location) { public boolean storeFile(Object dataHolder, String location) {
Yaml yaml = getYaml(dataHolder.getClass()); Yaml yaml = getYaml(dataHolder.getClass());
File outFile = new File(this.dataFolder, location); File outFile = new File(this.dataFolder, location);
if (!outFile.getParentFile().exists() && !outFile.getParentFile().mkdirs()) { if (!outFile.getParentFile().exists()
&& !outFile.getParentFile().mkdirs()) {
infoLogger.warning("Failed to create folder for file: " + location); infoLogger.warning("Failed to create folder for file: " + location);
} }
@ -103,8 +103,8 @@ public class DataStorage {
* Copies the specified file out of the plugin and into the plugins folder. * Copies the specified file out of the plugin and into the plugins folder.
* *
* @param fileLoc * @param fileLoc
* @return if the file is copied, will be false if override is false and the file already * @return if the file is copied, will be false if override is false and the
* existed. * file already existed.
*/ */
public boolean copyDefaultFile(String fileLoc, boolean overwrite) { public boolean copyDefaultFile(String fileLoc, boolean overwrite) {
return this.copyDefaultFile(fileLoc, fileLoc, overwrite); return this.copyDefaultFile(fileLoc, fileLoc, overwrite);
@ -115,10 +115,11 @@ public class DataStorage {
* *
* @param sourceLoc - location of the file in the jar * @param sourceLoc - location of the file in the jar
* @param fileLoc - location to save the file * @param fileLoc - location to save the file
* @return if the file is copied, will be false if override is false and the file already * @return if the file is copied, will be false if override is false and the
* existed. * file already existed.
*/ */
public boolean copyDefaultFile(String sourceLoc, String fileLoc, boolean overwrite) { public boolean copyDefaultFile(String sourceLoc, String fileLoc,
boolean overwrite) {
File outFile = new File(this.dataFolder, fileLoc); File outFile = new File(this.dataFolder, fileLoc);
if (!outFile.exists()) { if (!outFile.exists()) {
outFile.getParentFile().mkdirs(); outFile.getParentFile().mkdirs();
@ -126,7 +127,8 @@ public class DataStorage {
if (!outFile.exists() || overwrite) { if (!outFile.exists() || overwrite) {
try { try {
InputStream inputStream = InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream(sourceLoc); this.getClass().getClassLoader().getResourceAsStream(
sourceLoc);
if (inputStream == null) { if (inputStream == null) {
return false; return false;
} }
@ -134,11 +136,10 @@ public class DataStorage {
writeToFile(inputStream, outFile); writeToFile(inputStream, outFile);
} catch (NullPointerException e) { } catch (NullPointerException e) {
e.printStackTrace(); e.printStackTrace();
this.infoLogger.warning( this.infoLogger.warning("Could not load " + sourceLoc
"Could not load " + ". The file does"
+ sourceLoc + ("not exist or there has been an "
+ ". The file does" + "error reading the file."));
+ "not exist or there has been an error reading the file.");
return false; return false;
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
@ -152,8 +153,8 @@ public class DataStorage {
} }
/** /**
* A method to try to grab the files from the plugin and if its in the plugin folder load from * A method to try to grab the files from the plugin and if its in the
* there instead. * plugin folder load from there instead.
* *
* <p> * <p>
* *
@ -172,14 +173,14 @@ public class DataStorage {
} else { } else {
try { try {
copyDefaultFile(location, false); copyDefaultFile(location, false);
return this.getClass().getClassLoader().getResourceAsStream(location); return this.getClass().getClassLoader().getResourceAsStream(
location);
} catch (NullPointerException e) { } catch (NullPointerException e) {
e.printStackTrace(); e.printStackTrace();
this.infoLogger.warning( this.infoLogger.warning("Could not load " + location
"Could not load " + ". The file does"
+ location + ("not exist or there has been an "
+ ". The file does" + "error reading the file."));
+ "not exist or there has been an error reading the file.");
return null; return null;
} }
} }
@ -194,7 +195,8 @@ public class DataStorage {
} }
} }
private void writeToFile(InputStream inputStream, File outFile) throws IOException { private void writeToFile(InputStream inputStream, File outFile)
throws IOException {
try (FileOutputStream outStream = new FileOutputStream(outFile)) { try (FileOutputStream outStream = new FileOutputStream(outFile)) {
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int len; int len;
@ -209,7 +211,8 @@ public class DataStorage {
return new File(this.dataFolder, name).exists(); return new File(this.dataFolder, name).exists();
} }
public List<String> listAllFiles(String fileLocation, boolean trimExtension) { public List<String> listAllFiles(String fileLocation,
boolean trimExtension) {
return listAllFiles(fileLocation, trimExtension, null); return listAllFiles(fileLocation, trimExtension, null);
} }
@ -219,7 +222,8 @@ public class DataStorage {
* @param extension - if null will not filter by extension * @param extension - if null will not filter by extension
* @return * @return
*/ */
public List<String> listAllFiles(String fileLocation, boolean trimExtension, String extension) { public List<String> listAllFiles(String fileLocation, boolean trimExtension,
String extension) {
File directory = new File(dataFolder, fileLocation); File directory = new File(dataFolder, fileLocation);
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
@ -230,7 +234,8 @@ public class DataStorage {
if (file.isFile()) { if (file.isFile()) {
String fileName = file.getName(); String fileName = file.getName();
boolean extensionMatches = boolean extensionMatches =
(extension == null || fileName.endsWith("." + extension)); (extension == null
|| fileName.endsWith("." + extension));
if (extensionMatches) { if (extensionMatches) {
if (trimExtension) { if (trimExtension) {
@ -245,7 +250,9 @@ public class DataStorage {
} }
} }
} else { } else {
infoLogger.warning("Directory does not exist or is not a directory: " + fileLocation); infoLogger.warning(
"Directory does not exist or is not a directory: "
+ fileLocation);
} }
return list; return list;
} }

View File

@ -1,7 +1,6 @@
package com.sekwah.advancedportals.core.serializeddata; package com.sekwah.advancedportals.core.serializeddata;
public class DataTag { public class DataTag {
public final String NAME; public final String NAME;
public final String[] VALUES; public final String[] VALUES;

View File

@ -3,32 +3,44 @@ package com.sekwah.advancedportals.core.serializeddata;
import java.util.HashMap; import java.util.HashMap;
/** /**
* Possibly one of the only files in this package not designed to be serialised. * Possibly one of the only files in this package not designed to be
* serialised.
* *
* <p>Any temporary data about players will be stored here and cleaned up when the player leaves the * <p>Any temporary data about players will be stored here and cleaned up when
* server. * the player leaves the server.
* *
* <p>This is not a place to store long term data e.g. if you want to make a player unable to use a * <p>This is not a place to store long term data e.g. if you want to make a
* portal over hours/days. * player unable to use a portal over hours/days.
*/ */
public class PlayerData { public class PlayerData {
/**
/** Portal selection position 1 */ * Portal selection position 1
*/
private BlockLocation pos1; private BlockLocation pos1;
/** Portal selection position 2 */ /**
* Portal selection position 2
*/
private BlockLocation pos2; private BlockLocation pos2;
/** If to show portals near the player */ /**
* If to show portals near the player
*/
private boolean portalVisible = false; private boolean portalVisible = false;
/** If to show destination blocks near the player */ /**
* If to show destination blocks near the player
*/
private boolean destiVisible; private boolean destiVisible;
/** If the player is in a portal. Stops re-triggering. */ /**
* If the player is in a portal. Stops re-triggering.
*/
private transient boolean isInPortal = false; private transient boolean isInPortal = false;
/** The next time System.currentTimeMillis() a player can use a portal. */ /**
* The next time System.currentTimeMillis() a player can use a portal.
*/
private transient long joinCooldown; private transient long joinCooldown;
private transient long netherPortalCooldown; private transient long netherPortalCooldown;
@ -94,7 +106,8 @@ public class PlayerData {
} }
public void setNetherPortalCooldown(long netherPortalCooldown) { public void setNetherPortalCooldown(long netherPortalCooldown) {
this.netherPortalCooldown = System.currentTimeMillis() + netherPortalCooldown; this.netherPortalCooldown =
System.currentTimeMillis() + netherPortalCooldown;
} }
public boolean hasJoinCooldown() { public boolean hasJoinCooldown() {
@ -106,12 +119,13 @@ public class PlayerData {
} }
public void setPortalCooldown(String portalName, long cooldown) { public void setPortalCooldown(String portalName, long cooldown) {
perPortalCooldowns.put(portalName, System.currentTimeMillis() + cooldown); perPortalCooldowns.put(portalName,
System.currentTimeMillis() + cooldown);
} }
public boolean hasPortalCooldown(String portalName) { public boolean hasPortalCooldown(String portalName) {
return perPortalCooldowns.containsKey(portalName) return perPortalCooldowns.containsKey(portalName)
&& System.currentTimeMillis() < perPortalCooldowns.get(portalName); && System.currentTimeMillis() < perPortalCooldowns.get(portalName);
} }
public double getPortalCooldownLeft(String portalName) { public double getPortalCooldownLeft(String portalName) {

View File

@ -1,7 +1,6 @@
package com.sekwah.advancedportals.core.serializeddata; package com.sekwah.advancedportals.core.serializeddata;
public class PlayerLocation extends WorldLocation { public class PlayerLocation extends WorldLocation {
private final float yaw; private final float yaw;
private final float pitch; private final float pitch;
@ -12,14 +11,15 @@ public class PlayerLocation extends WorldLocation {
this.pitch = 0; this.pitch = 0;
} }
public PlayerLocation(String worldName, double posX, double posY, double posZ) { public PlayerLocation(String worldName, double posX, double posY,
double posZ) {
super(worldName, posX, posY, posZ); super(worldName, posX, posY, posZ);
this.yaw = 0; this.yaw = 0;
this.pitch = 0; this.pitch = 0;
} }
public PlayerLocation( public PlayerLocation(String worldName, double posX, double posY,
String worldName, double posX, double posY, double posZ, float yaw, float pitch) { double posZ, float yaw, float pitch) {
super(worldName, posX, posY, posZ); super(worldName, posX, posY, posZ);
this.yaw = yaw; this.yaw = yaw;
this.pitch = pitch; this.pitch = pitch;

View File

@ -1,23 +1,21 @@
package com.sekwah.advancedportals.core.serializeddata; package com.sekwah.advancedportals.core.serializeddata;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.*; import org.yaml.snakeyaml.nodes.*;
import sun.misc.Unsafe; import sun.misc.Unsafe;
import javax.inject.Inject;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReflectiveConstructor<T> extends Constructor { public class ReflectiveConstructor<T> extends Constructor {
private static final Unsafe unsafe = getUnsafe(); private static final Unsafe unsafe = getUnsafe();
private final Class<T> clazz; private final Class<T> clazz;
@Inject @Inject private InfoLogger infoLogger;
private InfoLogger infoLogger;
public ReflectiveConstructor(Class<T> clazz, LoaderOptions loadingConfig) { public ReflectiveConstructor(Class<T> clazz, LoaderOptions loadingConfig) {
super(clazz, loadingConfig); super(clazz, loadingConfig);
@ -34,10 +32,11 @@ public class ReflectiveConstructor<T> extends Constructor {
return constructFromMappingNode(currentClass, (MappingNode) node); return constructFromMappingNode(currentClass, (MappingNode) node);
} else if (node instanceof ScalarNode scalarNode) { } else if (node instanceof ScalarNode scalarNode) {
return constructFromScalarNode(scalarNode); return constructFromScalarNode(scalarNode);
} else if(node instanceof SequenceNode sequenceNode) { } else if (node instanceof SequenceNode sequenceNode) {
return constructFromSequenceNode(sequenceNode); return constructFromSequenceNode(sequenceNode);
} else { } else {
infoLogger.warning("Unexpected node type encountered: " + node.getClass().getSimpleName()); infoLogger.warning("Unexpected node type encountered: "
+ node.getClass().getSimpleName());
return null; return null;
} }
} }
@ -58,9 +57,10 @@ public class ReflectiveConstructor<T> extends Constructor {
return array; return array;
} }
private <U> Object constructFromMappingNode(Class<U> currentClass, MappingNode mappingNode) { private <U> Object constructFromMappingNode(Class<U> currentClass,
MappingNode mappingNode) {
// if the class is a hashmap, loop over the values and construct the objects // if the class is a hashmap, loop over the values and construct the
// objects
if (currentClass.equals(HashMap.class)) { if (currentClass.equals(HashMap.class)) {
Map<String, Object> values = new HashMap<>(); Map<String, Object> values = new HashMap<>();
for (NodeTuple tuple : mappingNode.getValue()) { for (NodeTuple tuple : mappingNode.getValue()) {
@ -71,18 +71,23 @@ public class ReflectiveConstructor<T> extends Constructor {
if (node instanceof ScalarNode scalarNode) { if (node instanceof ScalarNode scalarNode) {
var constructedItem = constructFromScalarNode(scalarNode); var constructedItem = constructFromScalarNode(scalarNode);
values.put(key, constructedItem); values.put(key, constructedItem);
} else if(node instanceof SequenceNode sequenceNode) { } else if (node instanceof SequenceNode sequenceNode) {
var constructedItem = constructFromSequenceNode(sequenceNode); var constructedItem =
constructFromSequenceNode(sequenceNode);
values.put(key, constructedItem); values.put(key, constructedItem);
} else if (node instanceof MappingNode mappingNodeChild) { } else if (node instanceof MappingNode mappingNodeChild) {
try { try {
Object value = constructFromMappingNode(Object.class, mappingNodeChild); Object value = constructFromMappingNode(
Object.class, mappingNodeChild);
values.put(key, value); values.put(key, value);
} catch (Exception e) { } catch (Exception e) {
infoLogger.warning("Failed to construct object from mapping node: " + e.getMessage()); infoLogger.warning(
"Failed to construct object from mapping node: "
+ e.getMessage());
} }
} else { } else {
infoLogger.warning("Unexpected node type encountered: " + node.getClass().getSimpleName()); infoLogger.warning("Unexpected node type encountered: "
+ node.getClass().getSimpleName());
} }
} }
return values; return values;
@ -93,11 +98,14 @@ public class ReflectiveConstructor<T> extends Constructor {
try { try {
instance = currentClass.getDeclaredConstructor().newInstance(); instance = currentClass.getDeclaredConstructor().newInstance();
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
infoLogger.info("No default constructor found for " + currentClass.getName() + ", using unsafe allocation."); infoLogger.info("No default constructor found for "
+ currentClass.getName()
+ ", using unsafe allocation.");
instance = unsafe.allocateInstance(currentClass); instance = unsafe.allocateInstance(currentClass);
} }
Map<String, Object> mappedValues = mapMappingNode(currentClass, mappingNode); Map<String, Object> mappedValues =
mapMappingNode(currentClass, mappingNode);
Field[] fields = getAllFields(currentClass); Field[] fields = getAllFields(currentClass);
for (Field field : fields) { for (Field field : fields) {
@ -111,19 +119,28 @@ public class ReflectiveConstructor<T> extends Constructor {
setField(instance, field, value); setField(instance, field, value);
} else { } else {
infoLogger.warning("Field " + field.getName() + " not found in mapping node " + instance.getClass().getName() + " will use default value."); infoLogger.warning("Field " + field.getName()
+ " not found in mapping node "
+ instance.getClass().getName()
+ " will use default value.");
} }
} } catch (Exception e) {
catch (Exception e) { infoLogger.warning("Failed to set field " + field.getName()
infoLogger.warning("Failed to set field " + field.getName() + " in " + currentClass.getName() + ": " + e.getMessage()); + " in " + currentClass.getName()
+ ": " + e.getMessage());
infoLogger.error(e); infoLogger.error(e);
throw new RuntimeException("Failed to set field " + field.getName() + " in " + currentClass.getName(), e); throw new RuntimeException("Failed to set field "
+ field.getName() + " in "
+ currentClass.getName(),
e);
} }
} }
return instance; return instance;
} catch (Exception e) { } catch (Exception e) {
infoLogger.warning("Failed to instantiate " + currentClass.getName() + ": " + e.getMessage()); infoLogger.warning("Failed to instantiate " + currentClass.getName()
throw new RuntimeException("Failed to instantiate " + currentClass.getName(), e); + ": " + e.getMessage());
throw new RuntimeException(
"Failed to instantiate " + currentClass.getName(), e);
} }
} }
@ -142,7 +159,8 @@ public class ReflectiveConstructor<T> extends Constructor {
return super.constructObject(scalarNode); return super.constructObject(scalarNode);
} }
private Map<String, Object> mapMappingNode(Class<?> currentClass, MappingNode mappingNode) { private Map<String, Object> mapMappingNode(Class<?> currentClass,
MappingNode mappingNode) {
Map<String, Object> values = new HashMap<>(); Map<String, Object> values = new HashMap<>();
for (NodeTuple tuple : mappingNode.getValue()) { for (NodeTuple tuple : mappingNode.getValue()) {
var key = (String) super.constructObject(tuple.getKeyNode()); var key = (String) super.constructObject(tuple.getKeyNode());
@ -154,13 +172,16 @@ public class ReflectiveConstructor<T> extends Constructor {
} else if (node instanceof MappingNode mappingNodeChild) { } else if (node instanceof MappingNode mappingNodeChild) {
try { try {
var field = currentClass.getDeclaredField(key); var field = currentClass.getDeclaredField(key);
Object value = constructFromMappingNode(field.getType(), mappingNodeChild); Object value = constructFromMappingNode(field.getType(),
mappingNodeChild);
values.put(key, value); values.put(key, value);
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
infoLogger.warning("Field " + key + " not found on " + currentClass.getName()); infoLogger.warning("Field " + key + " not found on "
+ currentClass.getName());
} }
} else { } else {
infoLogger.warning("Expected mapping node: " + node.getClass().getSimpleName()); infoLogger.warning("Expected mapping node: "
+ node.getClass().getSimpleName());
} }
} }
return values; return values;
@ -169,14 +190,14 @@ public class ReflectiveConstructor<T> extends Constructor {
/** /**
* Check and convert value types e.g. double to float * Check and convert value types e.g. double to float
*/ */
private void setField(Object instance, Field field, Object value) throws IllegalAccessException { private void setField(Object instance, Field field, Object value)
throws IllegalAccessException {
// Check for numeric type compatibility and cast if necessary // Check for numeric type compatibility and cast if necessary
if (field.getType() == float.class && value instanceof Double) { if (field.getType() == float.class &&value instanceof Double) {
value = ((Double) value).floatValue(); value = ((Double) value).floatValue();
} else if (field.getType() == int.class && value instanceof Long) { } else if (field.getType() == int.class &&value instanceof Long) {
value = ((Long) value).intValue(); value = ((Long) value).intValue();
} else if (field.getType() == short.class && value instanceof Integer) { } else if (field.getType() == short.class &&value instanceof Integer) {
value = ((Integer) value).shortValue(); value = ((Integer) value).shortValue();
} else if (field.getType() == byte.class && value instanceof Integer) { } else if (field.getType() == byte.class && value instanceof Integer) {
value = ((Integer) value).byteValue(); value = ((Integer) value).byteValue();
@ -186,7 +207,6 @@ public class ReflectiveConstructor<T> extends Constructor {
field.set(instance, value); field.set(instance, value);
} }
private static Unsafe getUnsafe() { private static Unsafe getUnsafe() {
try { try {
Field f = Unsafe.class.getDeclaredField("theUnsafe"); Field f = Unsafe.class.getDeclaredField("theUnsafe");

View File

@ -5,7 +5,6 @@ import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
public class ReflectiveRepresenter extends Representer { public class ReflectiveRepresenter extends Representer {
public ReflectiveRepresenter(DumperOptions options) { public ReflectiveRepresenter(DumperOptions options) {
super(options); super(options);
this.getPropertyUtils().setBeanAccess(BeanAccess.FIELD); this.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);

View File

@ -1,19 +1,17 @@
package com.sekwah.advancedportals.core.serializeddata; package com.sekwah.advancedportals.core.serializeddata;
public class WorldLocation extends Vector { public class WorldLocation extends Vector {
public final String worldName; public final String worldName;
public WorldLocation(String worldName, double posX, double posY, double posZ) { public WorldLocation(String worldName, double posX, double posY,
double posZ) {
super(posX, posY, posZ); super(posX, posY, posZ);
this.worldName = worldName; this.worldName = worldName;
} }
public BlockLocation toBlockPos() { public BlockLocation toBlockPos() {
return new BlockLocation( return new BlockLocation(this.worldName, (int) Math.floor(this.x),
this.worldName, (int) Math.floor(this.y),
(int) Math.floor(this.x), (int) Math.floor(this.z));
(int) Math.floor(this.y),
(int) Math.floor(this.z));
} }
} }

View File

@ -1,8 +1,9 @@
package com.sekwah.advancedportals.core.serializeddata.config; package com.sekwah.advancedportals.core.serializeddata.config;
/** To store the data for config */ /**
* To store the data for config
*/
public class Config { public class Config {
public boolean useOnlySpecialAxe = true; public boolean useOnlySpecialAxe = true;
public String selectorMaterial = "IRON_AXE"; public String selectorMaterial = "IRON_AXE";

View File

@ -1,7 +1,3 @@
package com.sekwah.advancedportals.core.services; package com.sekwah.advancedportals.core.services;
public enum Creation { public enum Creation { SUCCESS, NAME_IN_USE, TAG_REJECTED }
SUCCESS,
NAME_IN_USE,
TAG_REJECTED
}

View File

@ -9,17 +9,14 @@ import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation; import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.inject.Singleton; import javax.inject.Singleton;
@Singleton @Singleton
public class DestinationServices { public class DestinationServices {
@Inject private IDestinationRepository destinationRepository; @Inject private IDestinationRepository destinationRepository;
@Inject TagRegistry tagRegistry; @Inject TagRegistry tagRegistry;
@ -43,38 +40,40 @@ public class DestinationServices {
} }
} }
public Destination createDesti(PlayerLocation playerLocation, List<DataTag> tags) { public Destination createDesti(PlayerLocation playerLocation,
List<DataTag> tags) {
return createDesti(null, playerLocation, tags); return createDesti(null, playerLocation, tags);
} }
public Destination createDesti( public Destination createDesti(PlayerContainer player,
PlayerContainer player, PlayerLocation playerLocation, List<DataTag> tags) { PlayerLocation playerLocation,
List<DataTag> tags) {
// Find the tag with the "name" NAME // Find the tag with the "name" NAME
DataTag nameTag = DataTag nameTag = tags.stream()
tags.stream().filter(tag -> tag.NAME.equals("name")).findFirst().orElse(null); .filter(tag -> tag.NAME.equals("name"))
.findFirst()
.orElse(null);
String name = nameTag == null ? null : nameTag.VALUES[0]; String name = nameTag == null ? null : nameTag.VALUES[0];
// If the name is null, send an error saying that the name is required. // If the name is null, send an error saying that the name is required.
if (nameTag == null) { if (nameTag == null) {
if (player != null) if (player != null)
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("desti.error.noname"));
+ Lang.translate("desti.error.noname"));
return null; return null;
} }
if (name == null || name.equals("")) { if (name == null || name.equals("")) {
if (player != null) if (player != null)
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
+ Lang.translate("command.error.noname"));
return null; return null;
} else if (this.destinationRepository.containsKey(name)) { } else if (this.destinationRepository.containsKey(name)) {
if (player != null) if (player != null)
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translateInsertVariables(
+ Lang.translateInsertVariables("command.error.nametaken", name)); "command.error.nametaken", name));
return null; return null;
} }
@ -83,7 +82,8 @@ public class DestinationServices {
desti.setArgValues(portalTag); desti.setArgValues(portalTag);
} }
for (DataTag destiTag : tags) { for (DataTag destiTag : tags) {
Tag.Creation creation = tagRegistry.getCreationHandler(destiTag.NAME); Tag.Creation creation =
tagRegistry.getCreationHandler(destiTag.NAME);
if (creation != null) { if (creation != null) {
if (!creation.created(desti, player, destiTag.VALUES)) { if (!creation.created(desti, player, destiTag.VALUES)) {
return null; return null;
@ -98,13 +98,14 @@ public class DestinationServices {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("desti.error.save")); + Lang.translate("desti.error.save"));
} }
return desti; return desti;
} }
public boolean removeDestination(String name, PlayerContainer playerContainer) { public boolean removeDestination(String name,
PlayerContainer playerContainer) {
this.destinationCache.remove(name); this.destinationCache.remove(name);
if (this.destinationRepository.containsKey(name)) { if (this.destinationRepository.containsKey(name)) {
this.destinationRepository.delete(name); this.destinationRepository.delete(name);
@ -117,9 +118,11 @@ public class DestinationServices {
return destinationCache.get(name); return destinationCache.get(name);
} }
public boolean teleportToDestination(String name, PlayerContainer playerContainer) { public boolean teleportToDestination(String name,
PlayerContainer playerContainer) {
if (this.destinationRepository.containsKey(name)) { if (this.destinationRepository.containsKey(name)) {
playerContainer.teleport(this.destinationRepository.get(name).getLoc()); playerContainer.teleport(
this.destinationRepository.get(name).getLoc());
return true; return true;
} }
return false; return false;

View File

@ -7,17 +7,16 @@ import com.sekwah.advancedportals.core.repository.IPlayerDataRepository;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerData; import com.sekwah.advancedportals.core.serializeddata.PlayerData;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import javax.inject.Singleton; import javax.inject.Singleton;
@Singleton @Singleton
public final class PlayerDataServices { public final class PlayerDataServices {
/**
/** Possibly change to the cache map Aztec was talking about */ * Possibly change to the cache map Aztec was talking about
*/
private Map<UUID, PlayerData> tempDataMap = new HashMap<>(); private Map<UUID, PlayerData> tempDataMap = new HashMap<>();
@Inject private IPlayerDataRepository tempDataRepository; @Inject private IPlayerDataRepository tempDataRepository;
@ -25,16 +24,14 @@ public final class PlayerDataServices {
@Inject private ConfigRepository configRepository; @Inject private ConfigRepository configRepository;
public PlayerData getPlayerData(PlayerContainer player) { public PlayerData getPlayerData(PlayerContainer player) {
return tempDataMap.computeIfAbsent( return tempDataMap.computeIfAbsent(player.getUUID(), uuid -> {
player.getUUID(), var tempData = tempDataRepository.get(player.getUUID().toString());
uuid -> {
var tempData = tempDataRepository.get(player.getUUID().toString());
if (tempData == null) { if (tempData == null) {
tempData = new PlayerData(); tempData = new PlayerData();
} }
return tempData; return tempData;
}); });
} }
public void setJoinCooldown(PlayerContainer player) { public void setJoinCooldown(PlayerContainer player) {
@ -43,24 +40,22 @@ public final class PlayerDataServices {
} }
public void playerLeave(PlayerContainer player) { public void playerLeave(PlayerContainer player) {
tempDataRepository.save(player.getUUID().toString(), getPlayerData(player)); tempDataRepository.save(player.getUUID().toString(),
getPlayerData(player));
tempDataMap.remove(player.getUUID()); tempDataMap.remove(player.getUUID());
} }
public void playerSelectorActivate( public void playerSelectorActivate(PlayerContainer player,
PlayerContainer player, BlockLocation blockLoc, boolean leftClick) { BlockLocation blockLoc,
boolean leftClick) {
var tempData = getPlayerData(player); var tempData = getPlayerData(player);
if (leftClick) { if (leftClick) {
tempData.setPos1(blockLoc); tempData.setPos1(blockLoc);
} else { } else {
tempData.setPos2(blockLoc); tempData.setPos2(blockLoc);
} }
player.sendMessage( player.sendMessage(Lang.translateInsertVariables(
Lang.translateInsertVariables( "portal.selector.poschange", leftClick ? "1" : "2",
"portal.selector.poschange", blockLoc.getPosX(), blockLoc.getPosY(), blockLoc.getPosZ()));
leftClick ? "1" : "2",
blockLoc.getPosX(),
blockLoc.getPosY(),
blockLoc.getPosZ()));
} }
} }

View File

@ -14,14 +14,11 @@ import com.sekwah.advancedportals.core.tags.activation.NameTag;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.util.PlayerUtils; import com.sekwah.advancedportals.core.util.PlayerUtils;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.*; import java.util.*;
import javax.inject.Singleton; import javax.inject.Singleton;
@Singleton @Singleton
public class PortalServices { public class PortalServices {
@Inject private IPortalRepository portalRepository; @Inject private IPortalRepository portalRepository;
@Inject private transient PlayerDataServices playerDataServices; @Inject private transient PlayerDataServices playerDataServices;
@ -47,7 +44,8 @@ public class PortalServices {
public boolean inPortalRegionProtected(BlockLocation loc) { public boolean inPortalRegionProtected(BlockLocation loc) {
for (AdvancedPortal portal : portalCache.values()) { for (AdvancedPortal portal : portalCache.values()) {
if (portal.isLocationInPortal(loc, configRepository.getProtectionRadius())) { if (portal.isLocationInPortal(
loc, configRepository.getProtectionRadius())) {
return true; return true;
} }
} }
@ -56,7 +54,8 @@ public class PortalServices {
public boolean inPortalRegionProtected(PlayerLocation loc) { public boolean inPortalRegionProtected(PlayerLocation loc) {
for (AdvancedPortal portal : portalCache.values()) { for (AdvancedPortal portal : portalCache.values()) {
if (portal.isLocationInPortal(loc, configRepository.getProtectionRadius())) { if (portal.isLocationInPortal(
loc, configRepository.getProtectionRadius())) {
return true; return true;
} }
} }
@ -73,7 +72,6 @@ public class PortalServices {
} }
public void playerMove(PlayerContainer player, PlayerLocation toLoc) { public void playerMove(PlayerContainer player, PlayerLocation toLoc) {
var blockLoc = toLoc.toBlockPos(); var blockLoc = toLoc.toBlockPos();
var blockEntityTopLoc = blockLoc.addY(player.getHeight()); var blockEntityTopLoc = blockLoc.addY(player.getHeight());
var world = player.getWorld(); var world = player.getWorld();
@ -82,9 +80,10 @@ public class PortalServices {
var notInPortal = true; var notInPortal = true;
for (AdvancedPortal portal : portalCache.values()) { for (AdvancedPortal portal : portalCache.values()) {
if ((portal.isLocationInPortal(toLoc) && portal.isTriggerBlock(blockMaterial)) if ((portal.isLocationInPortal(toLoc)
|| (portal.isLocationInPortal(blockEntityTopLoc) && portal.isTriggerBlock(blockMaterial))
&& portal.isTriggerBlock(blockEntityTopMaterial))) { || (portal.isLocationInPortal(blockEntityTopLoc)
&& portal.isTriggerBlock(blockEntityTopMaterial))) {
notInPortal = false; notInPortal = false;
if (portal.activate(player, true)) { if (portal.activate(player, true)) {
return; return;
@ -118,62 +117,67 @@ public class PortalServices {
return false; return false;
} }
public AdvancedPortal createPortal(BlockLocation pos1, BlockLocation pos2, List<DataTag> tags) { public AdvancedPortal createPortal(BlockLocation pos1, BlockLocation pos2,
List<DataTag> tags) {
return createPortal(null, pos1, pos2, tags); return createPortal(null, pos1, pos2, tags);
} }
public AdvancedPortal createPortal(PlayerContainer player, ArrayList<DataTag> tags) { public AdvancedPortal createPortal(PlayerContainer player,
ArrayList<DataTag> tags) {
PlayerData tempData = playerDataServices.getPlayerData(player); PlayerData tempData = playerDataServices.getPlayerData(player);
if (tempData.getPos1() == null || tempData.getPos2() == null) { if (tempData.getPos1() == null || tempData.getPos2() == null) {
player.sendMessage( player.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("portal.error.selection.missing")); + Lang.translate("portal.error.selection.missing"));
return null; return null;
} }
if (!tempData.getPos1().getWorldName().equals(tempData.getPos2().getWorldName())) { if (!tempData.getPos1().getWorldName().equals(
tempData.getPos2().getWorldName())) {
player.sendMessage( player.sendMessage(
Lang.translate("messageprefix.negative") Lang.translate("messageprefix.negative")
+ Lang.translate("portal.error.selection.differentworlds")); + Lang.translate("portal.error.selection.differentworlds"));
return null; return null;
} }
return createPortal(player, tempData.getPos1(), tempData.getPos2(), tags); return createPortal(player, tempData.getPos1(), tempData.getPos2(),
tags);
} }
public AdvancedPortal createPortal( public AdvancedPortal createPortal(PlayerContainer player,
PlayerContainer player, BlockLocation pos1, BlockLocation pos2, List<DataTag> tags) { BlockLocation pos1, BlockLocation pos2,
List<DataTag> tags) {
// Find the tag with the "name" NAME // Find the tag with the "name" NAME
DataTag nameTag = DataTag nameTag = tags.stream()
tags.stream() .filter(tag -> tag.NAME.equals(NameTag.TAG_NAME))
.filter(tag -> tag.NAME.equals(NameTag.TAG_NAME)) .findFirst()
.findFirst() .orElse(null);
.orElse(null);
String name = nameTag == null ? null : nameTag.VALUES[0]; String name = nameTag == null ? null : nameTag.VALUES[0];
if (nameTag == null || name == null || name.isEmpty()) { if (nameTag == null || name == null || name.isEmpty()) {
if (player != null) if (player != null)
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
+ Lang.translate("command.error.noname"));
return null; return null;
} else if (this.portalRepository.containsKey(name)) { } else if (this.portalRepository.containsKey(name)) {
if (player != null) if (player != null)
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translateInsertVariables(
+ Lang.translateInsertVariables("command.error.nametaken", name)); "command.error.nametaken", name));
return null; return null;
} }
AdvancedPortal portal = new AdvancedPortal(pos1, pos2, tagRegistry, playerDataServices); AdvancedPortal portal =
new AdvancedPortal(pos1, pos2, tagRegistry, playerDataServices);
for (DataTag portalTag : tags) { for (DataTag portalTag : tags) {
portal.setArgValues(portalTag); portal.setArgValues(portalTag);
} }
for (DataTag portalTag : tags) { for (DataTag portalTag : tags) {
Tag.Creation creation = tagRegistry.getCreationHandler(portalTag.NAME); Tag.Creation creation =
tagRegistry.getCreationHandler(portalTag.NAME);
if (creation != null) { if (creation != null) {
if (!creation.created(portal, player, portalTag.VALUES)) { if (!creation.created(portal, player, portalTag.VALUES)) {
return null; return null;
@ -190,9 +194,8 @@ public class PortalServices {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
if (player != null) if (player != null)
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("portal.error.save"));
+ Lang.translate("portal.error.save"));
} }
return portal; return portal;

View File

@ -13,26 +13,20 @@ import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.util.PlayerUtils; import com.sekwah.advancedportals.core.util.PlayerUtils;
import com.sekwah.advancedportals.core.warphandler.ActivationData; import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.annotation.Nullable;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import javax.annotation.Nullable;
public class CooldownTag implements Tag.Activation, Tag.Creation { public class CooldownTag implements Tag.Activation, Tag.Creation {
@Inject transient PlayerDataServices playerDataServices;
@Inject @Inject transient ConfigRepository configRepository;
transient PlayerDataServices playerDataServices;
@Inject @Inject private InfoLogger infoLogger;
transient ConfigRepository configRepository;
@Inject
private InfoLogger infoLogger;
public static String TAG_NAME = "cooldown"; public static String TAG_NAME = "cooldown";
private final TagType[] tagTypes = new TagType[]{ TagType.PORTAL }; private final TagType[] tagTypes = new TagType[] {TagType.PORTAL};
@Override @Override
public TagType[] getTagTypes() { public TagType[] getTagTypes() {
@ -56,16 +50,22 @@ public class CooldownTag implements Tag.Activation, Tag.Creation {
} }
@Override @Override
public boolean preActivated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) { public boolean preActivated(TagTarget target, PlayerContainer player,
ActivationData activationData,
String[] argData) {
var playerData = playerDataServices.getPlayerData(player); var playerData = playerDataServices.getPlayerData(player);
if(target instanceof AdvancedPortal portal) { if (target instanceof AdvancedPortal portal) {
var portalName = portal.getName(); var portalName = portal.getName();
if(playerData.hasPortalCooldown(portalName)) { if (playerData.hasPortalCooldown(portalName)) {
var cooldown = (int) Math.ceil(playerData.getPortalCooldownLeft(portalName) / 1000D); var cooldown = (int) Math.ceil(
player.sendMessage(Lang.translateInsertVariables("portal.cooldown.individual", cooldown, playerData.getPortalCooldownLeft(portalName) / 1000D);
Lang.translate(cooldown == 1 ? "time.second" : "time.seconds"))); player.sendMessage(Lang.translateInsertVariables(
if(configRepository.playFailSound()) { "portal.cooldown.individual", cooldown,
player.playSound("block.portal.travel", 0.05f, new Random().nextFloat() * 0.4F + 0.8F); Lang.translate(cooldown == 1 ? "time.second"
: "time.seconds")));
if (configRepository.playFailSound()) {
player.playSound("block.portal.travel", 0.05f,
new Random().nextFloat() * 0.4F + 0.8F);
} }
return false; return false;
} }
@ -75,37 +75,44 @@ public class CooldownTag implements Tag.Activation, Tag.Creation {
} }
@Override @Override
public void postActivated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) { public void postActivated(TagTarget target, PlayerContainer player,
if(activationData.hasActivated()) { ActivationData activationData, String[] argData) {
if(target instanceof AdvancedPortal portal) { if (activationData.hasActivated()) {
if (target instanceof AdvancedPortal portal) {
var playerData = playerDataServices.getPlayerData(player); var playerData = playerDataServices.getPlayerData(player);
try { try {
playerData.setPortalCooldown(portal.getName(), Integer.parseInt(argData[0]) * 1000); playerData.setPortalCooldown(
portal.getName(), Integer.parseInt(argData[0]) * 1000);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
infoLogger.warning("Cooldown tag failed to set cooldown for portal: " + portal.getName() + " with value: " + argData[0]); infoLogger.warning(
"Cooldown tag failed to set cooldown for portal: "
+ portal.getName() + " with value: " + argData[0]);
} }
} }
} }
} }
@Override @Override
public boolean activated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) { public boolean activated(TagTarget target, PlayerContainer player,
ActivationData activationData, String[] argData) {
return true; return true;
} }
@Override @Override
public boolean created(TagTarget target, PlayerContainer player, String[] argData) { public boolean created(TagTarget target, PlayerContainer player,
String[] argData) {
try { try {
Integer.parseInt(argData[0]); Integer.parseInt(argData[0]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("tag.cooldown.fail")); player.sendMessage(Lang.translate("messageprefix.negative")
+ Lang.translate("tag.cooldown.fail"));
return false; return false;
} }
return true; return true;
} }
@Override @Override
public void destroyed(TagTarget target, PlayerContainer player, String[] argData) { public void destroyed(TagTarget target, PlayerContainer player,
String[] argData) {
} }
} }

View File

@ -10,13 +10,10 @@ import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.ActivationData; import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split { public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
public static String TAG_NAME = "destination"; public static String TAG_NAME = "destination";
@Inject DestinationServices destinationServices; @Inject DestinationServices destinationServices;
@ -45,8 +42,8 @@ public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
} }
@Override @Override
public boolean preActivated( public boolean preActivated(TagTarget target, PlayerContainer player,
TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData) { ActivationData activeData, String[] argData) {
// Check that the destination exists. // Check that the destination exists.
for (String destiName : destinationServices.getDestinationNames()) { for (String destiName : destinationServices.getDestinationNames()) {
if (destiName.equalsIgnoreCase(argData[0])) { if (destiName.equalsIgnoreCase(argData[0])) {
@ -57,19 +54,15 @@ public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
} }
@Override @Override
public void postActivated( public void postActivated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activationData, String[] argData) {
PlayerContainer player, }
ActivationData activationData,
String[] argData) {}
@Override @Override
public boolean activated( public boolean activated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activationData, String[] argData) {
PlayerContainer player, Destination destination =
ActivationData activationData, destinationServices.getDestination(argData[0]);
String[] argData) {
Destination destination = destinationServices.getDestination(argData[0]);
if (destination != null) { if (destination != null) {
var warpEffectVisual = warpEffectRegistry.getVisualEffect("ender"); var warpEffectVisual = warpEffectRegistry.getVisualEffect("ender");
if (warpEffectVisual != null) { if (warpEffectVisual != null) {

View File

@ -4,24 +4,23 @@ import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.registry.TagTarget; import com.sekwah.advancedportals.core.registry.TagTarget;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /**
* The name of the destination or portal. * The name of the destination or portal.
* *
* <p>Most of the implementation of this tag is external, this is just to allow for the tag to be * <p>Most of the implementation of this tag is external, this is just to allow
* used. * for the tag to be used.
* *
* <p>Most tags shouldn't be like this unless they are to be paired with another tag. * <p>Most tags shouldn't be like this unless they are to be paired with
* another tag.
*/ */
public class NameTag implements Tag.AutoComplete, Tag.Creation { public class NameTag implements Tag.AutoComplete, Tag.Creation {
public static String TAG_NAME = "name"; public static String TAG_NAME = "name";
private final TagType[] tagTypes = new TagType[] {TagType.PORTAL, TagType.DESTINATION}; private final TagType[] tagTypes =
new TagType[] {TagType.PORTAL, TagType.DESTINATION};
@Override @Override
public TagType[] getTagTypes() { public TagType[] getTagTypes() {
@ -55,13 +54,13 @@ public class NameTag implements Tag.AutoComplete, Tag.Creation {
} }
@Override @Override
public boolean created(TagTarget target, PlayerContainer player, String[] argData) { public boolean created(TagTarget target, PlayerContainer player,
String[] argData) {
if (argData.length > 0) { if (argData.length > 0) {
String name = argData[0]; String name = argData[0];
if (name.contains(" ")) { if (name.contains(" ")) {
player.sendMessage( player.sendMessage(Lang.translate("messageprefix.negative")
Lang.translate("messageprefix.negative") + Lang.translate("tag.name.error.nospaces"));
+ Lang.translate("tag.name.error.nospaces"));
return false; return false;
} }
} }
@ -69,5 +68,7 @@ public class NameTag implements Tag.AutoComplete, Tag.Creation {
} }
@Override @Override
public void destroyed(TagTarget target, PlayerContainer player, String[] argData) {} public void destroyed(TagTarget target, PlayerContainer player,
String[] argData) {
}
} }

View File

@ -8,12 +8,10 @@ import com.sekwah.advancedportals.core.util.InfoLogger;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.ActivationData; import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.inject.Inject; import javax.inject.Inject;
public class PermissionTag implements Tag.Activation { public class PermissionTag implements Tag.Activation {
@Inject transient PlayerDataServices playerDataServices; @Inject transient PlayerDataServices playerDataServices;
@Inject transient ConfigRepository configRepository; @Inject transient ConfigRepository configRepository;
@ -48,8 +46,8 @@ public class PermissionTag implements Tag.Activation {
} }
@Override @Override
public boolean preActivated( public boolean preActivated(TagTarget target, PlayerContainer player,
TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData) { ActivationData activeData, String[] argData) {
if (!player.hasPermission(argData[1])) { if (!player.hasPermission(argData[1])) {
player.sendMessage(Lang.translate("portal.error.nopermission")); player.sendMessage(Lang.translate("portal.error.nopermission"));
return false; return false;
@ -58,18 +56,13 @@ public class PermissionTag implements Tag.Activation {
} }
@Override @Override
public void postActivated( public void postActivated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activationData, String[] argData) {
PlayerContainer player, }
ActivationData activationData,
String[] argData) {}
@Override @Override
public boolean activated( public boolean activated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activationData, String[] argData) {
PlayerContainer player,
ActivationData activationData,
String[] argData) {
return true; return true;
} }
} }

View File

@ -4,13 +4,10 @@ import com.google.inject.Inject;
import com.sekwah.advancedportals.core.connector.containers.ServerContainer; import com.sekwah.advancedportals.core.connector.containers.ServerContainer;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.Tag; import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class TriggerBlockTag implements Tag.AutoComplete, Tag.Split { public class TriggerBlockTag implements Tag.AutoComplete, Tag.Split {
@Inject private ServerContainer serverContainer; @Inject private ServerContainer serverContainer;
public static String TAG_NAME = "triggerblock"; public static String TAG_NAME = "triggerblock";

View File

@ -2,31 +2,30 @@ package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import java.awt.*; import java.awt.*;
public class Debug { public class Debug {
public static boolean addMarker( public static boolean addMarker(PlayerContainer player,
PlayerContainer player, BlockLocation blockPos, String name,
BlockLocation blockPos, Color color, int milliseconds) {
String name,
Color color,
int milliseconds) {
FriendlyDataOutput out = new FriendlyDataOutput(); FriendlyDataOutput out = new FriendlyDataOutput();
out.writeBlock(blockPos); out.writeBlock(blockPos);
out.writeInt(color(color)); out.writeInt(color(color));
out.writeUtf(name); out.writeUtf(name);
out.writeInt(milliseconds); out.writeInt(milliseconds);
return player.sendPacket("minecraft:debug/game_test_add_marker", out.toByteArray()); return player.sendPacket("minecraft:debug/game_test_add_marker",
out.toByteArray());
} }
public static boolean clear(PlayerContainer player) { public static boolean clear(PlayerContainer player) {
FriendlyDataOutput out = new FriendlyDataOutput(); FriendlyDataOutput out = new FriendlyDataOutput();
return player.sendPacket("minecraft:debug/game_test_clear", out.toByteArray()); return player.sendPacket("minecraft:debug/game_test_clear",
out.toByteArray());
} }
public static int color(Color color) { public static int color(Color color) {
return color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); return color(color.getRed(), color.getGreen(), color.getBlue(),
color.getAlpha());
} }
public static int color(int r, int g, int b) { public static int color(int r, int g, int b) {

View File

@ -1,16 +1,15 @@
package com.sekwah.advancedportals.core.util; package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.EncoderException; import io.netty.handler.codec.EncoderException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
/** Meant to be similar to FriendlyByteBuf if you have used that before. */ /**
* Meant to be similar to FriendlyByteBuf if you have used that before.
*/
public class FriendlyDataOutput { public class FriendlyDataOutput {
private final ByteBuf dataOutput; private final ByteBuf dataOutput;
public FriendlyDataOutput() { public FriendlyDataOutput() {
@ -51,14 +50,16 @@ public class FriendlyDataOutput {
public void writeUtf(String text, int maxLength) { public void writeUtf(String text, int maxLength) {
if (text.length() > maxLength) { if (text.length() > maxLength) {
throw new EncoderException( throw new EncoderException("String too big (was " + text.length()
"String too big (was " + text.length() + " characters, max " + maxLength + ")"); + " characters, max " + maxLength
+ ")");
} else { } else {
byte[] abyte = text.getBytes(StandardCharsets.UTF_8); byte[] abyte = text.getBytes(StandardCharsets.UTF_8);
int i = getMaxEncodedUtfLength(maxLength); int i = getMaxEncodedUtfLength(maxLength);
if (abyte.length > i) { if (abyte.length > i) {
throw new EncoderException( throw new EncoderException("String too big (was " + abyte.length
"String too big (was " + abyte.length + " bytes encoded, max " + i + ")"); + " bytes encoded, max " + i
+ ")");
} else { } else {
this.writeVarInt(abyte.length); this.writeVarInt(abyte.length);
this.writeBytes(abyte); this.writeBytes(abyte);
@ -99,10 +100,11 @@ public class FriendlyDataOutput {
// Only for block serialising and such // Only for block serialising and such
private static final int PACKED_X_LENGTH = private static final int PACKED_X_LENGTH =
26; // 1 + Mth.log2(Mth.smallestEncompassingPowerOfTwo(30000000)) (im not gonna add all 26; // 1 + Mth.log2(Mth.smallestEncompassingPowerOfTwo(30000000)) (im
// the mojang math stuff to calculate this. // not gonna add all the mojang math stuff to calculate this.
private static final int PACKED_Z_LENGTH = PACKED_X_LENGTH; private static final int PACKED_Z_LENGTH = PACKED_X_LENGTH;
public static final int PACKED_Y_LENGTH = 64 - PACKED_X_LENGTH - PACKED_Z_LENGTH; public static final int PACKED_Y_LENGTH =
64 - PACKED_X_LENGTH - PACKED_Z_LENGTH;
private static final long PACKED_X_MASK = (1L << PACKED_X_LENGTH) - 1L; private static final long PACKED_X_MASK = (1L << PACKED_X_LENGTH) - 1L;
private static final long PACKED_Y_MASK = (1L << PACKED_Y_LENGTH) - 1L; private static final long PACKED_Y_MASK = (1L << PACKED_Y_LENGTH) - 1L;
private static final long PACKED_Z_MASK = (1L << PACKED_Z_LENGTH) - 1L; private static final long PACKED_Z_MASK = (1L << PACKED_Z_LENGTH) - 1L;
@ -114,7 +116,6 @@ public class FriendlyDataOutput {
} }
private long blockAsLong(BlockLocation blockLoc) { private long blockAsLong(BlockLocation blockLoc) {
long i = 0L; long i = 0L;
i |= ((long) blockLoc.getPosX() & PACKED_X_MASK) << X_OFFSET; i |= ((long) blockLoc.getPosX() & PACKED_X_MASK) << X_OFFSET;
i |= ((long) blockLoc.getPosY() & PACKED_Y_MASK) << 0; i |= ((long) blockLoc.getPosY() & PACKED_Y_MASK) << 0;

View File

@ -2,36 +2,44 @@ package com.sekwah.advancedportals.core.util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import javax.inject.Singleton; import javax.inject.Singleton;
/** For all delayed and repeating tasks. */ /**
* For all delayed and repeating tasks.
*/
@Singleton @Singleton
public final class GameScheduler { public final class GameScheduler {
private final ArrayList<DelayedGameTickEvent> newTickEvents =
private final ArrayList<DelayedGameTickEvent> newTickEvents = new ArrayList<>(); new ArrayList<>();
private final ArrayList<DelayedGameTickEvent> delayedTickEvents = new ArrayList<>(); private final ArrayList<DelayedGameTickEvent> delayedTickEvents =
new ArrayList<>();
public void tick() { public void tick() {
this.delayedTickEvents.addAll(this.newTickEvents); this.delayedTickEvents.addAll(this.newTickEvents);
this.newTickEvents.clear(); this.newTickEvents.clear();
Iterator<DelayedGameTickEvent> tickEventIterator = this.delayedTickEvents.iterator(); Iterator<DelayedGameTickEvent> tickEventIterator =
this.delayedTickEvents.iterator();
while (tickEventIterator.hasNext()) { while (tickEventIterator.hasNext()) {
DelayedGameTickEvent event = tickEventIterator.next(); DelayedGameTickEvent event = tickEventIterator.next();
event.tick(); event.tick();
if (event.shouldRun()) { if (event.shouldRun()) {
event.run(); event.run();
if (!(event instanceof DelayedGameIntervalEvent)) tickEventIterator.remove(); if (!(event instanceof DelayedGameIntervalEvent))
tickEventIterator.remove();
} }
} }
} }
public void delayedTickEvent(String name, Runnable consumer, int tickDelay) { public void delayedTickEvent(String name, Runnable consumer,
this.newTickEvents.add(new DelayedGameTickEvent(name, consumer, tickDelay)); int tickDelay) {
this.newTickEvents.add(
new DelayedGameTickEvent(name, consumer, tickDelay));
} }
public void intervalTickEvent(String name, Runnable consumer, int tickDelay, int interval) { public void intervalTickEvent(String name, Runnable consumer, int tickDelay,
this.newTickEvents.add(new DelayedGameIntervalEvent(name, consumer, tickDelay, interval)); int interval) {
this.newTickEvents.add(
new DelayedGameIntervalEvent(name, consumer, tickDelay, interval));
} }
public void clearAllEvents() { public void clearAllEvents() {
@ -40,7 +48,6 @@ public final class GameScheduler {
} }
public static class DelayedGameTickEvent { public static class DelayedGameTickEvent {
// So we can find it later and remove it if needed // So we can find it later and remove it if needed
public final String name; public final String name;
public final Runnable consumer; public final Runnable consumer;
@ -66,10 +73,10 @@ public final class GameScheduler {
} }
public static class DelayedGameIntervalEvent extends DelayedGameTickEvent { public static class DelayedGameIntervalEvent extends DelayedGameTickEvent {
public int interval; public int interval;
public DelayedGameIntervalEvent(String name, Runnable consumer, int ticks, int interval) { public DelayedGameIntervalEvent(String name, Runnable consumer,
int ticks, int interval) {
super(name, consumer, ticks); super(name, consumer, ticks);
this.interval = interval; this.interval = interval;
} }

View File

@ -1,7 +1,6 @@
package com.sekwah.advancedportals.core.util; package com.sekwah.advancedportals.core.util;
public abstract class InfoLogger { public abstract class InfoLogger {
/** /**
* Problematic messages * Problematic messages
* *

View File

@ -2,7 +2,6 @@ package com.sekwah.advancedportals.core.util;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.sekwah.advancedportals.core.serializeddata.DataStorage; import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;
@ -13,13 +12,12 @@ import java.util.Scanner;
/** /**
* @author sekwah41 * @author sekwah41
* <p>The language translation file for the game. Will always load english first so that if the * <p>The language translation file for the game. Will always load english
* translations are missing any then they are still readable and can then be translated. (It's * first so that if the translations are missing any then they are still
* better than a raw translate string) * readable and can then be translated. (It's better than a raw translate
* <p> * string) <p>
*/ */
public class Lang { public class Lang {
public static final Lang instance = new Lang(); public static final Lang instance = new Lang();
private final HashMap<String, String> languageMap = new HashMap<>(); private final HashMap<String, String> languageMap = new HashMap<>();
@ -39,8 +37,10 @@ public class Lang {
public static String translate(String s) { public static String translate(String s) {
if (instance.languageMap.containsKey(s)) { if (instance.languageMap.containsKey(s)) {
String translation = instance.languageMap.get(s); String translation = instance.languageMap.get(s);
// noinspection ALL (not sure what the specific warning is for escaped unicode) // noinspection ALL (not sure what the specific warning is for
translation = translation.replaceAll("&([0-9a-frk-ox])", "\u00A7$1"); // escaped unicode)
translation =
translation.replaceAll("&([0-9a-frk-ox])", "\u00A7$1");
return translation; return translation;
} else { } else {
return s; return s;
@ -50,13 +50,15 @@ public class Lang {
public static String translateInsertVariables(String s, Object... args) { public static String translateInsertVariables(String s, Object... args) {
String translation = translate(s); String translation = translate(s);
for (int i = 1; i <= args.length; i++) { for (int i = 1; i <= args.length; i++) {
translation = translation.replaceAll("%" + i + "\\$s", args[i - 1].toString()); translation = translation.replaceAll("%" + i + "\\$s",
args[i - 1].toString());
} }
return translation; return translation;
} }
public Map<String, String> getLanguageMap(String fileName) { public Map<String, String> getLanguageMap(String fileName) {
InputStream stream = this.dataStorage.loadResource("lang/" + fileName + ".lang"); InputStream stream =
this.dataStorage.loadResource("lang/" + fileName + ".lang");
if (stream != null) { if (stream != null) {
return Lang.parseLang(stream); return Lang.parseLang(stream);
} }
@ -65,7 +67,8 @@ public class Lang {
public Map<String, String> getInternalLanguageMap(String fileName) { public Map<String, String> getInternalLanguageMap(String fileName) {
InputStream stream = InputStream stream =
this.getClass().getClassLoader().getResourceAsStream("lang/" + fileName + ".lang"); this.getClass().getClassLoader().getResourceAsStream(
"lang/" + fileName + ".lang");
if (stream != null) { if (stream != null) {
return Lang.parseLang(stream); return Lang.parseLang(stream);
} }
@ -92,8 +95,8 @@ public class Lang {
} }
/** /**
* The default font is not monospaced, so this will likely be a little thinner to be on the safe * The default font is not monospaced, so this will likely be a little
* side * thinner to be on the safe side
* *
* @param title * @param title
* @return * @return
@ -103,29 +106,28 @@ public class Lang {
int eachSide = titleLength / 2; int eachSide = titleLength / 2;
return "\u00A7e" + "=".repeat(eachSide) + " " + title + " \u00A7e" + "=".repeat(eachSide); return "\u00A7e"
+ "=".repeat(eachSide) + " " + title + " \u00A7e"
+ "=".repeat(eachSide);
} }
private void injectTranslations(String fileName) { private void injectTranslations(String fileName) {
try { try {
URL url = URL url = Lang.instance.getClass().getClassLoader().getResource(
Lang.instance "lang/" + fileName + ".lang");
.getClass()
.getClassLoader()
.getResource("lang/" + fileName + ".lang");
if (url != null) { if (url != null) {
Map<String, String> initialMap = Lang.parseLang(url.openStream()); Map<String, String> initialMap =
Lang.parseLang(url.openStream());
Lang.instance.languageMap.putAll(initialMap); Lang.instance.languageMap.putAll(initialMap);
} else { } else {
this.infoLogger.warning( this.infoLogger.warning("Could not load " + fileName
"Could not load " + (".lang from within Advanced Portals "
+ fileName + "as it doesn't exist."));
+ ".lang from within Advanced Portals as it doesn't exist.");
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
this.infoLogger.warning( this.infoLogger.warning("Could not load " + fileName
"Could not load " + fileName + ".lang from within Advanced Portals."); + ".lang from within Advanced Portals.");
} }
Map<String, String> newLangMap = this.getLanguageMap(fileName); Map<String, String> newLangMap = this.getLanguageMap(fileName);

View File

@ -3,9 +3,11 @@ package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
public class PlayerUtils { public class PlayerUtils {
public static void throwPlayerBack(PlayerContainer player,
public static void throwPlayerBack(PlayerContainer player, double strength) { double strength) {
var playerLoc = player.getLoc().getDirection(); var playerLoc = player.getLoc().getDirection();
player.setVelocity(playerLoc.setY(0).normalize().multiply(-1).setY(0.5).multiply(strength)); player.setVelocity(
playerLoc.setY(0).normalize().multiply(-1).setY(0.5).multiply(
strength));
} }
} }

View File

@ -1,12 +1,10 @@
package com.sekwah.advancedportals.core.util; package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.serializeddata.DataTag; import com.sekwah.advancedportals.core.serializeddata.DataTag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
public class TagReader { public class TagReader {
public static boolean isClosedString(String[] args) { public static boolean isClosedString(String[] args) {
StringBuilder currentValue = new StringBuilder(); StringBuilder currentValue = new StringBuilder();
boolean inQuotes = false; boolean inQuotes = false;

View File

@ -8,7 +8,6 @@ import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
* @author sekwah41 * @author sekwah41
*/ */
public class ActivationData { public class ActivationData {
private boolean warpAllowed = true; private boolean warpAllowed = true;
public final boolean moveActivated; public final boolean moveActivated;
@ -28,15 +27,16 @@ public class ActivationData {
public void setWarpStatus(WarpedStatus warped) { public void setWarpStatus(WarpedStatus warped) {
if (this.warpStatus == WarpedStatus.WARPED) { if (this.warpStatus == WarpedStatus.WARPED) {
return; return;
} else if (this.warpStatus == WarpedStatus.ACTIVATED && warped != WarpedStatus.WARPED) { } else if (this.warpStatus == WarpedStatus.ACTIVATED
&& warped != WarpedStatus.WARPED) {
return; return;
} }
this.warpStatus = warped; this.warpStatus = warped;
} }
/** /**
* In case you need to set the status back down a step for whatever reason. However it is not * In case you need to set the status back down a step for whatever reason.
* recommended. * However it is not recommended.
* *
* @param warped * @param warped
*/ */
@ -57,11 +57,20 @@ public class ActivationData {
} }
public enum WarpedStatus { public enum WarpedStatus {
/** Player has moved or something major has happened. (only one of these should activate) */ /**
* Player has moved or something major has happened. (only one of these
* should activate)
*/
WARPED, WARPED,
/** Shows that the portal has been activated even if a major function is not performed. */ /**
* Shows that the portal has been activated even if a major function is
* not performed.
*/
ACTIVATED, ACTIVATED,
/** Nothing has activated on the portal (may need to come up with a new name) */ /**
* Nothing has activated on the portal (may need to come up with a new
* name)
*/
NOTACTIVATED; NOTACTIVATED;
} }
} }

View File

@ -2,34 +2,32 @@ package com.sekwah.advancedportals.core.warphandler;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.registry.TagTarget; import com.sekwah.advancedportals.core.registry.TagTarget;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /**
* If a tag can be used for any of them then either make it cast the target or if it doesn't need a * If a tag can be used for any of them then either make it cast the target or
* target then the exact same tag can be registered into both and ignore the portal info. * if it doesn't need a target then the exact same tag can be registered into
* both and ignore the portal info.
* *
* <p>Will probably make better documentation on how to do so or some tutorial videos though take a * <p>Will probably make better documentation on how to do so or some tutorial
* look at the source code on GitHub for how the current tags are added. * videos though take a look at the source code on GitHub for how the current
* tags are added.
* *
* <p>Also, not sure if its good practice or not in java however these all extend TagHandler, so * <p>Also, not sure if its good practice or not in java however these all
* they can be accepted in 1 method nicer than if they didn't * extend TagHandler, so they can be accepted in 1 method nicer than if they
* didn't
* *
* @author sekwah41 * @author sekwah41
*/ */
public interface Tag { public interface Tag {
/** /**
* By default, all tags should be able to use either. * By default, all tags should be able to use either.
* *
* <p>Though you may have use cases where you want to limit it to one or the other. * <p>Though you may have use cases where you want to limit it to one or the
* other.
*/ */
enum TagType { enum TagType { PORTAL, DESTINATION }
PORTAL,
DESTINATION
}
/** /**
* Used to flag where the auto complete should show more or less info. * Used to flag where the auto complete should show more or less info.
@ -40,41 +38,37 @@ public interface Tag {
String getName(); String getName();
@Nullable @Nullable String[] getAliases();
String[] getAliases();
String description(); String description();
interface AutoComplete extends Tag { interface AutoComplete extends Tag {
/** /**
* This is used to get the auto complete for the tag. This is called when the player is * This is used to get the auto complete for the tag. This is called
* typing the tag. * when the player is typing the tag.
* *
* @param argData * @param argData
* @return * @return
*/ */
@Nullable @Nullable List<String> autoComplete(String argData);
List<String> autoComplete(String argData);
@Nullable @Nullable String splitString();
String splitString();
} }
interface Split extends Tag { interface Split extends Tag {
/** /**
* This is used to split the tag into the arguments if multiple are supported * This is used to split the tag into the arguments if multiple are
* supported
* *
* @return null if the tag does not support splitting * @return null if the tag does not support splitting
*/ */
@Nullable @Nullable String splitString();
String splitString();
} }
/** The events for portal creation and destroying */ /**
* The events for portal creation and destroying
*/
interface Creation extends Tag { interface Creation extends Tag {
/** /**
* Example if the player does not have access to use the tag. * Example if the player does not have access to use the tag.
* *
@ -82,45 +76,46 @@ public interface Tag {
* @param argData * @param argData
* @return If the tag is valid or allowed creation * @return If the tag is valid or allowed creation
*/ */
boolean created(TagTarget target, PlayerContainer player, String[] argData); boolean created(TagTarget target, PlayerContainer player,
String[] argData);
/** /**
* Example if the player does not have access to remove the portal or destination. * Example if the player does not have access to remove the portal or
* destination.
* *
* @param player if null then removed by the server or a plugin * @param player if null then removed by the server or a plugin
* @param argData * @param argData
*/ */
void destroyed(TagTarget target, PlayerContainer player, String[] argData); void destroyed(TagTarget target, PlayerContainer player,
String[] argData);
} }
/** /**
* Order of activation Portal and Desti: preActivated activated postActivated * Order of activation Portal and Desti: preActivated activated
* postActivated
* *
* <p>Order of them combined: Portal.preActivated Portal.activated - when desti tag is hit (if * <p>Order of them combined: Portal.preActivated Portal.activated - when
* listed) then next two actions are activated - Desti.preActivate - Desti.activate * desti tag is hit (if listed) then next two actions are activated -
* Portal.postActivate - when desti tag is hit (if listed) then the next action is activated - * Desti.preActivate - Desti.activate Portal.postActivate - when desti tag
* Desti.postActivate * is hit (if listed) then the next action is activated - Desti.postActivate
*/ */
interface Activation extends Tag { interface Activation extends Tag {
/** /**
* Activates before the main part of activation. This should be for prechecks e.g. if the * Activates before the main part of activation. This should be for
* player has enough money before then taking the money in postActivated. * prechecks e.g. if the player has enough money before then taking the
* money in postActivated.
* *
* @param player * @param player
* @param activeData * @param activeData
* @param argData * @param argData
* @return If the tag has allowed the warp * @return If the tag has allowed the warp
*/ */
boolean preActivated( boolean preActivated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activeData, String[] argData);
PlayerContainer player,
ActivationData activeData,
String[] argData);
/** /**
* Activates after activation, should be used for actions such as removing money for a * Activates after activation, should be used for actions such as
* teleport. * removing money for a teleport.
* *
* <p>Any actions to do with player location should be done in activate * <p>Any actions to do with player location should be done in activate
* *
@ -128,55 +123,57 @@ public interface Tag {
* @param activationData * @param activationData
* @param argData * @param argData
*/ */
void postActivated( void postActivated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activationData, String[] argData);
PlayerContainer player,
ActivationData activationData,
String[] argData);
/** /**
* Activates if the portal is allowed from preActivating. Should be used to set the intended * Activates if the portal is allowed from preActivating. Should be used
* warp location * to set the intended warp location
* *
* <p>You should do some second checks if it can be dependent on the preActivate, the * <p>You should do some second checks if it can be dependent on the
* destination tags will also be triggered here if a desti is listed. * preActivate, the destination tags will also be triggered here if a
* desti is listed.
* *
* @param player * @param player
* @param activationData * @param activationData
* @param argData * @param argData
* @return Action performed (only return false if the tag failed to do anything) * @return Action performed (only return false if the tag failed to do
* anything)
*/ */
boolean activated( boolean activated(TagTarget target, PlayerContainer player,
TagTarget target, ActivationData activationData, String[] argData);
PlayerContainer player,
ActivationData activationData,
String[] argData);
} }
/** Triggers when a tag is added or removed from a portal or destination */ /**
* Triggers when a tag is added or removed from a portal or destination
*/
interface TagStatus extends Tag { interface TagStatus extends Tag {
/** /**
* If the user has access to add the tag (this does not include being added on creation) * If the user has access to add the tag (this does not include being
* added on creation)
* *
* @param target the target of the tag * @param target the target of the tag
* @param player if null then removed by the server or a plugin * @param player if null then removed by the server or a plugin
* @param argData the data for the tag * @param argData the data for the tag
* @param index the index of the tag in the list (if it is the only tag it will be 0) * @param index the index of the tag in the list (if it is the only tag
* it will be 0)
* @return if the tag will be added. * @return if the tag will be added.
*/ */
boolean tagAdded(TagTarget target, PlayerContainer player, int index, String argData); boolean tagAdded(TagTarget target, PlayerContainer player, int index,
String argData);
/** /**
* If the user has access to remove the tag (this does not include being added on * If the user has access to remove the tag (this does not include being
* destruction) * added on destruction)
* *
* @param target the target of the tag * @param target the target of the tag
* @param player if null then removed by the server or a plugin * @param player if null then removed by the server or a plugin
* @param argData the data of the tag to be removed * @param argData the data of the tag to be removed
* @param index the index of the tag in the list (if it is the only tag it will be 0) * @param index the index of the tag in the list (if it is the only tag
* it will be 0)
* @return if the tag will be removed. * @return if the tag will be removed.
*/ */
boolean tagRemoved(TagTarget target, PlayerContainer player, int index, String argData); boolean tagRemoved(TagTarget target, PlayerContainer player, int index,
String argData);
} }
} }

View File

@ -11,9 +11,9 @@ import org.bukkit.plugin.java.JavaPlugin;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.bukkit.plugin.java.JavaPlugin;
public class AdvancedPortalsPlugin extends JavaPlugin { public class AdvancedPortalsPlugin extends JavaPlugin {
private AdvancedPortalsCore portalsCore; private AdvancedPortalsCore portalsCore;
/** /**

View File

@ -17,11 +17,9 @@ import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.*; import org.bukkit.event.entity.*;
import org.bukkit.event.player.*; import org.bukkit.event.player.*;
import java.util.List;
/** /**
* Some of these will be passed to the core listener to handle the events, others it's easier to * Some of these will be passed to the core listener to handle the events,
* just check directly. * others it's easier to just check directly.
*/ */
public class Listeners implements Listener { public class Listeners implements Listener {
@ -60,9 +58,9 @@ public class Listeners implements Listener {
@EventHandler @EventHandler
public void onItemInteract(PlayerInteractEvent event) { public void onItemInteract(PlayerInteractEvent event) {
if (!event.isCancelled() if (!event.isCancelled()
&& (event.getAction() == Action.LEFT_CLICK_BLOCK && (event.getAction() == Action.LEFT_CLICK_BLOCK
|| event.getAction() == Action.RIGHT_CLICK_BLOCK) || event.getAction() == Action.RIGHT_CLICK_BLOCK)
&& event.getItem() != null) { && event.getItem() != null) {
Location blockloc = event.getClickedBlock().getLocation(); Location blockloc = event.getClickedBlock().getLocation();
boolean allowEvent = this.coreListeners.playerInteractWithBlock(new SpigotPlayerContainer(event.getPlayer()), boolean allowEvent = this.coreListeners.playerInteractWithBlock(new SpigotPlayerContainer(event.getPlayer()),
event.getClickedBlock().getType().toString(), event.getClickedBlock().getType().toString(),
@ -76,9 +74,10 @@ public class Listeners implements Listener {
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void spawnMobEvent(CreatureSpawnEvent event) { public void spawnMobEvent(CreatureSpawnEvent event) {
if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NETHER_PORTAL if (event.getSpawnReason()
&& portalServices.inPortalRegionProtected( == CreatureSpawnEvent.SpawnReason.NETHER_PORTAL
ContainerHelpers.toPlayerLocation(event.getLocation()))) { && portalServices.inPortalRegionProtected(
ContainerHelpers.toPlayerLocation(event.getLocation()))) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -90,18 +89,16 @@ public class Listeners implements Listener {
if (!configRepository.getStopWaterFlow()) { if (!configRepository.getStopWaterFlow()) {
return; return;
} }
if (!coreListeners.blockPlace( if (!coreListeners.blockPlace(null,
null, ContainerHelpers.toBlockLocation(
ContainerHelpers.toBlockLocation(event.getBlock().getLocation()), event.getBlock().getLocation()),
event.getBlock().getType().toString(), event.getBlock().getType().toString(),
null, null, null)
null) || !coreListeners.blockPlace(null,
|| !coreListeners.blockPlace( ContainerHelpers.toBlockLocation(
null, event.getToBlock().getLocation()),
ContainerHelpers.toBlockLocation(event.getToBlock().getLocation()), event.getBlock().getType().toString(),
event.getBlock().getType().toString(), null, null)) {
null,
null)) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -111,19 +108,21 @@ public class Listeners implements Listener {
var itemInHand = event.getPlayer().getItemInHand(); var itemInHand = event.getPlayer().getItemInHand();
if (!coreListeners.blockBreak( if (!coreListeners.blockBreak(
new SpigotPlayerContainer(event.getPlayer()), new SpigotPlayerContainer(event.getPlayer()),
ContainerHelpers.toBlockLocation(event.getBlock().getLocation()), ContainerHelpers.toBlockLocation(
event.getBlock().getLocation()),
event.getBlock().getType().toString(), event.getBlock().getType().toString(),
itemInHand == null ? null : itemInHand.getType().toString(), itemInHand == null ? null : itemInHand.getType().toString(),
itemInHand == null || itemInHand.getItemMeta() == null itemInHand == null || itemInHand.getItemMeta() == null
? null ? null
: itemInHand.getItemMeta().getDisplayName())) { : itemInHand.getItemMeta().getDisplayName())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onExplosion(EntityExplodeEvent event) { public void onExplosion(EntityExplodeEvent event) {
if (!configRepository.getPortalProtection()) return; if (!configRepository.getPortalProtection())
return;
List<Block> blockList = event.blockList(); List<Block> blockList = event.blockList();
for (int i = 0; i < blockList.size(); i++) { for (int i = 0; i < blockList.size(); i++) {

View File

@ -1,11 +1,9 @@
package com.sekwah.advancedportals.spigot; package com.sekwah.advancedportals.spigot;
import com.sekwah.advancedportals.core.util.InfoLogger; import com.sekwah.advancedportals.core.util.InfoLogger;
import java.util.logging.Level; import java.util.logging.Level;
public class SpigotInfoLogger extends InfoLogger { public class SpigotInfoLogger extends InfoLogger {
private final AdvancedPortalsPlugin plugin; private final AdvancedPortalsPlugin plugin;
public SpigotInfoLogger(AdvancedPortalsPlugin plugin) { public SpigotInfoLogger(AdvancedPortalsPlugin plugin) {

View File

@ -11,15 +11,12 @@ import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang; import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin; import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.spigot.commands.subcommands.portal.update.ConfigAccessor; import com.sekwah.advancedportals.spigot.commands.subcommands.portal.update.ConfigAccessor;
import org.bukkit.configuration.ConfigurationSection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.bukkit.configuration.ConfigurationSection;
public class UpdatePortalSubCommand implements SubCommand { public class UpdatePortalSubCommand implements SubCommand {
@Inject PortalServices portalServices; @Inject PortalServices portalServices;
@Inject DestinationServices destinationServices; @Inject DestinationServices destinationServices;
@ -29,43 +26,41 @@ public class UpdatePortalSubCommand implements SubCommand {
@Override @Override
public void onCommand(CommandSenderContainer sender, String[] args) { public void onCommand(CommandSenderContainer sender, String[] args) {
if (args.length > 1 && "confirm".equals(args[1])) { if (args.length > 1 && "confirm".equals(args[1])) {
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.positive")
Lang.translate("messageprefix.positive") + Lang.translateInsertVariables(
+ Lang.translateInsertVariables("command.portal.update.confirm")); "command.portal.update.confirm"));
int destinations = importDestinations(); int destinations = importDestinations();
int portals = importPortals(); int portals = importPortals();
sender.sendMessage( sender.sendMessage(
Lang.translate("messageprefix.positive") Lang.translate("messageprefix.positive")
+ Lang.translateInsertVariables( + Lang.translateInsertVariables(
"command.portal.update.complete", portals, destinations)); "command.portal.update.complete", portals, destinations));
return; return;
} }
sender.sendMessage( sender.sendMessage(Lang.translate("messageprefix.positive")
Lang.translate("messageprefix.positive") + Lang.translateInsertVariables(
+ Lang.translateInsertVariables( "command.portal.update", getPortalCount(),
"command.portal.update", getPortalCount(), getDestinationCount())); getDestinationCount()));
} }
private int importPortals() { private int importPortals() {
ConfigAccessor portalConfig = ConfigAccessor portalConfig = new ConfigAccessor(
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "portals.yaml"); AdvancedPortalsPlugin.getInstance(), "portals.yaml");
var config = portalConfig.getConfig(); var config = portalConfig.getConfig();
Set<String> portalSet = config.getKeys(false); Set<String> portalSet = config.getKeys(false);
int count = 0; int count = 0;
for (String portalName : portalSet) { for (String portalName : portalSet) {
BlockLocation pos1 = BlockLocation pos1 =
new BlockLocation( new BlockLocation(config.getString(portalName + ".world"),
config.getString(portalName + ".world"), config.getInt(portalName + ".pos1.X"),
config.getInt(portalName + ".pos1.X"), config.getInt(portalName + ".pos1.Y"),
config.getInt(portalName + ".pos1.Y"), config.getInt(portalName + ".pos1.Z"));
config.getInt(portalName + ".pos1.Z"));
BlockLocation pos2 = BlockLocation pos2 =
new BlockLocation( new BlockLocation(config.getString(portalName + ".world"),
config.getString(portalName + ".world"), config.getInt(portalName + ".pos2.X"),
config.getInt(portalName + ".pos2.X"), config.getInt(portalName + ".pos2.Y"),
config.getInt(portalName + ".pos2.Y"), config.getInt(portalName + ".pos2.Z"));
config.getInt(portalName + ".pos2.Z"));
List<DataTag> args = new ArrayList<>(); List<DataTag> args = new ArrayList<>();
args.add(new DataTag("name", portalName)); args.add(new DataTag("name", portalName));
var triggerblock = config.getString(portalName + ".triggerblock"); var triggerblock = config.getString(portalName + ".triggerblock");
@ -73,24 +68,26 @@ public class UpdatePortalSubCommand implements SubCommand {
args.add(new DataTag("triggerblock", triggerblock.split(","))); args.add(new DataTag("triggerblock", triggerblock.split(",")));
// It's called bungee as that's the implementation behind it // It's called bungee as that's the implementation behind it
var bungee = config.getString(portalName + ".bungee"); var bungee = config.getString(portalName + ".bungee");
if (bungee != null) args.add(new DataTag("bungee", bungee.split(","))); if (bungee != null)
args.add(new DataTag("bungee", bungee.split(",")));
var destination = config.getString(portalName + ".destination"); var destination = config.getString(portalName + ".destination");
if (destination != null) args.add(new DataTag("destination", destination.split(","))); if (destination != null)
args.add(new DataTag("destination", destination.split(",")));
ConfigurationSection portalConfigSection = config.getConfigurationSection(portalName); ConfigurationSection portalConfigSection =
config.getConfigurationSection(portalName);
ConfigurationSection portalArgsConf = ConfigurationSection portalArgsConf =
portalConfigSection.getConfigurationSection("portalArgs"); portalConfigSection.getConfigurationSection("portalArgs");
if (portalArgsConf != null) { if (portalArgsConf != null) {
Set<String> argsSet = portalArgsConf.getKeys(true); Set<String> argsSet = portalArgsConf.getKeys(true);
for (Object argName : argsSet.toArray()) { for (Object argName : argsSet.toArray()) {
// skip if it argName starts with command. // skip if it argName starts with command.
if (portalArgsConf.isString(argName.toString())) { if (portalArgsConf.isString(argName.toString())) {
args.add( args.add(new DataTag(
new DataTag( argName.toString(),
argName.toString(), portalArgsConf.getString(argName.toString())));
portalArgsConf.getString(argName.toString())));
} }
} }
} }
@ -104,16 +101,18 @@ public class UpdatePortalSubCommand implements SubCommand {
} }
} }
if (!commands.isEmpty()) { if (!commands.isEmpty()) {
args.add(new DataTag("commands", commands.toArray(new String[0]))); args.add(
new DataTag("commands", commands.toArray(new String[0])));
} }
args.stream() args.stream()
.filter(dataTag -> dataTag.NAME.startsWith("command.")) .filter(dataTag -> dataTag.NAME.startsWith("command."))
.toList() .toList()
.forEach(args::remove); .forEach(args::remove);
var portal = portalService.createPortal(pos1, pos2, args); var portal = portalService.createPortal(pos1, pos2, args);
if (portal != null) count++; if (portal != null)
count++;
} }
return count; return count;
@ -129,32 +128,32 @@ public class UpdatePortalSubCommand implements SubCommand {
} }
public int importDestinations() { public int importDestinations() {
ConfigAccessor destiConfig = ConfigAccessor destiConfig = new ConfigAccessor(
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "destinations.yaml"); AdvancedPortalsPlugin.getInstance(), "destinations.yaml");
var config = destiConfig.getConfig(); var config = destiConfig.getConfig();
Set<String> destiSet = config.getKeys(false); Set<String> destiSet = config.getKeys(false);
int count = 0; int count = 0;
for (String destiName : destiSet) { for (String destiName : destiSet) {
var destiPos = destiName + ".pos"; var destiPos = destiName + ".pos";
var desti = var desti = destinationServices.createDesti(
destinationServices.createDesti( new PlayerLocation(
new PlayerLocation( config.getString(destiName + ".world"),
config.getString(destiName + ".world"), config.getDouble(destiPos + ".X"),
config.getDouble(destiPos + ".X"), config.getDouble(destiPos + ".Y"),
config.getDouble(destiPos + ".Y"), config.getDouble(destiPos + ".Z"),
config.getDouble(destiPos + ".Z"), (float) config.getDouble(destiPos + ".yaw"),
(float) config.getDouble(destiPos + ".yaw"), (float) config.getDouble(destiPos + ".pitch")),
(float) config.getDouble(destiPos + ".pitch")), List.of(new DataTag("name", destiName)));
List.of(new DataTag("name", destiName))); if (desti != null)
if (desti != null) count++; count++;
} }
return count; return count;
} }
public int getDestinationCount() { public int getDestinationCount() {
ConfigAccessor destiConfig = ConfigAccessor destiConfig = new ConfigAccessor(
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "destinations.yaml"); AdvancedPortalsPlugin.getInstance(), "destinations.yaml");
var config = destiConfig.getConfig(); var config = destiConfig.getConfig();
Set<String> destiSet = config.getKeys(false); Set<String> destiSet = config.getKeys(false);
@ -162,8 +161,8 @@ public class UpdatePortalSubCommand implements SubCommand {
} }
public int getPortalCount() { public int getPortalCount() {
ConfigAccessor portalConfig = ConfigAccessor portalConfig = new ConfigAccessor(
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "portals.yaml"); AdvancedPortalsPlugin.getInstance(), "portals.yaml");
var config = portalConfig.getConfig(); var config = portalConfig.getConfig();
Set<String> portalSet = config.getKeys(false); Set<String> portalSet = config.getKeys(false);
@ -176,7 +175,8 @@ public class UpdatePortalSubCommand implements SubCommand {
} }
@Override @Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) { public List<String> onTabComplete(CommandSenderContainer sender,
String[] args) {
return null; return null;
} }

View File

@ -1,15 +1,13 @@
package com.sekwah.advancedportals.spigot.commands.subcommands.portal.update; package com.sekwah.advancedportals.spigot.commands.subcommands.portal.update;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public class ConfigAccessor { public class ConfigAccessor {
private final String fileName; private final String fileName;
private final JavaPlugin plugin; private final JavaPlugin plugin;
@ -25,7 +23,8 @@ public class ConfigAccessor {
public void reloadConfig() { public void reloadConfig() {
if (configFile == null) { if (configFile == null) {
File dataFolder = plugin.getDataFolder(); File dataFolder = plugin.getDataFolder();
if (dataFolder == null) throw new IllegalStateException(); if (dataFolder == null)
throw new IllegalStateException();
configFile = new File(dataFolder, fileName); configFile = new File(dataFolder, fileName);
} }
fileConfiguration = YamlConfiguration.loadConfiguration(configFile); fileConfiguration = YamlConfiguration.loadConfiguration(configFile);
@ -46,7 +45,8 @@ public class ConfigAccessor {
try { try {
getConfig().save(configFile); getConfig().save(configFile);
} catch (IOException ex) { } catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex); plugin.getLogger().log(
Level.SEVERE, "Could not save config to " + configFile, ex);
} }
} }
} }
@ -58,8 +58,8 @@ public class ConfigAccessor {
* this.plugin.saveResource(fileName, false); } } * this.plugin.saveResource(fileName, false); } }
*/ */
// New save default config saving code, it checks if the needed config is in the jar file before // New save default config saving code, it checks if the needed config is in
// overriding it. // the jar file before overriding it.
public void saveDefaultConfig() { public void saveDefaultConfig() {
if (configFile == null) { if (configFile == null) {
configFile = new File(plugin.getDataFolder(), fileName); configFile = new File(plugin.getDataFolder(), fileName);

View File

@ -2,16 +2,13 @@ package com.sekwah.advancedportals.spigot.connector.command;
import com.sekwah.advancedportals.core.commands.CommandTemplate; import com.sekwah.advancedportals.core.commands.CommandTemplate;
import com.sekwah.advancedportals.spigot.connector.container.SpigotCommandSenderContainer; import com.sekwah.advancedportals.spigot.connector.container.SpigotCommandSenderContainer;
import java.util.List;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter; import org.bukkit.command.TabCompleter;
import java.util.List;
public class SpigotCommandHandler implements CommandExecutor, TabCompleter { public class SpigotCommandHandler implements CommandExecutor, TabCompleter {
private final CommandTemplate commandExecutor; private final CommandTemplate commandExecutor;
public SpigotCommandHandler(CommandTemplate commandExecutor) { public SpigotCommandHandler(CommandTemplate commandExecutor) {
@ -19,17 +16,19 @@ public class SpigotCommandHandler implements CommandExecutor, TabCompleter {
} }
@Override @Override
public boolean onCommand( public boolean onCommand(CommandSender commandSender, Command command,
CommandSender commandSender, Command command, String s, String[] args) { String s, String[] args) {
this.commandExecutor.onCommand( this.commandExecutor.onCommand(
new SpigotCommandSenderContainer(commandSender), command.getName(), args); new SpigotCommandSenderContainer(commandSender), command.getName(),
args);
return true; return true;
} }
@Override @Override
public List<String> onTabComplete( public List<String> onTabComplete(CommandSender commandSender,
CommandSender commandSender, Command command, String s, String[] args) { Command command, String s,
String[] args) {
return this.commandExecutor.onTabComplete( return this.commandExecutor.onTabComplete(
new SpigotCommandSenderContainer(commandSender), args); new SpigotCommandSenderContainer(commandSender), args);
} }
} }

View File

@ -4,9 +4,10 @@ import com.sekwah.advancedportals.core.commands.CommandTemplate;
import com.sekwah.advancedportals.core.connector.commands.CommandRegister; import com.sekwah.advancedportals.core.connector.commands.CommandRegister;
import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin; import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin;
/** Register the CommandTemplate files to the appropriate system */ /**
* Register the CommandTemplate files to the appropriate system
*/
public class SpigotCommandRegister implements CommandRegister { public class SpigotCommandRegister implements CommandRegister {
private final AdvancedPortalsPlugin plugin; private final AdvancedPortalsPlugin plugin;
public SpigotCommandRegister(AdvancedPortalsPlugin plugin) { public SpigotCommandRegister(AdvancedPortalsPlugin plugin) {
@ -19,7 +20,9 @@ public class SpigotCommandRegister implements CommandRegister {
* @param commandName * @param commandName
* @param commandExecutor * @param commandExecutor
*/ */
public void registerCommand(String commandName, CommandTemplate commandExecutor) { public void registerCommand(String commandName,
this.plugin.getCommand(commandName).setExecutor(new SpigotCommandHandler(commandExecutor)); CommandTemplate commandExecutor) {
this.plugin.getCommand(commandName)
.setExecutor(new SpigotCommandHandler(commandExecutor));
} }
} }

View File

@ -1,12 +1,10 @@
package com.sekwah.advancedportals.spigot.connector.container; package com.sekwah.advancedportals.spigot.connector.container;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer; import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class SpigotCommandSenderContainer implements CommandSenderContainer { public class SpigotCommandSenderContainer implements CommandSenderContainer {
private final CommandSender sender; private final CommandSender sender;
public SpigotCommandSenderContainer(CommandSender commandSender) { public SpigotCommandSenderContainer(CommandSender commandSender) {

View File

@ -7,14 +7,15 @@ import com.sekwah.advancedportals.core.connector.containers.WorldContainer;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation; import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.serializeddata.Vector; import com.sekwah.advancedportals.core.serializeddata.Vector;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
/** Just a temporary container for whenever advanced portals needs to get data from a player */ /**
* Just a temporary container for whenever advanced portals needs to get data
* from a player
*/
public class SpigotEntityContainer implements EntityContainer { public class SpigotEntityContainer implements EntityContainer {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
private final Entity entity; private final Entity entity;
@ -26,20 +27,16 @@ public class SpigotEntityContainer implements EntityContainer {
@Override @Override
public PlayerLocation getLoc() { public PlayerLocation getLoc() {
Location loc = this.entity.getLocation(); Location loc = this.entity.getLocation();
return new PlayerLocation( return new PlayerLocation(loc.getWorld().getName(), loc.getX(),
loc.getWorld().getName(), loc.getY(), loc.getZ(), loc.getYaw(),
loc.getX(), loc.getPitch());
loc.getY(),
loc.getZ(),
loc.getYaw(),
loc.getPitch());
} }
@Override @Override
public BlockLocation getBlockLoc() { public BlockLocation getBlockLoc() {
Location loc = this.entity.getLocation(); Location loc = this.entity.getLocation();
return new BlockLocation( return new BlockLocation(loc.getWorld().getName(), loc.getBlockX(),
loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); loc.getBlockY(), loc.getBlockZ());
} }
@Override @Override
@ -49,12 +46,9 @@ public class SpigotEntityContainer implements EntityContainer {
@Override @Override
public boolean teleport(PlayerLocation location) { public boolean teleport(PlayerLocation location) {
return this.entity.teleport( return this.entity.teleport(new Location(
new Location( Bukkit.getWorld(location.getWorldName()), location.getPosX(),
Bukkit.getWorld(location.getWorldName()), location.getPosY(), location.getPosZ()));
location.getPosX(),
location.getPosY(),
location.getPosZ()));
} }
@Override @Override
@ -74,7 +68,7 @@ public class SpigotEntityContainer implements EntityContainer {
@Override @Override
public void setVelocity(Vector vector) { public void setVelocity(Vector vector) {
this.entity.setVelocity( this.entity.setVelocity(new org.bukkit.util.Vector(
new org.bukkit.util.Vector(vector.getX(), vector.getY(), vector.getZ())); vector.getX(), vector.getY(), vector.getZ()));
} }
} }

View File

@ -7,7 +7,8 @@ import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation; import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin; import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.spigot.reflection.MinecraftCustomPayload; import com.sekwah.advancedportals.spigot.reflection.MinecraftCustomPayload;
import java.util.Arrays;
import java.util.UUID;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@ -15,12 +16,12 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import java.util.Arrays; /**
import java.util.UUID; * Just a temporary container for whenever advanced portals needs to get data
* from a player
/** Just a temporary container for whenever advanced portals needs to get data from a player */ */
public class SpigotPlayerContainer extends SpigotEntityContainer implements PlayerContainer { public class SpigotPlayerContainer
extends SpigotEntityContainer implements PlayerContainer {
@Inject private AdvancedPortalsCore portalsCore; @Inject private AdvancedPortalsCore portalsCore;
private final Player player; private final Player player;
@ -47,12 +48,9 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
@Override @Override
public boolean teleport(PlayerLocation location) { public boolean teleport(PlayerLocation location) {
return this.player.teleport( return this.player.teleport(new Location(
new Location( Bukkit.getWorld(location.getWorldName()), location.getPosX(),
Bukkit.getWorld(location.getWorldName()), location.getPosY(), location.getPosZ()));
location.getPosX(),
location.getPosY(),
location.getPosZ()));
} }
@Override @Override
@ -65,7 +63,8 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
* @param material * @param material
*/ */
@Override @Override
public void sendFakeBlock(BlockLocation blockPos, String material) {} public void sendFakeBlock(BlockLocation blockPos, String material) {
}
/** /**
* Only 1.12 and below supported * Only 1.12 and below supported
@ -75,11 +74,15 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
* @param data * @param data
*/ */
@Override @Override
public void sendFakeBlockWithData(BlockLocation blockPos, String material, byte data) {} public void sendFakeBlockWithData(BlockLocation blockPos, String material,
byte data) {
}
@Override @Override
public void giveItem(String material, String itemName, String... itemDescription) { public void giveItem(String material, String itemName,
ItemStack regionselector = new ItemStack(Material.getMaterial(material)); String... itemDescription) {
ItemStack regionselector =
new ItemStack(Material.getMaterial(material));
ItemMeta selectorname = regionselector.getItemMeta(); ItemMeta selectorname = regionselector.getItemMeta();
selectorname.setDisplayName(itemName); selectorname.setDisplayName(itemName);
selectorname.setLore(Arrays.asList(itemDescription)); selectorname.setLore(Arrays.asList(itemDescription));
@ -90,9 +93,11 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
@Override @Override
public boolean sendPacket(String channel, byte[] bytes) { public boolean sendPacket(String channel, byte[] bytes) {
if (channel.startsWith("minecraft:")) { if (channel.startsWith("minecraft:")) {
return MinecraftCustomPayload.sendCustomPayload(player, channel, bytes); return MinecraftCustomPayload.sendCustomPayload(player, channel,
bytes);
} else { } else {
player.sendPluginMessage(AdvancedPortalsPlugin.getInstance(), channel, bytes); player.sendPluginMessage(AdvancedPortalsPlugin.getInstance(),
channel, bytes);
} }
return true; return true;
} }

View File

@ -3,18 +3,19 @@ package com.sekwah.advancedportals.spigot.connector.container;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer; import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.connector.containers.ServerContainer; import com.sekwah.advancedportals.core.connector.containers.ServerContainer;
import com.sekwah.advancedportals.core.connector.containers.WorldContainer; import com.sekwah.advancedportals.core.connector.containers.WorldContainer;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class SpigotServerContainer implements ServerContainer { public class SpigotServerContainer implements ServerContainer {
private final Server server; private final Server server;
private final List<String> triggerBlockList = Arrays.stream(Material.values()).filter(this::isAdvancedPortalBlock).map(Enum::name) private final List<String> triggerBlockList =
Arrays.stream(Material.values())
.filter(this::isAdvancedPortalBlock)
.map(Enum::name)
.toList(); .toList();
public SpigotServerContainer(Server server) { public SpigotServerContainer(Server server) {
@ -24,7 +25,7 @@ public class SpigotServerContainer implements ServerContainer {
@Override @Override
public WorldContainer getWorld(String name) { public WorldContainer getWorld(String name) {
var world = server.getWorld(name); var world = server.getWorld(name);
if(world != null) { if (world != null) {
return new SpigotWorldContainer(world); return new SpigotWorldContainer(world);
} else { } else {
return null; return null;
@ -34,7 +35,7 @@ public class SpigotServerContainer implements ServerContainer {
@Override @Override
public PlayerContainer getPlayer(String name) { public PlayerContainer getPlayer(String name) {
var player = server.getPlayer(name); var player = server.getPlayer(name);
if(player != null) { if (player != null) {
return new SpigotPlayerContainer(player); return new SpigotPlayerContainer(player);
} else { } else {
return null; return null;
@ -44,7 +45,7 @@ public class SpigotServerContainer implements ServerContainer {
@Override @Override
public PlayerContainer getPlayer(UUID name) { public PlayerContainer getPlayer(UUID name) {
var player = server.getPlayer(name); var player = server.getPlayer(name);
if(player != null) { if (player != null) {
return new SpigotPlayerContainer(player); return new SpigotPlayerContainer(player);
} else { } else {
return null; return null;
@ -58,9 +59,10 @@ public class SpigotServerContainer implements ServerContainer {
@Override @Override
public PlayerContainer[] getPlayers() { public PlayerContainer[] getPlayers() {
return server.getOnlinePlayers().stream() return server.getOnlinePlayers()
.map(SpigotPlayerContainer::new) .stream()
.toArray(PlayerContainer[]::new); .map(SpigotPlayerContainer::new)
.toArray(PlayerContainer[] ::new);
} }
// Check if it's a material compatible with making portals // Check if it's a material compatible with making portals

View File

@ -9,7 +9,6 @@ import org.bukkit.World;
import org.bukkit.block.data.Orientable; import org.bukkit.block.data.Orientable;
public class SpigotWorldContainer implements WorldContainer { public class SpigotWorldContainer implements WorldContainer {
private final World world; private final World world;
public SpigotWorldContainer(World world) { public SpigotWorldContainer(World world) {
@ -18,18 +17,27 @@ public class SpigotWorldContainer implements WorldContainer {
public void setBlock(BlockLocation location, String material) { public void setBlock(BlockLocation location, String material) {
Material mat = Material.getMaterial(material, false); Material mat = Material.getMaterial(material, false);
if(mat != null) this.world.getBlockAt(location.getPosX(), location.getPosY(), location.getPosZ()).setType(mat); if (mat != null)
this.world
.getBlockAt(location.getPosX(), location.getPosY(),
location.getPosZ())
.setType(mat);
} }
public String getBlock(BlockLocation location) { public String getBlock(BlockLocation location) {
return this.world.getBlockAt(location.getPosX(), location.getPosY(), location.getPosZ()).getType().toString(); return this.world
.getBlockAt(location.getPosX(), location.getPosY(),
location.getPosZ())
.getType()
.toString();
} }
@Override @Override
public BlockAxis getBlockAxis(BlockLocation location) { public BlockAxis getBlockAxis(BlockLocation location) {
var block = world.getBlockAt(location.getPosX(), location.getPosY(), location.getPosZ()); var block = world.getBlockAt(location.getPosX(), location.getPosY(),
location.getPosZ());
var matData = block.getState().getBlockData(); var matData = block.getState().getBlockData();
if(matData instanceof Orientable rotatable) { if (matData instanceof Orientable rotatable) {
try { try {
return BlockAxis.valueOf(rotatable.getAxis().toString()); return BlockAxis.valueOf(rotatable.getAxis().toString());
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -41,9 +49,10 @@ public class SpigotWorldContainer implements WorldContainer {
@Override @Override
public void setBlockAxis(BlockLocation location, BlockAxis axis) { public void setBlockAxis(BlockLocation location, BlockAxis axis) {
var block = world.getBlockAt(location.getPosX(), location.getPosY(), location.getPosZ()); var block = world.getBlockAt(location.getPosX(), location.getPosY(),
location.getPosZ());
var matData = block.getState().getBlockData(); var matData = block.getState().getBlockData();
if(matData instanceof Orientable rotatable) { if (matData instanceof Orientable rotatable) {
rotatable.setAxis(Axis.valueOf(axis.toString())); rotatable.setAxis(Axis.valueOf(axis.toString()));
block.setBlockData(rotatable); block.setBlockData(rotatable);
} }

View File

@ -3,14 +3,6 @@ package com.sekwah.advancedportals.spigot.metrics;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import java.io.*; import java.io.*;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -20,8 +12,13 @@ import java.util.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
/** /**
* bStats collects some data for plugin authors. * bStats collects some data for plugin authors.
@ -30,30 +27,25 @@ import javax.net.ssl.HttpsURLConnection;
*/ */
@SuppressWarnings({"WeakerAccess", "unused"}) @SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics { public class Metrics {
static { static {
// You can use the property to disable the check in your test environment // You can use the property to disable the check in your test
// environment
if (System.getProperty("bstats.relocatecheck") == null if (System.getProperty("bstats.relocatecheck") == null
|| !System.getProperty("bstats.relocatecheck").equals("false")) { || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little // Maven's Relocate is clever and changes strings, too. So we have
// "trick" ... :D // to use this little "trick" ... :D
final String defaultPackage = final String defaultPackage = new String(
new String( new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's',
new byte[] { '.', 'b', 'u', 'k', 'k', 'i', 't'});
'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', final String examplePackage = new String(new byte[] {
'k', 'k', 'i', 't' 'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
}); // We want to make sure nobody just copy & pastes the example and
final String examplePackage = // use the wrong package names
new String(
new byte[] {
'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'
});
// We want to make sure nobody just copy & pastes the example and use the wrong package
// names
if (Metrics.class.getPackage().getName().equals(defaultPackage) if (Metrics.class.getPackage().getName().equals(defaultPackage)
|| Metrics.class.getPackage().getName().equals(examplePackage)) { || Metrics.class.getPackage().getName().equals(
examplePackage)) {
throw new IllegalStateException( throw new IllegalStateException(
"bStats Metrics class has not been relocated correctly!"); "bStats Metrics class has not been relocated correctly!");
} }
} }
} }
@ -97,13 +89,14 @@ public class Metrics {
this.plugin = plugin; this.plugin = plugin;
// Get the config file // Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); File bStatsFolder =
new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yaml"); File configFile = new File(bStatsFolder, "config.yaml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); YamlConfiguration config =
YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists // Check if the config file exists
if (!config.isSet("serverUuid")) { if (!config.isSet("serverUuid")) {
// Add default values // Add default values
config.addDefault("enabled", true); config.addDefault("enabled", true);
// Every server gets it's unique random id. // Every server gets it's unique random id.
@ -117,13 +110,14 @@ public class Metrics {
// Inform the server owners about bStats // Inform the server owners about bStats
config.options() config.options()
.header( .header(
"bStats collects some data for plugin authors like how many servers are" "bStats collects some data for plugin authors like how "
+ " using their plugins.\n" + "many servers are"
+ "To honor their work, you should not disable it.\n" + " using their plugins.\n"
+ "This has nearly no effect on the server performance!\n" + "To honor their work, you should not disable it.\n"
+ "Check out https://bStats.org/ to learn more :)") + "This has nearly no effect on the server performance!\n"
.copyDefaults(true); + "Check out https://bStats.org/ to learn more :)")
.copyDefaults(true);
try { try {
config.save(configFile); config.save(configFile);
} catch (IOException ignored) { } catch (IOException ignored) {
@ -135,12 +129,15 @@ public class Metrics {
serverUUID = config.getString("serverUuid"); serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false); logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false); logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false); logResponseStatusText =
config.getBoolean("logResponseStatusText", false);
if (enabled) { if (enabled) {
boolean found = false; boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one // Search for all other bStats Metrics classes to see if we are the
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { // first one
for (Class<?> service :
Bukkit.getServicesManager().getKnownServices()) {
try { try {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first found = true; // We aren't the first
@ -149,8 +146,8 @@ public class Metrics {
} }
} }
// Register our service // Register our service
Bukkit.getServicesManager() Bukkit.getServicesManager().register(Metrics.class, this, plugin,
.register(Metrics.class, this, plugin, ServicePriority.Normal); ServicePriority.Normal);
if (!found) { if (!found) {
// We are the first! // We are the first!
startSubmitting(); startSubmitting();
@ -179,33 +176,31 @@ public class Metrics {
charts.add(chart); charts.add(chart);
} }
/** Starts the Scheduler which submits our data every 30 minutes. */ /**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() { private void startSubmitting() {
final Timer timer = final Timer timer =
new Timer( new Timer(true); // We use a timer cause the Bukkit
true); // We use a timer cause the Bukkit scheduler is affected by server // scheduler is affected by server lags
// lags timer.scheduleAtFixedRate(new TimerTask() {
timer.scheduleAtFixedRate( @Override
new TimerTask() { public void run() {
@Override if (!plugin.isEnabled()) { // Plugin was disabled
public void run() { timer.cancel();
if (!plugin.isEnabled()) { // Plugin was disabled return;
timer.cancel(); }
return; // Nevertheless we want our code to run in the Bukkit main
} // thread, so we have to use the Bukkit scheduler Don't be
// Nevertheless we want our code to run in the Bukkit main thread, so we // afraid! The connection to the bStats server is still async,
// have to use the Bukkit scheduler // only the stats collection is sync ;)
// Don't be afraid! The connection to the bStats server is still async, only Bukkit.getScheduler().runTask(plugin, () -> submitData());
// the stats collection is sync ;) }
Bukkit.getScheduler().runTask(plugin, () -> submitData()); }, 1000 * 60 * 5, 1000 * 60 * 30);
} // Submit the data every 30 minutes, first time after 5 minutes to give
}, // other plugins enough time to start WARNING: Changing the frequency
1000 * 60 * 5, // has no effect but your plugin WILL be blocked/deleted! WARNING: Just
1000 * 60 * 30); // don't do it!
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough
// time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
} }
/** /**
@ -219,8 +214,10 @@ public class Metrics {
String pluginName = plugin.getDescription().getName(); String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion(); String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin data.addProperty("pluginName",
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin pluginName); // Append the name of the plugin
data.addProperty("pluginVersion",
pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray(); JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) { for (CustomChart customChart : charts) {
// Add the data of the custom charts // Add the data of the custom charts
@ -244,20 +241,22 @@ public class Metrics {
// Minecraft specific data // Minecraft specific data
int playerAmount; int playerAmount;
try { try {
// Around MC 1.8 the return type was changed to a collection from an array, // Around MC 1.8 the return type was changed to a collection from an
// This fixes java.lang.NoSuchMethodError: // array, This fixes java.lang.NoSuchMethodError:
// org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Method onlinePlayersMethod = Class.forName("org.bukkit.Server")
Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); .getMethod("getOnlinePlayers");
playerAmount = playerAmount =
onlinePlayersMethod.getReturnType().equals(Collection.class) onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())) ? ((Collection<?>) onlinePlayersMethod.invoke(
.size() Bukkit.getServer()))
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; .size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer()))
.length;
} catch (Exception e) { } catch (Exception e) {
playerAmount = playerAmount =
Bukkit.getOnlinePlayers() Bukkit.getOnlinePlayers()
.size(); // Just use the new method if the Reflection failed .size(); // Just use the new method if the Reflection failed
} }
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion(); String bukkitVersion = Bukkit.getVersion();
@ -288,55 +287,59 @@ public class Metrics {
return data; return data;
} }
/** Collects the data and sends it afterwards. */ /**
* Collects the data and sends it afterwards.
*/
private void submitData() { private void submitData() {
final JsonObject data = getServerData(); final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray(); JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data // Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { for (Class<?> service :
Bukkit.getServicesManager().getKnownServices()) {
try { try {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : for (RegisteredServiceProvider<?> provider :
Bukkit.getServicesManager().getRegistrations(service)) { Bukkit.getServicesManager().getRegistrations(service)) {
try { try {
Object plugin = Object plugin = provider.getService()
provider.getService() .getMethod("getPluginData")
.getMethod("getPluginData") .invoke(provider.getProvider());
.invoke(provider.getProvider());
if (plugin instanceof JsonObject) { if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin); pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility } else { // old bstats version compatibility
try { try {
Class<?> jsonObjectJsonSimple = Class<?> jsonObjectJsonSimple =
Class.forName("org.json.simple.JSONObject"); Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { if (plugin.getClass().isAssignableFrom(
jsonObjectJsonSimple)) {
Method jsonStringGetter = Method jsonStringGetter =
jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); jsonObjectJsonSimple.getDeclaredMethod(
"toJSONString");
jsonStringGetter.setAccessible(true); jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin); String jsonString =
JsonObject object = (String) jsonStringGetter.invoke(
new JsonParser().parse(jsonString).getAsJsonObject(); plugin);
JsonObject object = new JsonParser()
.parse(jsonString)
.getAsJsonObject();
pluginData.add(object); pluginData.add(object);
} }
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
// minecraft version 1.14+ // minecraft version 1.14+
if (logFailedRequests) { if (logFailedRequests) {
this.plugin this.plugin.getLogger().log(
.getLogger() Level.SEVERE,
.log( "Encountered unexpected exception", e);
Level.SEVERE,
"Encountered unexpected exception",
e);
} }
continue; // continue looping since we cannot do any other thing. continue; // continue looping since we cannot do
// any other thing.
} }
} }
} catch (NullPointerException } catch (NullPointerException | NoSuchMethodException
| NoSuchMethodException | IllegalAccessException
| IllegalAccessException | InvocationTargetException ignored) {
| InvocationTargetException ignored) {
} }
} }
} catch (NoSuchFieldException ignored) { } catch (NoSuchFieldException ignored) {
@ -346,27 +349,24 @@ public class Metrics {
data.add("plugins", pluginData); data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server // Create a new thread for the connection to the bStats server
new Thread( new Thread(new Runnable() {
new Runnable() { @Override
@Override public void run() {
public void run() { try {
try { // Send the data
// Send the data sendData(plugin, data);
sendData(plugin, data); } catch (Exception e) {
} catch (Exception e) { // Something went wrong! :(
// Something went wrong! :( if (logFailedRequests) {
if (logFailedRequests) { plugin.getLogger().log(
plugin.getLogger() Level.WARNING,
.log( "Could not submit plugin stats of "
Level.WARNING, + plugin.getName(),
"Could not submit plugin stats of " e);
+ plugin.getName(), }
e); }
} }
} }).start();
}
})
.start();
} }
/** /**
@ -376,18 +376,21 @@ public class Metrics {
* @param data The data to send. * @param data The data to send.
* @throws Exception If the request failed. * @throws Exception If the request failed.
*/ */
private static void sendData(Plugin plugin, JsonObject data) throws Exception { private static void sendData(Plugin plugin, JsonObject data)
throws Exception {
if (data == null) { if (data == null) {
throw new IllegalArgumentException("Data cannot be null!"); throw new IllegalArgumentException("Data cannot be null!");
} }
if (Bukkit.isPrimaryThread()) { if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException( throw new IllegalAccessException(
"This method must not be called from the main thread!"); "This method must not be called from the main thread!");
} }
if (logSentData) { if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString()); plugin.getLogger().info("Sending data to bStats: "
+ data.toString());
} }
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); HttpsURLConnection connection =
(HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth // Compress the data to save bandwidth
byte[] compressedData = compress(data.toString()); byte[] compressedData = compress(data.toString());
@ -396,21 +399,27 @@ public class Metrics {
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Encoding",
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length",
String.valueOf(compressedData.length));
connection.setRequestProperty( connection.setRequestProperty(
"Content-Type", "application/json"); // We send our data in JSON format "Content-Type",
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent",
"MC-Server/" + B_STATS_VERSION);
// Send data // Send data
connection.setDoOutput(true); connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); DataOutputStream outputStream =
new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData); outputStream.write(compressedData);
outputStream.flush(); outputStream.flush();
outputStream.close(); outputStream.close();
InputStream inputStream = connection.getInputStream(); InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
String line; String line;
@ -419,8 +428,9 @@ public class Metrics {
} }
bufferedReader.close(); bufferedReader.close();
if (logResponseStatusText) { if (logResponseStatusText) {
plugin.getLogger() plugin.getLogger().info(
.info("Sent data to bStats and received response: " + builder.toString()); "Sent data to bStats and received response: "
+ builder.toString());
} }
} }
@ -442,9 +452,10 @@ public class Metrics {
return outputStream.toByteArray(); return outputStream.toByteArray();
} }
/** Represents a custom chart. */ /**
* Represents a custom chart.
*/
public abstract static class CustomChart { public abstract static class CustomChart {
// The id of the chart // The id of the chart
final String chartId; final String chartId;
@ -455,7 +466,8 @@ public class Metrics {
*/ */
CustomChart(String chartId) { CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) { if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!"); throw new IllegalArgumentException(
"ChartId cannot be null or empty!");
} }
this.chartId = chartId; this.chartId = chartId;
} }
@ -472,11 +484,11 @@ public class Metrics {
chart.add("data", data); chart.add("data", data);
} catch (Throwable t) { } catch (Throwable t) {
if (logFailedRequests) { if (logFailedRequests) {
Bukkit.getLogger() Bukkit.getLogger().log(
.log( Level.WARNING,
Level.WARNING, "Failed to get data for custom chart with id "
"Failed to get data for custom chart with id " + chartId, + chartId,
t); t);
} }
return null; return null;
} }
@ -486,9 +498,10 @@ public class Metrics {
protected abstract JsonObject getChartData() throws Exception; protected abstract JsonObject getChartData() throws Exception;
} }
/** Represents a custom simple pie. */ /**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart { public static class SimplePie extends CustomChart {
private final Callable<String> callable; private final Callable<String> callable;
/** /**
@ -515,9 +528,10 @@ public class Metrics {
} }
} }
/** Represents a custom advanced pie. */ /**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart { public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable; private final Callable<Map<String, Integer>> callable;
/** /**
@ -526,7 +540,8 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) { public AdvancedPie(String chartId,
Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@ -557,9 +572,10 @@ public class Metrics {
} }
} }
/** Represents a custom drilldown pie. */ /**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart { public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable; private final Callable<Map<String, Map<String, Integer>>> callable;
/** /**
@ -568,7 +584,9 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) { public DrilldownPie(
String chartId,
Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@ -583,12 +601,14 @@ public class Metrics {
return null; return null;
} }
boolean reallyAllSkipped = true; boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) { for (Map.Entry<String, Map<String, Integer>> entryValues :
map.entrySet()) {
JsonObject value = new JsonObject(); JsonObject value = new JsonObject();
boolean allSkipped = true; boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : for (Map.Entry<String, Integer> valueEntry :
map.get(entryValues.getKey()).entrySet()) { map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue()); value.addProperty(valueEntry.getKey(),
valueEntry.getValue());
allSkipped = false; allSkipped = false;
} }
if (!allSkipped) { if (!allSkipped) {
@ -605,9 +625,10 @@ public class Metrics {
} }
} }
/** Represents a custom single line chart. */ /**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart { public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable; private final Callable<Integer> callable;
/** /**
@ -634,9 +655,10 @@ public class Metrics {
} }
} }
/** Represents a custom multi line chart. */ /**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart { public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable; private final Callable<Map<String, Integer>> callable;
/** /**
@ -645,7 +667,8 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) { public MultiLineChart(String chartId,
Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@ -676,9 +699,10 @@ public class Metrics {
} }
} }
/** Represents a custom simple bar chart. */ /**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart { public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable; private final Callable<Map<String, Integer>> callable;
/** /**
@ -687,7 +711,8 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) { public SimpleBarChart(String chartId,
Callable<Map<String, Integer>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }
@ -711,9 +736,10 @@ public class Metrics {
} }
} }
/** Represents a custom advanced bar chart. */ /**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart { public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable; private final Callable<Map<String, int[]>> callable;
/** /**
@ -722,7 +748,8 @@ public class Metrics {
* @param chartId The id of the chart. * @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data. * @param callable The callable which is used to request the chart data.
*/ */
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) { public AdvancedBarChart(String chartId,
Callable<Map<String, int[]>> callable) {
super(chartId); super(chartId);
this.callable = callable; this.callable = callable;
} }

View File

@ -1,37 +1,39 @@
package com.sekwah.advancedportals.spigot.reflection; package com.sekwah.advancedportals.spigot.reflection;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import org.bukkit.entity.Player;
/** /**
* Just a util class to force spigot to allow us to have fun with the minecraft: channel category * Just a util class to force spigot to allow us to have fun with the
* minecraft: channel category
* *
* <p>Atm at least this is just designed to be able to access debug/ for showing visuals of the * <p>Atm at least this is just designed to be able to access debug/ for
* portals and such * showing visuals of the portals and such
*/ */
public class MinecraftCustomPayload { public class MinecraftCustomPayload {
public static boolean sendCustomPayload(Player player, String channel,
public static boolean sendCustomPayload(Player player, String channel, byte[] data) { byte[] data) {
try { try {
// Access the MinecraftKey class using reflection // Access the MinecraftKey class using reflection
Class<?> minecraftKeyClass = Class.forName("net.minecraft.resources.MinecraftKey"); Class<?> minecraftKeyClass =
Constructor<?> minecraftKeyConstructor = minecraftKeyClass.getConstructor(String.class); Class.forName("net.minecraft.resources.MinecraftKey");
Constructor<?> minecraftKeyConstructor =
minecraftKeyClass.getConstructor(String.class);
// Create an instance of MinecraftKey with the channel name // Create an instance of MinecraftKey with the channel name
Object minecraftKey = minecraftKeyConstructor.newInstance(channel); Object minecraftKey = minecraftKeyConstructor.newInstance(channel);
// Access the sendCustomPayload method in the CraftPlayer class // Access the sendCustomPayload method in the CraftPlayer class
Method sendCustomPayloadMethod = Method sendCustomPayloadMethod =
player.getClass() player.getClass().getDeclaredMethod(
.getDeclaredMethod( "sendCustomPayload", minecraftKeyClass, byte[].class);
"sendCustomPayload", minecraftKeyClass, byte[].class);
// Make the private method accessible // Make the private method accessible
sendCustomPayloadMethod.setAccessible(true); sendCustomPayloadMethod.setAccessible(true);
// Invoke the sendCustomPayload method with the MinecraftKey and data // Invoke the sendCustomPayload method with the MinecraftKey and
// data
sendCustomPayloadMethod.invoke(player, minecraftKey, data); sendCustomPayloadMethod.invoke(player, minecraftKey, data);
return true; // Successfully sent the custom payload return true; // Successfully sent the custom payload

View File

@ -2,23 +2,17 @@ package com.sekwah.advancedportals.spigot.utils;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation; import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation; import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import org.bukkit.Location; import org.bukkit.Location;
public class ContainerHelpers { public class ContainerHelpers {
public static PlayerLocation toPlayerLocation(Location loc) { public static PlayerLocation toPlayerLocation(Location loc) {
return new PlayerLocation( return new PlayerLocation(loc.getWorld().getName(), loc.getX(),
loc.getWorld().getName(), loc.getY(), loc.getZ(), loc.getYaw(),
loc.getX(), loc.getPitch());
loc.getY(),
loc.getZ(),
loc.getYaw(),
loc.getPitch());
} }
public static BlockLocation toBlockLocation(Location loc) { public static BlockLocation toBlockLocation(Location loc) {
return new BlockLocation( return new BlockLocation(loc.getWorld().getName(), loc.getBlockX(),
loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); loc.getBlockY(), loc.getBlockZ());
} }
} }

View File

@ -8,27 +8,31 @@ import com.sekwah.advancedportals.spigot.connector.container.SpigotPlayerContain
import org.bukkit.Effect; import org.bukkit.Effect;
public class EnderWarpEffect implements WarpEffect.Visual, WarpEffect.Sound { public class EnderWarpEffect implements WarpEffect.Visual, WarpEffect.Sound {
@Override @Override
public void onWarpSound(PlayerContainer playerContainer, WarpEffect.Action action) { public void onWarpSound(PlayerContainer playerContainer,
if(playerContainer instanceof SpigotPlayerContainer spigotPlayerContainer) { WarpEffect.Action action) {
if (playerContainer
instanceof SpigotPlayerContainer spigotPlayerContainer) {
var player = spigotPlayerContainer.getPlayer(); var player = spigotPlayerContainer.getPlayer();
player.getWorld().playSound(player.getLocation(), "entity.enderman.teleport", 1, 1); player.getWorld().playSound(player.getLocation(),
"entity.enderman.teleport", 1, 1);
} }
} }
@Override @Override
public void onWarpVisual(PlayerContainer playerContainer, WarpEffect.Action action) { public void onWarpVisual(PlayerContainer playerContainer,
if(playerContainer instanceof SpigotPlayerContainer spigotPlayerContainer) { WarpEffect.Action action) {
if (playerContainer
instanceof SpigotPlayerContainer spigotPlayerContainer) {
var player = spigotPlayerContainer.getPlayer(); var player = spigotPlayerContainer.getPlayer();
var world = player.getWorld(); var world = player.getWorld();
var loc = player.getLocation().clone(); var loc = player.getLocation().clone();
for(int i = 0; i < 10; i++){ for (int i = 0; i < 10; i++) {
world.playEffect(loc, Effect.ENDER_SIGNAL, 0); world.playEffect(loc, Effect.ENDER_SIGNAL, 0);
} }
loc.add(0D, 1D, 0D); loc.add(0D, 1D, 0D);
for(int i = 0; i < 10; i++){ for (int i = 0; i < 10; i++) {
world.playEffect(loc, Effect.ENDER_SIGNAL, 0); world.playEffect(loc, Effect.ENDER_SIGNAL, 0);
} }
} }

View File

@ -1,11 +1,9 @@
package com.sekwah.advancedportals.spigot.warpeffects; package com.sekwah.advancedportals.spigot.warpeffects;
import com.sekwah.advancedportals.core.registry.WarpEffectRegistry; import com.sekwah.advancedportals.core.registry.WarpEffectRegistry;
import javax.inject.Inject; import javax.inject.Inject;
public class SpigotWarpEffects { public class SpigotWarpEffects {
@Inject private WarpEffectRegistry warpEffectRegistry; @Inject private WarpEffectRegistry warpEffectRegistry;
public void registerEffects() { public void registerEffects() {