Rewrote to have no references to any of the platforms

This commit is contained in:
Alastair 2018-01-03 23:16:11 +00:00
parent a4b1e101d4
commit 0b69728639
49 changed files with 837 additions and 4085 deletions

View File

@ -1,92 +0,0 @@
# Advanced Portals Config
# To set this file back to its default state just delete it and reload the server or restart it!
# Set to true if you want the normal axes to work normally but the ones gived with /portals selector or wand will still work though
# It can be usefull if people with permission want to use an iron axe on a survival server
UseOnlyServerMadeAxe: false
# Preferably an item and not a block but it shouldnt matter
AxeItemId: IRON_AXE
# Will be implemented so you can give yourself the portal block and build manually with it so its easier to make portals with the portal block.
CanBuildPortalBlock: true
# Defines if portals protect themselves
PortalProtection: true
# How many blocks around the portals will be protected from griefing or destruction
PortalProtectionRadius: 5
# What the default trigger block is for portals if nothing is defined.
DefaultPortalTriggerBlock: PORTAL
# This stops all water flowing inside a portal area(can be disabled if something like world edit is handelling the water flow or you dont want it active)
# you want to
StopWaterFlow: true
# This must be a placeable block or it will not work and may even crash
ShowSelectionBlockID: STAINED_GLASS
ShowSelectionBlockData: 14
# WarpEffect
# 0 = disabled(no particles)
# 1 = Eye of ender explode effect(loads of portal particles)
# adding more soon and may create some custom ones
WarpParticles: 1
# WarpSound generally suggested to keep the same as warpeffect but can usually be used for just the sound and no particle effects
# 0 = disabled(no sound)
# 1 = Enderman Warp Sound
# adding more soon
WarpSound: 1
# In case you want to show the bungee attempting warp message
ShowBungeeWarpMessage: false
# This changes how long the show seletion lasts in seconds
ShowSelectionShowDuration: 10
# If a player is riding a entity, warp the entity too?(unless its a bungee portal or any non teleporting portal)
WarpRiddenEntity: true
# Where to display the message 0 = disabled(replaces PortalWarpMessages), 1 = in chat and 2 = action bar(1.8 and above only, anything lower will print the message that would
# generally on the action bar in the chat without a prefix or extra chat formatting)
WarpMessageDisplay: 2
# Use plugin name in the warp messages
UseWarpPrefix: true
# If this is true a custom prefix can be used, (not fully coded yet!!)
UseCustomPrefix: false
CustomPrefix: '&a[&eAdvancedPortals&a]'
CustomPrefixFail: '&c[&7AdvancedPortals&c]'
BlockSpectatorMode: false
PortalCooldown: 5 # How long after trying to enter a portal until the player can try to enter another. 0 or lower to deactivate.
ThrowbackAmount: 0.7 # How fast to throw them back, 0 or lower to disable throwback
# Letters are flags. Include them to activate. n always disables everything, remove if you want it to work.
# Lettering may not make too much sense but meh its useful. Examples are "ocpk" or "cop" (doesnt matter order)
#
# Remember enabling this means potentially admins could leave a portal lying around which could let them reop themselves.
# If you think this may be an issue use a permission plugin and specifically give the users you trust permissions.
#
# n Disabled none, best just put this to really make sure the fact none are here is specified. It disables any others too
# o Admin Heighten Enabled Permission advancedportals.createportal.commandlevel.op
# p Perm Heighten Enabled Permission advancedportals.createportal.commandlevel.perms
# c Console Heighten Enabled Permission advancedportals.createportal.commandlevel.console
# h Ops can create admin commands without special perms
# e Ops can create all perm commands without special perms
# k Ops can create console commands without special perms
#
CommandLevels: opchek

View File

@ -1,7 +0,0 @@
# ExampleDestination:
# world: it will be the world name
# pos:
# X:
# Y:
# Z:

View File

@ -1,54 +0,0 @@
main: com.sekwah.advancedportals.AdvancedPortalsPlugin
name: AdvancedPortals
version: 0.0.37
author: sekwah41
description: An advanced portals plugin for bukkit.
commands:
advancedportals:
description: The main command for the advanced portals
aliases: [portals, aportals, portal, ap]
usage: /<command>
destination:
description: Can be used to access portal destinations.
aliases: [desti]
usage: /<command>
permissions:
advancedportals.*:
description: Gives access to all commands
default: op
children:
advancedportals.createportal: true
advancedportals.portal: true
advancedportals.build: true
advancedportals.desti: true
advancedportals.createportal:
description: Allows you to create portals
default: op
advancedportals.createportal.commandlevel.*:
description: Gives access to all level raisers
default: false
children:
advancedportals.createportal.commandlevel.op: true
advancedportals.createportal.commandlevel.perms: true
advancedportals.createportal.commandlevel.console: true
advancedportals.createportal.commandlevel.op:
description: Allows you to increase the users level temporaily to op
default: false
advancedportals.createportal.commandlevel.perms:
description: Allows you to increase the users level temporaily to have all perms
default: false
advancedportals.createportal.commandlevel.console:
description: Executes command in the console
default: false
advancedportals.portal:
description: Allows use of portal commands
default: op
advancedportals.build:
description: Allows you to build in the portal regions
default: op
advancedportals.desti:
description: Gives access to all desti commands
default: op
advancedportals.warp.*:
description: Access to all warps (not really used tbh)
default: true

View File

@ -1,19 +0,0 @@
# ExamplePortal:
# world: it will be the world name
# triggerblock: LAVA # will only be used if the hastriggerblock is true and can be id or text
# pos1: # dont mess with the data here, if you do it may stop the portal from working.
# X:
# Y:
# Z:
# pos2:
# X:
# Y:
# Z:
# destination:
# issetpoint: true # if this was false point name would not be used and the coordinates would be saved here, it just adds more customisation.
# pointname: examplepoint # if issetpoint is false this wont be here and tppos will be.
# tppos:
# X:
# Y:
# Z:

20
pom.xml
View File

@ -3,7 +3,7 @@
<groupId>com.sekwah.advancedportals</groupId>
<artifactId>Advanced-Portals</artifactId>
<build>
<sourceDirectory>${basedir}/src/</sourceDirectory>
<sourceDirectory>${basedir}/core/</sourceDirectory>
<resources>
<resource>
<directory>${basedir}/Resources</directory>
@ -11,27 +11,29 @@
</resources>
</build>
<repositories>
<repository>
<!-- Only needed for spigot -->
<!--<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repository>-->
</repositories>
<version>0.0.37-snapshot</version>
<version>1.0.0-snapshot</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- spigot's buildtools automatically places it in maven's repository after building it -->
<!-- Craftbukkit contains the bukkit code. But as the majority uses it uses bukkit
it stops the need to build to edit at least -->
<dependency>
<!-- Only needed for spigot -->
<!--<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.12.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependency>-->
<!-- spigot's buildtools automatically places it in maven's repository after building it -->
<!-- Craftbukkit contains the bukkit code. But as the majority uses it uses bukkit
it stops the need to build to edit at least -->
<!--<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>

View File

@ -1,722 +0,0 @@
package com.sekwah.advancedportals;
import com.sekwah.advancedportals.api.portaldata.PortalArg;
import com.sekwah.advancedportals.listeners.Listeners;
import com.sekwah.advancedportals.portals.AdvancedPortal;
import com.sekwah.advancedportals.portals.Portal;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.Wool;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.*;
public class AdvancedPortalsCommand implements CommandExecutor, TabCompleter {
private final ArrayList<String> blockMaterialList = new ArrayList<>();
private AdvancedPortalsPlugin plugin;
private int portalArgsStringLength = 0;
// TODO recode the portal args to be put into a hashmap and use a string array
// to store all possible portal arguments. Makes code shorter and possibly more efficient.
//private HashMap<String, String> portalArgs = new HashMap<>();
public AdvancedPortalsCommand(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
for(Material material : Material.values()) {
this.blockMaterialList.add("triggerblock:" + material.name());
}
plugin.getCommand("advancedportals").setExecutor(this);
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command cmd, String command, String[] args) {
System.out.printf("%s %s %s %s%n", sender, cmd, command, args );
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
ConfigAccessor portalConfig = new ConfigAccessor(plugin, "portals.yml");
if(!(sender instanceof Player)) {
sender.sendMessage(PluginMessages.customPrefixFail + " You cannot use commands with the console.");
return true;
}
Player player = (Player) sender;
PlayerInventory inventory = player.getInventory();
if (sender.hasPermission("advancedportals.portal")) {
if (args.length > 0) { switch (args[0].toLowerCase()) {
case "wand":
case "selector":
String ItemID = config.getConfig().getString("AxeItemId");
Material WandMaterial = Material.getMaterial(ItemID);
if (WandMaterial == null) {
WandMaterial = Material.IRON_AXE;
}
ItemStack regionselector = new ItemStack(WandMaterial);
ItemMeta selectorname = regionselector.getItemMeta();
selectorname.setDisplayName("\u00A7ePortal Region Selector");
selectorname.setLore(Arrays.asList("\u00A7rThis wand with has the power to help"
, "\u00A7r create portals bistowed upon it!"));
regionselector.setItemMeta(selectorname);
inventory.addItem(regionselector);
sender.sendMessage(PluginMessages.customPrefix + " You have been given a \u00A7ePortal Region Selector\u00A7a!");
break;
case "portalblock":
// TODO change this to a purple wool block and give it a name with a color. Then listen to when its placed.
// Also do this for other blocks such as gateways and end portals just in case they want it.
ItemStack portalBlock = new Wool(DyeColor.PURPLE).toItemStack(1);
ItemMeta blockName = portalBlock.getItemMeta();
blockName.setDisplayName("\u00A75Portal Block Placer");
blockName.setLore(Arrays.asList("\u00A7rThis wool is made of a magical substance",
"\u00A7rRight Click: Place portal block",
"\u00A7rLeft Click: Rotate portal block"));
portalBlock.setItemMeta(blockName);
inventory.addItem(portalBlock);
sender.sendMessage(PluginMessages.customPrefix + " You have been given a \u00A7ePortal Block\u00A7a!");
break;
case "endportalblock":
// TODO change this to a purple wool block and give it a name with a color. Then listen to when its placed.
// Also do this for other blocks such as gateways and end portals just in case they want it.
portalBlock = new Wool(DyeColor.BLACK).toItemStack(1);
blockName = portalBlock.getItemMeta();
blockName.setDisplayName("\u00A78End Portal Block Placer");
blockName.setLore(Arrays.asList("\u00A7rThis wool is made of a magical substance",
"\u00A7rRight Click: Place portal block"));
portalBlock.setItemMeta(blockName);
inventory.addItem(portalBlock);
sender.sendMessage(PluginMessages.customPrefix + " You have been given a \u00A7ePortal Block\u00A7a!");
break;
case "gatewayblock":
// TODO change this to a purple wool block and give it a name with a color. Then listen to when its placed.
// Also do this for other blocks such as gateways and end portals just in case they want it.
portalBlock = new Wool(DyeColor.BLACK).toItemStack(1);
blockName = portalBlock.getItemMeta();
blockName.setDisplayName("\u00A78Gateway Block Placer");
blockName.setLore(Arrays.asList("\u00A7rThis wool is made of a magical substance",
"\u00A7rRight Click: Place portal block"));
portalBlock.setItemMeta(blockName);
inventory.addItem(portalBlock);
sender.sendMessage(PluginMessages.customPrefix + " You have been given a \u00A7ePortal Block\u00A7a!");
break;
case "create":
if (player.hasMetadata("Pos1World") && player.hasMetadata("Pos2World")) {
if (player.getMetadata("Pos1World").get(0).asString().equals(player.getMetadata("Pos2World").get(0).asString())
&& player.getMetadata("Pos1World").get(0).asString().equals(player.getLocation().getWorld().getName())) {
if (args.length >= 2) { // may make this next piece of code more efficient, maybe check against a list of available variables or something
// TODO change system to use arrays and hashmaps
boolean hasName = false;
boolean hasTriggerBlock = false;
boolean hasDestination = false;
boolean isBungeePortal = false;
boolean needsPermission = false;
boolean executesCommand = false;
String destination = null;
String portalName = null;
String triggerBlock = null;
String serverName = null;
String permission = null;
String portalCommand = null;
ArrayList<PortalArg> extraData = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
if (args[i].toLowerCase().startsWith("name:") && args[i].length() > 5) {
hasName = true;
portalName = args[i].replaceFirst("name:", "");
} else if (args[i].toLowerCase().startsWith("name:")) {
player.sendMessage(PluginMessages.customPrefixFail + " You must include a name for the portal that isnt nothing!");
return true;
} else if (args[i].toLowerCase().startsWith("destination:") && args[i].length() > 12) {
hasDestination = true;
destination = args[i].toLowerCase().replaceFirst("destination:", "");
} else if (args[i].toLowerCase().startsWith("desti:") && args[i].length() > 6) {
hasDestination = true;
destination = args[i].toLowerCase().replaceFirst("desti:", "");
} else if (args[i].toLowerCase().startsWith("triggerblock:") && args[i].length() > 13) {
hasTriggerBlock = true;
triggerBlock = args[i].toLowerCase().replaceFirst("triggerblock:", "");
} else if (args[i].toLowerCase().startsWith("triggerblock:") && args[i].length() > 13) {
hasTriggerBlock = true;
triggerBlock = args[i].toLowerCase().replaceFirst("triggerblock:", "");
} else if (args[i].toLowerCase().startsWith("bungee:") && args[i].length() > 7) { // not completely implemented
isBungeePortal = true;
serverName = args[i].toLowerCase().replaceFirst("bungee:", "");
//extraData.add(new PortalArgs("bungee", serverName));
} else if (args[i].toLowerCase().startsWith("permission:") && args[i].length() > 11) { // not completely implemented
needsPermission = true;
permission = args[i].toLowerCase().replaceFirst("permission:", "");
extraData.add(new PortalArg("permission", permission));
} else if (args[i].toLowerCase().startsWith("command:") && args[i].length() > 8) { // not completely implemented
executesCommand = true;
portalCommand = parseArgVariable(args, i, "command:");
i += this.portalArgsStringLength - 1;
if(portalCommand.startsWith("#") && !(this.plugin.getSettings().hasCommandLevel("c")
&& (sender.hasPermission("advancedportals.createportal.commandlevel.console"))
|| (this.plugin.getSettings().hasCommandLevel("k") && sender.isOp()))) {
player.sendMessage(PluginMessages.customPrefixFail + " You need permission to make a console command portal!");
return true;
}
else if(portalCommand.startsWith("!") && !(this.plugin.getSettings().hasCommandLevel("o")
&& (sender.hasPermission("advancedportals.createportal.commandlevel.op"))
|| (this.plugin.getSettings().hasCommandLevel("p") && sender.isOp()))) {
player.sendMessage(PluginMessages.customPrefixFail + " You need permission to make a op command portal!");
return true;
}
else if(portalCommand.startsWith("^") && !(this.plugin.getSettings().hasCommandLevel("p")
&& (sender.hasPermission("advancedportals.createportal.commandlevel.perms"))
|| (this.plugin.getSettings().hasCommandLevel("e") && sender.isOp()))) {
player.sendMessage(PluginMessages.customPrefixFail + " You need permission to make a all perms command portal!");
return true;
}
extraData.add(new PortalArg("command.1", portalCommand));
}
}
if (!hasName) {
player.sendMessage(PluginMessages.customPrefixFail + " You must include a name for the portal that you are creating in the variables!");
return true;
}
World world = org.bukkit.Bukkit.getWorld(player.getMetadata("Pos1World").get(0).asString());
Location pos1 = new Location(world, player.getMetadata("Pos1X").get(0).asInt(), player.getMetadata("Pos1Y").get(0).asInt(), player.getMetadata("Pos1Z").get(0).asInt());
Location pos2 = new Location(world, player.getMetadata("Pos2X").get(0).asInt(), player.getMetadata("Pos2Y").get(0).asInt(), player.getMetadata("Pos2Z").get(0).asInt());
ConfigAccessor desticonfig = new ConfigAccessor(plugin, "destinations.yml");
String destiPosX = desticonfig.getConfig().getString(destination + ".pos.X");
if (!Portal.portalExists(portalName)) {
player.sendMessage("");
player.sendMessage(PluginMessages.customPrefix + "\u00A7e You have created a new portal with the following details:");
player.sendMessage("\u00A7aname: \u00A7e" + portalName);
if (hasDestination) {
if (destiPosX == null) {
player.sendMessage("\u00A7cdestination: \u00A7e" + destination + " (destination does not exist)");
return true;
}
else{
player.sendMessage("\u00A7adestination: \u00A7e" + destination);
}
} else {
player.sendMessage("\u00A7cdestination: \u00A7eN/A (will not teleport to a location)");
}
if (isBungeePortal) {
player.sendMessage("\u00A7abungee: \u00A7e" + serverName);
}
if (needsPermission) {
player.sendMessage("\u00A7apermission: \u00A7e" + permission);
} else {
player.sendMessage("\u00A7apermission: \u00A7e(none needed)");
}
if (executesCommand) {
player.sendMessage("\u00A7acommand: \u00A7e" + portalCommand);
}
Material triggerBlockMat;
if (hasTriggerBlock) {
triggerBlockMat = Material.getMaterial(triggerBlock.toUpperCase());
if (triggerBlockMat != null) {
player.sendMessage("\u00A7atriggerBlock: \u00A7e" + triggerBlock.toUpperCase());
PortalArg[] portalArgs = new PortalArg[extraData.size()];
portalArgs = extraData.toArray(portalArgs);
player.sendMessage(Portal.create(pos1, pos2, portalName, destination, triggerBlockMat, serverName, portalArgs));
} else {
hasTriggerBlock = false;
ConfigAccessor Config = new ConfigAccessor(plugin, "config.yml");
player.sendMessage("\u00A7ctriggerBlock: \u00A7edefault(" + Config.getConfig().getString("DefaultPortalTriggerBlock") + ")");
player.sendMessage("\u00A7cThe block " + triggerBlock.toUpperCase() + " is not a valid block name in minecraft so the trigger block has been set to the default!");
PortalArg[] portalArgs = new PortalArg[extraData.size()];
portalArgs = extraData.toArray(portalArgs);
player.sendMessage(Portal.create(pos1, pos2, portalName, destination, serverName, portalArgs));
}
} else {
ConfigAccessor Config = new ConfigAccessor(plugin, "config.yml");
player.sendMessage("\u00A7atriggerBlock: \u00A7edefault(" + Config.getConfig().getString("DefaultPortalTriggerBlock") + ")");
PortalArg[] portalArgs = new PortalArg[extraData.size()];
portalArgs = extraData.toArray(portalArgs);
player.sendMessage(Portal.create(pos1, pos2, portalName, destination, serverName, portalArgs));
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " A portal by that name already exists!");
}
// add code to save the portal to the portal config and reload the portals
player.sendMessage("");
} else {
player.sendMessage(PluginMessages.customPrefixFail + " You need to at least add the name of the portal as a variable, \u00A7cType \u00A7e/portal variables\u00A7c"
+ " for a full list of currently available variables and an example command!");
}
} else {
player.sendMessage(PluginMessages.customPrefixFail + " The points you have selected need to be in the same world!");
}
} else {
player.sendMessage(PluginMessages.customPrefixFail + " You need to have two points selected to make a portal!");
}
break;
case "variables" :
sender.sendMessage(PluginMessages.customPrefix + " \u00A77Variables \u00A7c: \u00A7aname, triggerBlock, desti, destination, bungee, permission, command");
sender.sendMessage("");
sender.sendMessage("\u00A7aExample command: \u00A7e/portal create name:test triggerId:portal");
break;
case "select":
// TODO finish the select command and the hit block to replace!
if (!player.hasMetadata("selectingPortal")) {
if (args.length > 1) {
if (Portal.portalExists(args[1])) {
player.setMetadata("selectedPortal", new FixedMetadataValue(plugin, args[1]));
player.sendMessage(PluginMessages.customPrefix + " You have selected\u00A7e" + args[1] + "\u00A7a.");
} else {
player.sendMessage(PluginMessages.customPrefixFail + " No portal by the name \u00A7e" + args[1] + "\u00A7c exists (maybe you got the caps wrong)\n Try typing \u00A7e/portal select\u00A7c and hit inside the apropriate portals area!");
}
} else {
player.sendMessage(PluginMessages.customPrefix + " Hit a block inside the portal region to select the portal!");
player.setMetadata("selectingPortal", new FixedMetadataValue(plugin, true));
}
} else {
player.removeMetadata("selectingPortal", plugin);
player.sendMessage(PluginMessages.customPrefixFail + " Portal selection cancelled!");
}
break;
case "unselect":
if(player.hasMetadata("selectedPortal")){
player.sendMessage(PluginMessages.customPrefix + " You have unselected\u00A7e" + player.getMetadata("selectedPortal").get(0).asString()
+ "\u00A7a.");
}
else{
player.sendMessage(PluginMessages.customPrefixFail + " You had no portal selected!");
}
case "gui" :
if (args.length > 1) {
if (args[1].toLowerCase().equals("remove") && args.length > 2) {
sender.sendMessage("");
sender.sendMessage(PluginMessages.customPrefixFail + " Are you sure you would like to remove the portal \u00A7e" + args[2] + "\u00A7c?");
sender.sendMessage("");
plugin.compat.sendRawMessage("{\"text\":\" \",\"extra\":[{\"text\":\"\u00A7e[Yes]\",\"hoverEvent\":{\"action\":\"show_text\"," +
"\"value\":\"Confirm removing this portal\"},\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/portal remove " + args[2] + "\"}}, " +
"{\"text\":\" \"},{\"text\":\"\u00A7e[No]\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Cancel removing this portal\"}" +
",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/portal edit " + args[2] + "\"}}]}", player);
sender.sendMessage("");
}
}
break;
case "edit":
if (args.length > 1) {
if (Portal.portalExists(args[1])) {
player.setMetadata("selectedPortal", new FixedMetadataValue(plugin, args[1]));
portalEditMenu(sender, portalConfig, args[1]);
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No portal by the name \u00A7e" + args[1] + "\u00A7c exists!");
}
} else {
if (player.hasMetadata("selectedPortal")) {
String portalName = player.getMetadata("selectedPortal").get(0).asString();
String posX = portalConfig.getConfig().getString(portalName + ".pos1.X");
if (posX != null) {
portalEditMenu(sender, portalConfig, portalName);
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " The portal you had selected no longer seems to exist!");
player.removeMetadata("selectedPortal", plugin);
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No portal has been defined or selected!");
}
}
break;
case "rename":
// not finished yet /
if (args.length > 1) {
if (player.hasMetadata("selectedPortal")) {
String portalName = player.getMetadata("selectedPortal").get(0).asString();
if (portalName.toLowerCase() != args[1].toLowerCase()) {
String posX = portalConfig.getConfig().getString(portalName + ".pos1.X");
String newPortalPosX = portalConfig.getConfig().getString(args[1] + ".pos1.X");
if (posX != null && newPortalPosX == null) {
Portal.rename(portalName, args[1]);
sender.sendMessage(PluginMessages.customPrefix + " The portal \u00A7e" + portalName + "\u00A7a has been renamed to \u00A7e" + args[1] + "\u00A7a.");
player.setMetadata("selectedPortal", new FixedMetadataValue(plugin, args[1]));
} else if (newPortalPosX != null) {
sender.sendMessage(PluginMessages.customPrefixFail + " There is already a portal with the name \u00A7e" + args[1] + "\u00A7c!");
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " The portal you had selected no longer seems to exist!");
player.removeMetadata("selectedPortal", plugin);
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " The portal you have selected is already called that!");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No portal has been defined or selected!");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You must select a portal first and then type \u00A7e/portal rename (new name)\u00A7c!");
}
break;
case "command":
if (player.hasMetadata("selectedPortal")) {
String portalName = player.getMetadata("selectedPortal").get(0).asString();
if (args.length > 1) {
// TODO add the command autocompletes, add, remove and show
if (args[1].toLowerCase().equals("add")) {
if (args.length > 2) {
String portalCommand = args[2];
for (int i = 3; i < args.length; i++) {
portalCommand += args[i];
}
if (Portal.addCommand(portalName, portalCommand)) {
sender.sendMessage(PluginMessages.customPrefixFail + " Command added to portal!");
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " Failed to add command to portal!");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You must actually specify a command to execute!");
}
} else if (args[1].toLowerCase().equals("remove")) {
// Specify what line to remove
} else if (args[1].toLowerCase().equals("show")) {
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You must specify to \u00A7eadd\u00A7c or \u00A7eremove a command!");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You must specify to \u00A7eadd\u00A7c or \u00A7eremove\u00A7c a command!");
}
} else {
}
break;
case "remove":
if (args.length > 1) {
String posX = portalConfig.getConfig().getString(args[1] + ".pos1.X");
if (posX != null) {
Portal.remove(args[1]);
sender.sendMessage(PluginMessages.customPrefixFail + " The portal \u00A7e" + args[1] + "\u00A7c has been removed!");
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No portal by that name exists!");
}
} else {
if (player.hasMetadata("selectedPortal")) {
String portalName = player.getMetadata("selectedPortal").get(0).asString();
String posX = portalConfig.getConfig().getString(portalName + ".pos1.X");
if (posX != null) {
Portal.remove(portalName);
sender.sendMessage(PluginMessages.customPrefixFail + " The portal \u00A77" + portalName + "\u00A7c has been removed!");
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " The portal you had selected no longer seems to exist!");
player.removeMetadata("selectedPortal", plugin);
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No portal has been defined or selected!");
}
}
break;
case "help":
helpCommand(sender, command, args);
break;
case "show":
if (args.length > 1) {
String posX = portalConfig.getConfig().getString(args[1] + ".pos1.X");
if (posX != null) {
Selection.show(player, this.plugin, args[1]);
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No portal by that name exists!");
}
} else {
if (player.hasMetadata("selectedPortal")) {
player.sendMessage(PluginMessages.customPrefix + " Your currently selected portal has been shown, it will dissapear shortly!");
Selection.show(player, this.plugin, player.getMetadata("selectedPortal").get(0).asString());
} else if (player.hasMetadata("Pos1World") && player.hasMetadata("Pos2World")) {
if (player.getMetadata("Pos1World").get(0).asString().equals(player.getMetadata("Pos2World").get(0).asString())
&& player.getMetadata("Pos1World").get(0).asString().equals(player.getLocation().getWorld().getName())) {
player.sendMessage(PluginMessages.customPrefix + " Your currently selected area has been shown, it will dissapear shortly!");
Selection.show(player, this.plugin, null);
}
} else {
player.sendMessage(PluginMessages.customPrefixFail + " No regions selected!");
}
}
break;
case "reload":
sender.sendMessage(PluginMessages.customPrefix + " Reloaded values!");
Listeners.reloadValues(plugin);
Portal.loadPortals();
break;
case "list" :
String message = PluginMessages.customPrefix + " \u00A77Portals \u00A7c:\u00A7a";
LinkedList<String> portals = new LinkedList<>();
for (AdvancedPortal portal : Portal.portals) {
portals.add(portal.getName());
}
Collections.sort(portals);
for (Object portalName : portals.toArray()) {
message = message + " " + portalName;
}
player.sendMessage(message);
break;
default:
PluginMessages.UnknownCommand(sender, command);
}
} else {
PluginMessages.UnknownCommand(sender, command);
}
} else {
PluginMessages.NoPermission(sender, command);
}
return true;
}
private void helpCommand(CommandSender sender, String command, String[] args) {
// Add pages if there starts to become too many
if(args.length == 1) {
sendMenu(sender, "Help Menu",
"\u00A76/" + command + " selector \u00A7a- gives you a region selector",
"\u00A76/" + command + " create \u00A7c[tags] \u00A7a- creates a portal with a selection ",
"\u00A76/" + command + " portalblock \u00A7a- gives you a portal block",
"\u00A76/" + command + " endportalblock \u00A7a- gives you an end portal block",
"\u00A76/" + command + " gatewayblock \u00A7a- gives you a gateway block",
"\u00A76/" + command + " select \u00A7a- selects an existing portal",
"\u00A76/" + command + " unselect \u00A7a- unselects the current portal",
"\u00A76/" + command + " command \u00A7a- adds or removes commands from the selected portal",
"\u00A76/" + command + " help \u00A7a- shows this help section",
"\u00A76/" + command + " help <arg> \u00A7a- shows help for the specified arg",
"\u00A76/" + command + " remove \u00A7a- removes a portal",
"\u00A76/" + command + " list \u00A7a- lists all the current portals",
"\u00A76/" + command + " variables \u00A7a- lists all available tags");
}
else if(args.length > 1){
if(args[1].toLowerCase().equals("help")) {
sendMenu(sender, "Help Command",
"Shows the help section. You can also use a single argument after it to show the " +
"help section for the corresponding command.");
}
else if(args[1].toLowerCase().equals("portalblock")) {
sendMenu(sender, "Help Command",
"Gives you a special wool block to place portal blocks.",
"",
"\u00A7eLeft Click: \u00A76Rotates the hit portal block",
"\u00A7eRight Click: \u00A76Placed a portal block");
}
else if(args[1].toLowerCase().equals("endportalblock")) {
sendMenu(sender, "Help Command",
"Gives you a special wool block to place end portal blocks.",
"",
"\u00A7eRight Click: \u00A76Placed a end portal block");
}
else if(args[1].toLowerCase().equals("gatewayblock")) {
sendMenu(sender, "Help Command",
"Gives you a special wool block to place gateway blocks.",
"",
"\u00A7eRight Click: \u00A76Placed a gateway block");
}
else{
sender.sendMessage(PluginMessages.customPrefix + " Either \u00A7e" + args[1] + "\u00A7a is not a command or a help page has not been added yet.");
}
}
}
private void sendMenu(CommandSender sender, String title, String... lines) {
sender.sendMessage(PluginMessages.customPrefix + " " + title);
sender.sendMessage("\u00A7e\u00A7m-----------------------------------");
for(String line : lines){
sender.sendMessage("\u00A7a" + line);
}
sender.sendMessage("\u00A7e\u00A7m-----------------------------------");
}
private String parseArgVariable(String[] args, int currentArg, String argStarter) {
String variableString = args[currentArg].replaceFirst(argStarter, "");
this.portalArgsStringLength = 1;
if (variableString.charAt(0) == '"') {
variableString = variableString.substring(1, variableString.length());
if (variableString.charAt(variableString.length() - 1) != '"') {
currentArg++;
for (; currentArg < args.length; currentArg++) {
variableString += " " + args[currentArg];
this.portalArgsStringLength += 1;
if (variableString.charAt(variableString.length() - 1) == '"') {
variableString = variableString.substring(0, variableString.length() - 1);
break;
}
}
} else {
variableString = variableString.substring(0, variableString.length() - 1);
}
}
return variableString;
}
private void portalEditMenu(CommandSender sender, ConfigAccessor portalConfig, String portalName) {
// make the text gui with the json message for a list of edit commands to be clicked or hovered
// put \" for a " in the json messages
// sadly there is no newline code so these three lines will have to be copied and pasted for each line
// use the usual messages for normal lines but anything that needs special features make sure you use the
// chat steriliser
sender.sendMessage("");
sender.sendMessage(PluginMessages.customPrefix + " Editing: \u00A7e" + portalName);
sender.sendMessage(" \u00A7apos1\u00A7e: " + portalConfig.getConfig().getString(portalName + ".pos1.X")
+ ", " + portalConfig.getConfig().getString(portalName + ".pos1.Y") + ", " + portalConfig.getConfig().getString(portalName + ".pos1.Z"));
sender.sendMessage(" \u00A7apos2\u00A7e: " + portalConfig.getConfig().getString(portalName + ".pos2.X")
+ ", " + portalConfig.getConfig().getString(portalName + ".pos2.Y") + ", " + portalConfig.getConfig().getString(portalName + ".pos2.Z"));
String destination = portalConfig.getConfig().getString(portalName + ".destination");
if (destination != null) {
sender.sendMessage(" \u00A7adestination\u00A7e: " + destination);
} else {
sender.sendMessage(" \u00A7cdestination\u00A7e: null");
}
String trigger = portalConfig.getConfig().getString(portalName + ".triggerblock");
if (trigger != null) {
sender.sendMessage(" \u00A7atriggerBlock\u00A7e: " + trigger);
} else {
sender.sendMessage(" \u00A7ctriggerBlock\u00A7e: null");
}
if (portalConfig.getConfig().getString(portalName + ".portalArgs.command.1") != null) {
int commands = 0;
String command = portalConfig.getConfig().getString(portalName + ".portalArgs.command.1");
// TODO possibly change code so it counds number of subvalues rather than a loop.
while (command != null) {
command = portalConfig.getConfig().getString(portalName + ".portalArgs.command." + ++commands);
}
if (--commands > 1) {
sender.sendMessage(" \u00A7acommands\u00A7e: " + commands + " commands");
} else {
sender.sendMessage(" \u00A7acommands\u00A7e: " + commands + " command");
}
} else {
sender.sendMessage(" \u00A7ccommands\u00A7e: none");
}
sender.sendMessage("");
Player player = (Player) sender;
plugin.compat.sendRawMessage("{\"text\":\"\u00A7aFunctions\u00A7e: \"," +
"\"extra\":[{\"text\":\"\u00A7eRemove\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Remove the selected portal\"},\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/portal gui remove " + portalName + "\"}}"
+ ",{\"text\":\" \"},{\"text\":\"\u00A7eShow\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Show the selected portal\"},\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/portal show " + portalName + "\"}}"
+ ",{\"text\":\" \"},{\"text\":\"\u00A7eRename\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Change the name of the portal\"},\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/portal rename \"}}"
+ ",{\"text\":\" \"},{\"text\":\"\u00A7eTeleport\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Teleport to the set destination\n(If there is one)\"},\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/desti warp " + destination + "\"}}]}", player);
sender.sendMessage("");
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String command, String[] args) {
LinkedList<String> autoComplete = new LinkedList<String>();
if (sender.hasPermission("advancedportals.createportal")) {
if (args.length == 1 || (args.length == 2 && args[0].toLowerCase().equals("help"))) {
autoComplete.addAll(Arrays.asList("create", "list", "portalblock", "select", "unselect", "command", "selector"
, "show", "gatewayblock", "endportalblock", "variables", "wand", "remove", "rename", "help", "bukkitpage", "helppage"));
} else if (args[0].toLowerCase().equals("create")) {
boolean hasName = false;
boolean hasTriggerBlock = false;
boolean hasDestination = false;
boolean isBungeePortal = false;
boolean needsPermission = false;
boolean hasCommand = false;
// TODO change auto complete when quotes are opened and closed. Such as autocomplete @Player and stuff when specifying commands
for (int i = 1; i < args.length; i++) {
String argTag = getTag(args[i].toLowerCase());
if (argTag.length() + 1 < args[i].length()) {
switch (argTag) {
case "name":
hasName = true;
break;
case "destination":
hasDestination = true;
break;
case "desti":
hasDestination = true;
break;
case "triggerblock":
hasTriggerBlock = true;
break;
case "bungee":
isBungeePortal = true;
break;
case "permission":
needsPermission = true;
break;
case "command":
hasCommand = true;
break;
}
}
}
if (!hasName) {
autoComplete.add("name:");
}
if (!hasTriggerBlock) {
autoComplete.add("triggerblock:");
autoComplete.addAll(this.blockMaterialList);
}
if (!hasDestination) {
autoComplete.add("destination:");
autoComplete.add("desti:");
}
if (!isBungeePortal) {
autoComplete.add("bungee:");
}
if (!needsPermission) {
autoComplete.add("permission:");
}
if (!hasCommand) {
autoComplete.add("command:");
}
}
}
Collections.sort(autoComplete);
for (Object result : autoComplete.toArray()) {
if (!result.toString().startsWith(args[args.length - 1])) {
autoComplete.remove(result);
}
}
return autoComplete;
}
private String getTag(String arg) {
int indexOfSplitter = arg.indexOf(':');
if (indexOfSplitter > 0) {
return arg.substring(0, indexOfSplitter);
}
return "";
}
}

View File

@ -1,161 +0,0 @@
package com.sekwah.advancedportals;
import com.sekwah.advancedportals.compat.CraftBukkit;
import com.sekwah.advancedportals.destinations.Destination;
import com.sekwah.advancedportals.destinations.DestinationCommand;
import com.sekwah.advancedportals.effects.WarpEffects;
import com.sekwah.advancedportals.listeners.*;
import com.sekwah.advancedportals.metrics.Metrics;
import com.sekwah.advancedportals.portals.Portal;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.*;
public class AdvancedPortalsPlugin extends JavaPlugin {
public CraftBukkit compat = null;
private Settings settings;
public void onEnable() {
String packageName = getServer().getClass().getPackage().getName();
String[] packageSplit = packageName.split("\\.");
String version = packageSplit[packageSplit.length - 1];
saveDefaultConfig();
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
// Failed to submit the stats :-(
}
try {
this.compat = new CraftBukkit(this, version);
// This is a fix for my stupidity with the last version
File dataFolder = this.getDataFolder();
File configFile = new File(dataFolder, "portals.yml");
InputStreamReader inr = null;
try {
inr = new InputStreamReader(new FileInputStream(configFile), "ASCII");
BufferedReader br = new BufferedReader(inr);
StringBuffer sb = new StringBuffer();
while (true) {
String line = br.readLine();
if (line == null)
break;
sb.append(line);
sb.append("\n");
}
br.close();
inr.close();
String fileContents = sb.toString();
fileContents = fileContents.replaceAll(" getPos1\\(\\):", " pos1:");
fileContents = fileContents.replaceAll(" getPos2\\(\\):", " pos2:");
fileContents = fileContents.replaceAll(" getBungee\\(\\):", " bungee:");
try {
FileWriter fileWriter = new FileWriter(configFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(fileContents);
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
this.getLogger().warning("Invalid Encoding");
} catch (FileNotFoundException e) {
this.getLogger().info("File not found");
} catch (IOException e) {
e.printStackTrace();
}
ConfigAccessor portalConfig = new ConfigAccessor(this, "portals.yml");
portalConfig.saveDefaultConfig();
ConfigAccessor destinationConfig = new ConfigAccessor(this, "destinations.yml");
destinationConfig.saveDefaultConfig();
this.settings = new Settings(this);
// Loads the portal and destination editors
new Portal(this);
new Destination(this);
this.registerCommands();
new WarpEffects(this);
this.addListeners();
this.setupDataCollector();
this.setupBungee();
this.getServer().getConsoleSender().sendMessage("\u00A7aAdvanced portals have been successfully enabled!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
this.getLogger().warning("This version of craftbukkit is not yet supported, please notify sekwah and tell him about this version v:" + version);
this.getLogger().warning("Along with the above stacktrace");
this.setEnabled(false);
} catch (IllegalArgumentException |
NoSuchFieldException | SecurityException | NoSuchMethodException e) {
e.printStackTrace();
this.getLogger().warning("Something went wrong, please notify sekwah and tell him about this version v:" + version);
this.getLogger().warning("Along with the above stacktrace");
this.setEnabled(false);
}
// thanks to the new config accessor code the config.saveDefaultConfig(); will now
// only copy the file if it doesnt exist!
}
private void registerCommands() {
new PluginMessages(this);
new AdvancedPortalsCommand(this);
new DestinationCommand(this);
}
private void addListeners() {
new Listeners(this);
new FlowStopper(this);
new PortalProtect(this);
new PortalPlacer(this);
}
private void setupDataCollector() {
Selection.loadData(this);
}
private void setupBungee() {
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeListener(this));
}
public void onDisable() {
this.getServer().getConsoleSender().sendMessage("\u00A7cAdvanced portals are being disabled!");
}
public Settings getSettings() {
return settings;
}
}

View File

@ -1,81 +0,0 @@
package com.sekwah.advancedportals;
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.IOException;
import java.util.logging.Level;
public class ConfigAccessor {
private final String fileName;
private final JavaPlugin plugin;
private File configFile;
private FileConfiguration fileConfiguration;
public ConfigAccessor(JavaPlugin plugin, String fileName) {
this.plugin = plugin;
this.fileName = fileName;
}
// gets all of the
public void reloadConfig() {
if (configFile == null) {
File dataFolder = plugin.getDataFolder();
if (dataFolder == null)
throw new IllegalStateException();
configFile = new File(dataFolder, fileName);
}
fileConfiguration = YamlConfiguration.loadConfiguration(configFile);
// Look for defaults in the jar
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new File(this.getClass()
.getClassLoader().getResource(fileName).getPath()));
fileConfiguration.setDefaults(defConfig);
}
public FileConfiguration getConfig() {
if (fileConfiguration == null) {
this.reloadConfig();
}
return fileConfiguration;
}
// Saves all the data to the selected yml file
public void saveConfig() {
if (fileConfiguration == null || configFile == null) {
return;
} else {
try {
getConfig().save(configFile);
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex);
}
}
}
// Saves
/**
* public void saveDefaultConfig() {
* if (!configFile.exists()) {
* this.plugin.saveResource(fileName, false);
* }
* }
*/
// New save default config saving code, it checks if the needed config is in the jar file before
// overriding it.
public void saveDefaultConfig() {
if (configFile == null) {
configFile = new File(plugin.getDataFolder(), fileName);
}
if (!configFile.exists()) {
plugin.saveResource(fileName, false);
}
}
}

View File

@ -1,32 +0,0 @@
package com.sekwah.advancedportals;
import org.bukkit.command.CommandSender;
public class PluginMessages {
private AdvancedPortalsPlugin plugin;
public boolean useCustomPrefix = false;
public static String customPrefix = "\u00A7a[\u00A7eAdvancedPortals\u00A7a]";
public static String customPrefixFail = "\u00A7c[\u00A77AdvancedPortals\u00A7c]";
public PluginMessages (AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
ConfigAccessor config = new ConfigAccessor(this.plugin, "config.yml");
this.useCustomPrefix = config.getConfig().getBoolean("UseCustomPrefix");
if (useCustomPrefix) {
PluginMessages.customPrefix = config.getConfig().getString("CustomPrefix").replaceAll("&", "\u00A7");
PluginMessages.customPrefixFail = config.getConfig().getString("CustomPrefixFail").replaceAll("&", "\u00A7");
}
}
// This class is so then the common messages in commands or just messages over the commands are the same and can be
// easily changed.
public static void UnknownCommand(CommandSender sender, String command) {
sender.sendMessage(customPrefixFail + " You need to type something after /" + command + "\n");
sender.sendMessage("\u00A7cIf you do not know what you can put or would like some help with the commands please type \u00A7e" + '"' + "\u00A7e/" + command + " help" + '"' + "\u00A7c\n");
}
public static void NoPermission(CommandSender sender, String command) {
sender.sendMessage(customPrefixFail + " You do not have permission to perform that command!");
}
}

View File

@ -1,207 +0,0 @@
package com.sekwah.advancedportals;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public class Selection {
private static Material blockType = Material.STAINED_GLASS;
private static int timeout = 10;
private static byte metadata = 14;
@SuppressWarnings("deprecation")
public static void loadData(AdvancedPortalsPlugin plugin) {
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
timeout = config.getConfig().getInt("ShowSelectionShowDuration");
String BlockID = config.getConfig().getString("ShowSelectionBlockID");
try {
blockType = Material.getMaterial(Integer.parseInt(BlockID));
} catch (Exception e) {
blockType = Material.getMaterial(BlockID);
}
if (blockType == null) {
blockType = Material.STAINED_GLASS;
}
metadata = (byte) config.getConfig().getInt("ShowSelectionBlockData");
}
@SuppressWarnings("deprecation")
public static void show(final Player player, final AdvancedPortalsPlugin plugin, String portalName) {
int LowX = 0;
int LowY = 0;
int LowZ = 0;
int HighX = 0;
int HighY = 0;
int HighZ = 0;
if (portalName != null) {
ConfigAccessor portalConfig = new ConfigAccessor(plugin, "portals.yml");
LowX = portalConfig.getConfig().getInt(portalName + ".pos2.X");
LowY = portalConfig.getConfig().getInt(portalName + ".pos2.Y");
LowZ = portalConfig.getConfig().getInt(portalName + ".pos2.Z");
HighX = portalConfig.getConfig().getInt(portalName + ".pos1.X");
HighY = portalConfig.getConfig().getInt(portalName + ".pos1.Y");
HighZ = portalConfig.getConfig().getInt(portalName + ".pos1.Z");
} else {
if (player.getMetadata("Pos1X").get(0).asInt() > player.getMetadata("Pos2X").get(0).asInt()) {
LowX = player.getMetadata("Pos2X").get(0).asInt();
HighX = player.getMetadata("Pos1X").get(0).asInt();
} else {
LowX = player.getMetadata("Pos1X").get(0).asInt();
HighX = player.getMetadata("Pos2X").get(0).asInt();
}
if (player.getMetadata("Pos1Y").get(0).asInt() > player.getMetadata("Pos2Y").get(0).asInt()) {
LowY = player.getMetadata("Pos2Y").get(0).asInt();
HighY = player.getMetadata("Pos1Y").get(0).asInt();
} else {
LowY = player.getMetadata("Pos1Y").get(0).asInt();
HighY = player.getMetadata("Pos2Y").get(0).asInt();
}
if (player.getMetadata("Pos1Z").get(0).asInt() > player.getMetadata("Pos2Z").get(0).asInt()) {
LowZ = player.getMetadata("Pos2Z").get(0).asInt();
HighZ = player.getMetadata("Pos1Z").get(0).asInt();
} else {
LowZ = player.getMetadata("Pos1Z").get(0).asInt();
HighZ = player.getMetadata("Pos2Z").get(0).asInt();
}
}
final Location pos1 = new Location(player.getWorld(), LowX, LowY, LowZ);
final Location pos2 = new Location(player.getWorld(), HighX, HighY, HighZ);
/*
* There are alot of for loops at the moment, when i find an easier way to do these other that a load of if statements
* then i will change it, but for now its the best way i can think of for doing this.
*/
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, LowY, LowZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, LowY, HighZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), LowX, LowY, z);
player.sendBlockChange(loc, blockType, metadata);
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), HighX, LowY, z);
player.sendBlockChange(loc, blockType, metadata);
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), LowX, y, LowZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), LowX, y, HighZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), HighX, y, LowZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), HighX, y, HighZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, HighY, HighZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, HighY, LowZ);
player.sendBlockChange(loc, blockType, metadata);
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), LowX, HighY, z);
player.sendBlockChange(loc, blockType, metadata);
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), HighX, HighY, z);
player.sendBlockChange(loc, blockType, metadata);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
Selection.hide(player, plugin, pos1, pos2);
}
}, timeout * 20);
}
@SuppressWarnings("deprecation")
protected static void hide(Player player, AdvancedPortalsPlugin plugin, Location pos1, Location pos2) {
int LowX = pos1.getBlockX();
int LowY = pos1.getBlockY();
int LowZ = pos1.getBlockZ();
int HighX = pos2.getBlockX();
int HighY = pos2.getBlockY();
int HighZ = pos2.getBlockZ();
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, LowY, LowZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, LowY, HighZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), LowX, LowY, z);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), HighX, LowY, z);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), LowX, y, LowZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), LowX, y, HighZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), HighX, y, LowZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int y = LowY; y <= HighY; y++) {
Location loc = new Location(player.getWorld(), HighX, y, HighZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, HighY, HighZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int x = LowX; x <= HighX; x++) {
Location loc = new Location(player.getWorld(), x, HighY, LowZ);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), LowX, HighY, z);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
for (int z = LowZ; z <= HighZ; z++) {
Location loc = new Location(player.getWorld(), HighX, HighY, z);
player.sendBlockChange(loc, loc.getBlock().getType(), loc.getBlock().getData());
}
}
}

View File

@ -1,40 +0,0 @@
package com.sekwah.advancedportals;
/**
* This contains generally used settings mostly
*/
public class Settings {
private int currentWarpParticles = 0;
private int currentWarpSound = 0;
private String commandLevels = "n";
public Settings(AdvancedPortalsPlugin plugin) {
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
currentWarpParticles = config.getConfig().getInt("WarpParticles");
currentWarpSound = config.getConfig().getInt("WarpSound");
commandLevels = config.getConfig().getString("CommandLevels", "opchek");
if(commandLevels.contains("n") || commandLevels.equals("")) {
commandLevels = "n";
}
}
public String getCommandLevels(){
return this.commandLevels;
}
public boolean hasCommandLevel(String level){
return this.commandLevels.contains(level);
}
public int getCurrentWarpSound() {
return currentWarpSound;
}
public int getCurrentWarpParticles() {
return currentWarpParticles;
}
}

View File

@ -1,15 +0,0 @@
package com.sekwah.advancedportals.api.portaldata;
public class PortalArg {
public final String argName;
public final String value;
public PortalArg(String argName, String value/*, int type*/) {
this.argName = argName;
this.value = value;
// may be used if values need to be 100% not string
//this.type = type;
}
}

View File

@ -1,42 +0,0 @@
package com.sekwah.advancedportals.api.portaldata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by on 29/03/2016.
* <p>
* TODO add all the normal tags then add the extradata tags
*
* @author sekwah41
*/
public class PortalTags {
// TODO create a list or hashmap of tags to check for.
public Map<String, String> tagDesc = new HashMap<String, String>();
public ArrayList<String> tags = new ArrayList<String>();
public void registerTag(String tagName) {
this.registerTag(tagName, false);
}
/**
* Will only be used if a /portal tags command is created. The descriptions will be used for help text
* so please keep it short.
*
* @param tagName
* @param description
*/
public void registerTag(String tagName, boolean multiWord, String description) {
this.registerTag(tagName, multiWord);
}
public void registerTag(String tagName, boolean multiWord) {
}
}

View File

@ -1,71 +0,0 @@
package com.sekwah.advancedportals.api.registry;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.api.warphandler.TagHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by on 25/07/2016.
*
* @author sekwah41
*/
public class TagRegistry {
private final AdvancedPortalsPlugin plugin;
private ArrayList<String> tags = new ArrayList<String>();
private Map<String, TagHandler.Activation> tagActivation = new HashMap<String, TagHandler.Activation>();
private Map<String, TagHandler.Creation> tagCreation = new HashMap<String, TagHandler.Creation>();
private Map<String, TagHandler.TagStatus> tagStatus = new HashMap<String, TagHandler.TagStatus>();
// TODO the event can be used for general data detection and management, but use a TagHandler to make it so they can register
// the individual class to handle.
public TagRegistry(AdvancedPortalsPlugin plugin){
this.plugin = plugin;
}
/**
*
* @return if the tag has been registered or if it already exists.
*/
public boolean registerTag(String tag, TagHandler tagHandler){
if(tag == null){
plugin.getLogger().warning("A tag can not be null.");
return false;
}
if(tags.contains(tag)){
return false;
}
tags.add(tag);
if(tagHandler != null && !(tagHandler instanceof TagHandler.Activation) && !(tagHandler instanceof TagHandler.TagStatus) &&
!(tagHandler instanceof TagHandler.Creation)){
plugin.getLogger().warning("Error with tag: " + tag + ". A tag handler must implement one of the handlers. Not just extend.");
if(tagHandler instanceof TagHandler.Activation){
tagActivation.put(tag, (TagHandler.Activation) tagHandler);
}
if(tagHandler instanceof TagHandler.TagStatus){
tagStatus.put(tag, (TagHandler.TagStatus) tagHandler);
}
if(tagHandler instanceof TagHandler.Creation){
tagCreation.put(tag, (TagHandler.Creation) tagHandler);
}
}
return true;
}
}

View File

@ -1,134 +0,0 @@
package com.sekwah.advancedportals.compat;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by on 02/08/2016.
*
* I don't think there will be any others supported other than bukkit but if there are its not just the compat that will
* need to change unless it has a different package for the minecraft server parts
*
* @author sekwah41 maxqia
*/
public class CraftBukkit {
private final AdvancedPortalsPlugin plugin;
private Method chatMessageTypeMethod;
private Method serializeMessage;
private Constructor<?> chatPacketConstructor;
private Method playerGetHandle;
private Field playerConnection;
private Method sendPacket;
private boolean useEnumType = false;
// Classes so it doesnt keep fetching them.
public CraftBukkit(AdvancedPortalsPlugin plugin, String bukkitImpl) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
this.plugin = plugin;
try {
// CraftBukkit Ahoy!
String craftBukkitPackage = "org.bukkit.craftbukkit." + bukkitImpl + ".";
String minecraftPackage = "net.minecraft.server." + bukkitImpl + ".";
Class<?> chatBaseComponent = Class.forName(minecraftPackage + "IChatBaseComponent"); // string to packet methods
Class<?> chatSerialClass = this.findClass(chatBaseComponent, "ChatSerializer");
try{
Class<?> chatMessageTypeClass = Class.forName(minecraftPackage + "ChatMessageType");
this.chatMessageTypeMethod = chatMessageTypeClass.getMethod("a", byte.class);
this.chatPacketConstructor = Class.forName(minecraftPackage + "PacketPlayOutChat").getConstructor(chatBaseComponent, chatMessageTypeClass);
useEnumType = true;
}
catch(ClassNotFoundException e) {
plugin.getLogger().info("Old version detected, changing chat method");
this.chatPacketConstructor = Class.forName(minecraftPackage + "PacketPlayOutChat").getConstructor(chatBaseComponent, byte.class);
}
if(chatSerialClass != null){
this.serializeMessage = chatSerialClass.getMethod("a", String.class);
}
else{
plugin.getLogger().info("Even older version detected, changing chat method.");
this.serializeMessage = chatBaseComponent.getMethod("a", String.class);
}
this.playerGetHandle = Class.forName(craftBukkitPackage + "entity.CraftPlayer").getMethod("getHandle");
this.playerConnection = Class.forName(minecraftPackage + "EntityPlayer").getField("playerConnection"); // get player connection
Class<?> packet = Class.forName(minecraftPackage + "Packet");
this.sendPacket = playerConnection.getType().getMethod("sendPacket", packet);
} catch (Exception e) {
e.printStackTrace();
plugin.getLogger().warning("Attempting to use backup porekit locations");
// Fall back on your Porekit
Class<?> textBaseComponent = Class.forName("net.minecraft.util.text.ITextComponent"); // string to packet methods
this.serializeMessage = this.findClass(textBaseComponent, "Serializer").getMethod("func_150699_a", String.class); // md: jsonToComponent
this.chatPacketConstructor = Class.forName("net.minecraft.network.play.server.SPacketChat").getConstructor(textBaseComponent, byte.class);
this.playerGetHandle = Class.forName("blue.lapis.pore.impl.entity.PorePlayer").getMethod("getHandle");
this.playerConnection = Class.forName("net.minecraft.entity.player.EntityPlayerMP").getField("field_71135_a"); // get player connection fd: connection
Class<?> packet = Class.forName("net.minecraft.network.Packet");
this.sendPacket = playerConnection.getType().getMethod("func_147359_a", packet); //md: sendPacket
}
}
public void sendRawMessage(String rawMessage, Player player) {
this.sendMessage(rawMessage,player, (byte) 1);
}
public void sendActionBarMessage(String rawMessage, Player player) {
this.sendMessage(rawMessage,player, (byte) 2);
}
public void sendMessage(String rawMessage, Player player, byte msgType) {
try {
Object comp = this.serializeMessage.invoke(null,rawMessage); // convert string into bytes
Object packet;
if(useEnumType){
packet = this.chatPacketConstructor.newInstance(comp, this.chatMessageTypeMethod.invoke(null,msgType)); // convert bytes into packet
}
else{
packet = this.chatPacketConstructor.newInstance(comp, msgType); // convert bytes into packet
}
Object handle = this.playerGetHandle.invoke(player);
Object playerConnection = this.playerConnection.get(handle); // get players connection
sendPacket.invoke(playerConnection, packet); // send packet
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
this.plugin.getLogger().warning("Error creating raw message, something must be wrong with reflection");
e.printStackTrace();
}
/*IChatBaseComponent comp = IChatBaseComponent.ChatSerializer.a(rawMessage);
// "json message", position(0: chat (chat box), 1: system message (chat box), 2: above action bar)
PacketPlayOutChat packet = new PacketPlayOutChat(comp, (byte) 1);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);*/
}
public Class<?> findClass(Class<?> classObj, String className){
for(Class<?> classes : classObj.getDeclaredClasses()){
if(classes.getSimpleName().equals(className)){
return classes;
}
}
return null;
}
}

View File

@ -0,0 +1,39 @@
package com.sekwah.advancedportals.core;
import com.sekwah.advancedportals.core.util.DataStorage;
import com.sekwah.advancedportals.core.util.InfoLogger;
public class AdvancedPortalsCore {
private static AdvancedPortalsCore instance;
private static CoreConnector coreConnector;
private static DataStorage dataStorage;
private static InfoLogger infoLogger;
public AdvancedPortalsCore(CoreConnector coreConnector, DataStorage dataStorage, InfoLogger infoLogger) {
this.dataStorage = dataStorage;
this.infoLogger = infoLogger;
this.instance = this;
this.coreConnector = coreConnector;
}
private static AdvancedPortalsCore getInstance() {
return instance;
}
public static DataStorage getDataStorage() {
return dataStorage;
}
public static InfoLogger getInfoLogger() {
return infoLogger;
}
public static CoreConnector getCoreConnector() {
return coreConnector;
}
public interface CoreConnector {
DataStorage getDataStorage();
}
}

View File

@ -0,0 +1,35 @@
package com.sekwah.advancedportals.core.api.commands;
import org.bukkit.command.CommandSender;
import java.util.List;
/**
* Subcommand that can be registered to parts.
*
* @author sekwah41
*/
public interface SubCommand {
/**
* @param sender
* @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 suggesting to check help)
*/
boolean onCommand(CommandSender sender, String[] args);
/**
*
*
* @param sender
* @param args arguments including the subcommand that has been specified.
* @return tab completion for the subcommand
*/
List<String> onTabComplete(CommandSender sender, String[] args);
/**
* @return the string to show on the above help menu. (describing the subcommand)
*/
String getHelpText();
}

View File

@ -0,0 +1,13 @@
package com.sekwah.advancedportals.core.api.destination;
/**
* Possibly look at adding the ability to add some tags to destinations such as permissions. Would make it easier
* to add permissions to block access to certain areas and such. Could be a different permission system or just
* it takes the tags on the destination and automatically applies them when a portal wants to warp to there.
* (Of course it would not work cross server unless the data was communicated and checked first however that
* could effect performance and would definitely effect speed)
*
* @author sekwah41
*/
public class Destination {
}

View File

@ -0,0 +1,21 @@
package com.sekwah.advancedportals.core.api.effect;
import com.sekwah.advancedportals.core.api.portal.Portal;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
* @author sekwah41
*/
public class TestEffect implements WarpEffect {
@Override
public void onWarp(Player player, Location loc, Action action, Portal portal) {
}
@Override
public Type getType() {
return null;
}
}

View File

@ -0,0 +1,32 @@
package com.sekwah.advancedportals.core.api.effect;
import com.sekwah.advancedportals.core.api.portal.Portal;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
* Effects to be registered to the list.
* <p>
* Fires once at each end.
* <p>
* Can be a Visual effect or a Sound. Just register to the correct one
*
* @author sekwah41
*/
public interface WarpEffect {
void onWarp(Player player, Location loc, Action action, Portal portal);
Type getType();
enum Action {
ENTER,
EXIT;
}
enum Type {
SOUND,
VISUAL;
}
}

View File

@ -0,0 +1,21 @@
package com.sekwah.advancedportals.core.api.events;
/**
* Activated when something about the event is edited.
*
* @author sekwah41
*/
public class PortalEditEvent {
public class TagChange {
}
public class Renamed {
}
public class Moved {
}
}

View File

@ -0,0 +1,16 @@
package com.sekwah.advancedportals.core.api.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Triggered once all the portals are loaded
*
* @author sekwah41
*/
public class PortalsLoadedEvent extends Event {
@Override
public HandlerList getHandlers() {
return null;
}
}

View File

@ -1,32 +1,30 @@
package com.sekwah.advancedportals.api.events;
import com.sekwah.advancedportals.portals.AdvancedPortal;
import com.sekwah.advancedportals.api.portal.Portal;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public final class WarpEvent extends Event implements Cancellable {
/**
* Trigered whenever a player activates the warp after the tags are handled.
*/
public class WarpEvent extends Event implements Cancellable {
/**
* Use listeners so you can add new triggers easier and also other plugins can listen for the event
* and add their own triggers
*/
private static final HandlerList handlers = new HandlerList();
private static HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private Player player;
@SuppressWarnings("unused")
private AdvancedPortal portalData;
private Portal portalData;
private boolean hasWarped = false;
public WarpEvent(Player player, AdvancedPortal portalData) {
/*public WarpEvent(Player player, AdvancedPortal portalData) {
this.player = player;
this.portalData = portalData;
}
}*/
public static HandlerList getHandlerList() {
return handlers;
@ -45,9 +43,9 @@ public final class WarpEvent extends Event implements Cancellable {
cancelled = cancel;
}
public AdvancedPortal getPortalData() {
/*public AdvancedPortal getPortalData() {
return portalData;
}
}*/
/**
* This will return true if another plugin has warped the player(and set this to true)
@ -63,7 +61,6 @@ public final class WarpEvent extends Event implements Cancellable {
*
* @param warped
*/
@SuppressWarnings("unused")
public void setHasWarped(boolean warped) {
this.hasWarped = warped;
}

View File

@ -0,0 +1,7 @@
package com.sekwah.advancedportals.core.api.managers;
/**
* @author sekwah41
*/
public class DestinationManager {
}

View File

@ -0,0 +1,50 @@
package com.sekwah.advancedportals.core.api.managers;
import com.sekwah.advancedportals.core.api.portal.Portal;
import org.bukkit.entity.Player;
import java.util.HashMap;
/**
* When a player leaves the server any data stored on them is removed to free memory.
*
* @author sekwah41
*/
public class PortalManager {
/**
* Cooldown time for players to try entering portals.
*/
private static final int COOLDOWN = 0;
private static PortalManager instance = new PortalManager();
/**
* Store data of when the player last entered the portal
*/
private HashMap<Player, Long> lastAttempt = new HashMap();
/**
* Tracks what portal a player has selected
*/
private HashMap<Player, Portal> selectedPortal = new HashMap();
public PortalManager() {
this.loadPortals();
}
/**
* A player has left the server
*
* @param player
*/
public static void playerLeave(Player player) {
instance.lastAttempt.remove(player);
instance.selectedPortal.remove(player);
}
/**
* Load the default data into the portals.
*/
private void loadPortals() {
}
}

View File

@ -0,0 +1,7 @@
package com.sekwah.advancedportals.core.api.portal;
/**
* @author sekwah41
*/
public class Portal {
}

View File

@ -0,0 +1,16 @@
package com.sekwah.advancedportals.core.api.portal;
public class PortalTag {
public final String NAME;
public final String VALUE;
//public final int type;
public PortalTag(String argName, String value/*, int type*/) {
this.NAME = argName;
this.VALUE = value;
// may be used if values need to be 100% not string
//this.type = type;
}
}

View File

@ -0,0 +1,9 @@
package com.sekwah.advancedportals.core.api.registry;
/**
* Designed to let addons add new command sections to access, edit or add new functonality.
*
* @author sekwah41
*/
public class DestinationSubCommandRegistry extends SubCommandRegistry {
}

View File

@ -0,0 +1,11 @@
package com.sekwah.advancedportals.core.api.registry;
/**
* Designed to let addons add new command sections to access, edit or add new functonality.
*
* @author sekwah41
*/
public class PortalSubCommandRegistry extends SubCommandRegistry {
}

View File

@ -0,0 +1,84 @@
package com.sekwah.advancedportals.core.api.registry;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.api.commands.SubCommand;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 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.
*
* @author sekwah41
*/
public class SubCommandRegistry {
private Map<String, SubCommand> subCommandMap = new HashMap<>();
private static final SubCommandRegistry instance = new SubCommandRegistry();
/**
* List of subcommand names which should be in order alphabetically
*/
private ArrayList<String> subCommands = new ArrayList<>();
/**
* @param arg argument needed to activate
* @param subCommand
* @return if the subcommand is registered or not
*/
public static boolean registerSubCommand(String arg, SubCommand subCommand) {
if (subCommand == null) {
AdvancedPortalsCore.getInfoLogger().logWarning("The subcommand '" + arg + "' cannot be null.");
return false;
}
if(!instance.subCommandMap.containsKey(arg)){
AdvancedPortalsCore.getInfoLogger().logWarning("The subcommand '" + arg + "' already exists.");
return false;
}
instance.subCommandMap.put(arg.toLowerCase(), subCommand);
instance.subCommands.add(arg.toLowerCase());
Collections.sort(instance.subCommands);
return true;
}
/**
* @return a list of arguments of registered subcommands
*/
public static ArrayList<String> getSubCommands(){
return instance.subCommands;
}
/**
* I may be wrong but for larger lists containsKey is faster with a hashmap than arraylist.
*
* Though im not sure at what size it becomes more efficient.
* @param arg
* @return if the argument is registered
*/
public static boolean isArgRegistered(String arg){
return instance.subCommandMap.containsKey(arg.toLowerCase());
}
/**
* Gets the subcommand corresponding to the string argument
* @param arg
* @return the subcommand linked to the arg
*/
public static SubCommand getSubCommand(String arg){
if(instance.subCommandMap.containsKey(arg.toLowerCase())){
return instance.subCommandMap.get(arg.toLowerCase());
}
return null;
}
}

View File

@ -0,0 +1,123 @@
package com.sekwah.advancedportals.api.registry;
import com.sekwah.advancedportals.api.warphandler.TagHandler;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Allows a portal to register a tag and add a handler. If a plugin wants to add functionality
* to someone elses tag then they should use the events.
*
* @author sekwah41
*/
public class TagRegistry {
// TODO the event can be used for general data detection and management, but use a TagHandler to make it so they can register
// the individual class to handle.
private static TagRegistry instance = new TagRegistry();
/**
* List of tag names which should be in order alphabetically
*/
private ArrayList<String> tags = new ArrayList();
/**
* Description of tags for help commands
*/
private Map<String, String> tagDesc = new HashMap();
private Map<String, TagHandler.Activation> activationHandlers = new HashMap();
private Map<String, TagHandler.Creation> creationHandlers = new HashMap();
private Map<String, TagHandler.TagStatus> statusHandlers = new HashMap();
/**
*
* @param tag
* @param desc
* @param tagHandler
* @return if the tag was registered
*/
public static boolean registerTag(String tag, String desc, TagHandler tagHandler) {
if (registerTag(tag, tagHandler)) {
instance.tagDesc.put(tag, desc);
}
return false;
}
/**
* It is reccomended that you use the taghandlers to add tag functionality. However
* if needed such as extra data for a tag then this is here.
*
* @param tag
* @return if the tag was registered
*/
public static boolean registerTag(String tag) {
if (tag.contains(" ")) {
AdvancedPortalsCore.getInfoLogger().logWarning("The tag '"
+ tag + "' is invalid as it contains spaces.");
return false;
}
if (instance.tags.contains(tag)) {
AdvancedPortalsCore.getInfoLogger().logWarning("The tag "
+ tag + " has already been registered.");
return false;
}
instance.tags.add(tag);
Collections.sort(instance.tags);
return true;
}
/**
* Same as registerTag(String tag) but allows a description to be added.
*
* @param tag Tag to be used on command line
* @param desc
* @return if the tag was registered
*/
public static boolean registerTag(String tag, String desc) {
if (registerTag(tag)) {
instance.tagDesc.put(tag, desc);
return true;
}
return false;
}
public static boolean isTagRegistered(String tag){
return instance.tagDesc.containsKey(tag);
}
/**
* @return if the tag has been registered or if it already exists.
*/
public static boolean registerTag(String tag, TagHandler tagHandler) {
if (tag == null) {
AdvancedPortalsCore.getInfoLogger().logWarning("A tag cannot be null.");
return false;
}
if (!registerTag(tag)) {
return false;
}
if (tagHandler != null && !(tagHandler instanceof TagHandler.Activation) && !(tagHandler instanceof TagHandler.TagStatus) &&
!(tagHandler instanceof TagHandler.Creation)) {
AdvancedPortalsCore.getInfoLogger().logWarning("Error with tag: " + tag + ". A tag handler must implement one of the handlers. Not just extend.");
if (tagHandler instanceof TagHandler.Activation) {
instance.activationHandlers.put(tag, (TagHandler.Activation) tagHandler);
}
if (tagHandler instanceof TagHandler.TagStatus) {
instance.statusHandlers.put(tag, (TagHandler.TagStatus) tagHandler);
}
if (tagHandler instanceof TagHandler.Creation) {
instance.creationHandlers.put(tag, (TagHandler.Creation) tagHandler);
}
}
return true;
}
}

View File

@ -0,0 +1,76 @@
package com.sekwah.advancedportals.core.api.registry;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.api.effect.WarpEffect;
import java.util.HashMap;
import java.util.Map;
/**
* @author sekwah41
*/
public class WarpEffectRegistry {
private Map<String, WarpEffect> visualEffects = new HashMap();
private Map<String, WarpEffect> soundEffects = new HashMap();
private static final WarpEffectRegistry instance = new WarpEffectRegistry();
/**
* Register a new warp effect.
*
* @param name
* @param effect
* @return if the effect was registered
*/
public static boolean registerEffect(String name, WarpEffect effect) {
if(name == null){
return false;
}
Map<String, WarpEffect> list = null;
switch (effect.getType()){
case SOUND:
list = instance.soundEffects;
break;
case VISUAL:
list = instance.visualEffects;
break;
default:
AdvancedPortalsCore.getInfoLogger().logWarning(effect.getType().toString()
+ " effect type not recognised");
return false;
}
if(list.containsKey(name)){
return false;
}
list.put(name, effect);
return true;
}
public static WarpEffect getEffect(String name, WarpEffect.Type type){
Map<String, WarpEffect> list = null;
switch (type){
case SOUND:
list = instance.soundEffects;
break;
case VISUAL:
list = instance.visualEffects;
break;
default:
AdvancedPortalsCore.getInfoLogger().logWarning(type.toString()
+ " effect type not recognised");
return null;
}
if(list.containsKey(name)) {
return list.get(name);
}
else{
AdvancedPortalsCore.getInfoLogger().logWarning("No effect of type:"
+ type.toString() + " was registered with the name: " + name);
return null;
}
}
}

View File

@ -1,6 +1,5 @@
package com.sekwah.advancedportals.api.warphandler;
import com.sekwah.advancedportals.portals.Portal;
/**
* Created by on 30/07/2016.
@ -13,21 +12,20 @@ public class ActivationData {
private WarpedStatus warpStatus = WarpedStatus.INACTIVE;
private Portal activePortal;
//private Portal activePortal;
public ActivationData(Portal portal){
/*public ActivationData(Portal portal){
this.activePortal = portal;
}
public WarpedStatus getWarped(){
*/
public WarpedStatus getWarped() {
return this.warpStatus;
}
public void setWarpStatus(WarpedStatus warped){
if(this.warpStatus == WarpedStatus.WARPED){
public void setWarpStatus(WarpedStatus warped) {
if (this.warpStatus == WarpedStatus.WARPED) {
return;
}
else if(this.warpStatus == WarpedStatus.INACTIVE){
} else if (this.warpStatus == WarpedStatus.INACTIVE) {
return;
}
this.warpStatus = warped;
@ -35,21 +33,22 @@ public class ActivationData {
/**
* In case you need to set the status back down a step for whatever reason. However it is not recommended.
*
* @param warped
*/
public void setWarpStatusAbsolute(WarpedStatus warped){
public void setWarpStatusAbsolute(WarpedStatus warped) {
this.warpStatus = warped;
}
public boolean getAllowed(){
public boolean getAllowed() {
return this.warpAllowed;
}
public void setAllowed(boolean allowed){
public void setAllowed(boolean allowed) {
this.warpAllowed = allowed;
}
public enum WarpedStatus{
public enum WarpedStatus {
/**
* Player has moved or something major has happened. (only one of these should activate)
*/

View File

@ -2,6 +2,8 @@ package com.sekwah.advancedportals.api.warphandler;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
/**
* Created by on 30/07/2016.
*
@ -9,32 +11,45 @@ import org.bukkit.entity.Player;
*/
public class TagHandler {
public interface Creation{
/**
* When the user wants to activate the tag, not all will support this of course. its just a _ before or after the tag
* to specify
*/
public enum ActivatePref{
BEFORE,
AFTER,
DEFAULT;
}
public interface Creation {
/**
* Example if the player does not have access to use a tag on the portal.
* @param player
*
* @param player if null the portal has been created by the server or a plugin
* @param activeData
* @param argData
* @return if the portal can be created.
*/
boolean portalCreated(Player player, ActivationData activeData, String argData);
boolean portalCreated(@Nullable Player player, ActivationData activeData, String argData);
/**
* Example if the player does not have access to remove the portal.
* @param player
*
* @param player if null the portal has been destroyed by the server or a plugin
* @param activeData
* @param argData
* @return if the portal can be destroyed.
*/
boolean portalDestroyed(Player player, ActivationData activeData, String argData);
boolean portalDestroyed(@Nullable Player player, ActivationData activeData, String argData);
}
public interface Activation{
public interface Activation {
/**
* Activates before the main part of portal activation.
*
* @param player
* @param activeData
* @param argData
@ -43,6 +58,7 @@ public class TagHandler {
/**
* Activates after portal activation
*
* @param player
* @param activeData
* @param argData
@ -51,6 +67,7 @@ public class TagHandler {
/**
* Activates if the portal is allowed from pre
*
* @param player
* @param activeData
* @param argData
@ -59,25 +76,27 @@ public class TagHandler {
}
public interface TagStatus{
public interface TagStatus {
/**
* If the user has access to add the tag
*
* @param player
* @param activeData
* @param argData
* @return if the tag will be added.
*/
boolean tagAdded(Player player, ActivationData activeData, String argData);
boolean tagAdded(@Nullable Player player, ActivationData activeData, String argData);
/**
* If the user has access to remove the tag
*
* @param player
* @param activeData
* @param argData
* @return if the tag will be removed.
*/
boolean ragRemoved(Player player, ActivationData activeData, String argData);
boolean tagRemoved(@Nullable Player player, ActivationData activeData, String argData);
}

View File

@ -0,0 +1,97 @@
package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import java.io.*;
public abstract class DataStorage {
protected File dataFolder;
/**
* Copies the default file, defaults to true to keep true to the name
*
* @param fileLoc
* @return
*/
public boolean copyDefaultFile(String fileLoc) {
return this.copyDefaultFile(fileLoc, true);
}
public void copyDefaultFiles(boolean override, String... fileLocs) {
for (String fileLoc : fileLocs) {
this.copyDefaultFile(fileLoc, override);
}
}
/**
* Copies the specified file out of the plugin and into the plugins folder.
*
* @param fileLoc
* @return if the file is copied, will be false if override is false and the file already existed.
*/
public boolean copyDefaultFile(String fileLoc, boolean overwrite) {
File outFile = new File(this.dataFolder, fileLoc);
if (!outFile.exists()) {
outFile.getParentFile().mkdirs();
}
if (!outFile.exists() || overwrite) {
try {
InputStream inputStream = DataStorage.class.getClassLoader().getResourceAsStream(fileLoc);
FileOutputStream outStream = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outStream.write(buf, 0, len);
}
inputStream.close();
outStream.close();
} catch (NullPointerException e) {
e.printStackTrace();
AdvancedPortalsCore.getInfoLogger().logWarning("Could not load " + fileLoc + ". The file does" +
"not exist or there has been an error reading the file.");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
AdvancedPortalsCore.getInfoLogger().logWarning("Could not create " + fileLoc);
} catch (IOException e) {
e.printStackTrace();
AdvancedPortalsCore.getInfoLogger().logWarning("File error reading " + fileLoc);
}
}
return true;
}
/**
* A method to try to grab the files from the plugin and if its in the plugin folder load from there instead.
* <p>
* TODO add loading from the plugin folder first rather than straight from the plugin.
*
* @param lang
* @param location
* @return
*/
public InputStream loadResource(Lang lang, String location) {
File inFile = new File(dataFolder, location);
if (inFile.exists() && !inFile.isDirectory()) {
try {
return new FileInputStream(inFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
} else {
try {
copyDefaultFile(location, false);
return lang.getClass().getClassLoader().getResourceAsStream(location);
} catch (NullPointerException e) {
e.printStackTrace();
AdvancedPortalsCore.getInfoLogger().logWarning("Could not load " + location + ". The file does" +
"not exist or there has been an error reading the file.");
return null;
}
}
}
}

View File

@ -0,0 +1,5 @@
package com.sekwah.advancedportals.core.util;
public abstract class InfoLogger {
public abstract void logWarning(String s);
}

View File

@ -0,0 +1,113 @@
package com.sekwah.advancedportals.core.util;
import com.google.common.collect.Maps;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Scanner;
/**
* @author sekwah41
* <p>
* The language translation file for the game. Will always load english first
* so that if the translations are missing any then they are still readable and can then be translated.
* (Its better than a raw translate string)
* <p>
* TODO add a loaddefault where it only loads from the plugins version of the data rather than paying attention to any
* possible changed versions in the lang folder.
*/
public class Lang {
private static final Lang instance = new Lang();
private final Map<String, String> languageMap = Maps.newHashMap();
private final String DEFAULT_LANG = "en_GB";
public Lang() {
injectTranslations(this, DEFAULT_LANG);
}
public static void loadLanguage(String fileName) {
instance.injectTranslations(instance, fileName);
}
public static String translate(String s) {
if (instance.languageMap.containsKey(s)) {
return instance.languageMap.get(s);
} else {
return s;
}
}
public static String translateInsertVariables(String s, String... args) {
String translation = instance.translate(s);
for (int i = 1; i <= args.length; i++) {
translation = translation.replaceAll("%" + i + "$s", args[i]);
}
return translation;
}
public static String translateInsertVariablesColor(String s, String... args) {
String translation = instance.translateColor(s);
for (int i = 1; i <= args.length; i++) {
translation = translation.replaceAll("%" + i + "$s", args[i]);
}
return translation;
}
public static String translateColor(String s) {
String translation = instance.translate(s);
translation = translation.replaceAll("\\\\u00A7", "\u00A7");
return translation;
}
private void injectTranslations(Lang lang, String fileName) {
try {
//URL url = lang.getClass().getClassLoader().getResource("lang/" + fileName + ".lang");
//System.out.println(url);
//Map<String, String> newLangMap = lang.parseLang(url.openStream());
InputStream stream = AdvancedPortalsCore.getDataStorage().loadResource(lang, "lang/" + fileName + ".lang");
if (stream != null) {
Map<String, String> newLangMap = lang.parseLang(stream);
if (newLangMap != null) {
lang.languageMap.putAll(newLangMap);
}
}
} catch (NullPointerException e) {
e.printStackTrace();
AdvancedPortalsCore.getInfoLogger().logWarning("Could not load " + fileName + ".lang The file does" +
"not exist or there has been an error reading the file. Canceled loading language file.");
}
}
private Map<String, String> parseLang(InputStream inputStream) {
Scanner scanner = new Scanner(inputStream, "UTF-8");
String line = getNextLine(scanner);
Map<String, String> newMap = Maps.newHashMap();
while (scanner != null && line != null) {
//System.out.println(line);
if (!line.startsWith("#") && line.indexOf('=') > -1) {
int split = line.indexOf('=');
String key = line.substring(0, split);
String value = line.substring(split + 1, line.length());
newMap.put(key, value);
}
line = getNextLine(scanner);
// TODO add split code at the first = and also conversion of strings/codes which are constants like colors.
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return newMap;
}
private String getNextLine(Scanner scanner) {
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
return null;
}
}

View File

@ -1,163 +0,0 @@
package com.sekwah.advancedportals.destinations;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.PluginMessages;
import com.sekwah.advancedportals.effects.WarpEffects;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.logging.Level;
public class Destination {
private static AdvancedPortalsPlugin plugin;
private static boolean TeleportRiding = false;
public static int PortalMessagesDisplay = 0;
public Destination(AdvancedPortalsPlugin plugin) {
Destination.plugin = plugin;
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
TeleportRiding = config.getConfig().getBoolean("WarpRiddenEntity");
PortalMessagesDisplay = config.getConfig().getInt("WarpMessageDisplay");
}
// TODO add permissions for destinations.
// TODO try keeping the chunks loaded and add different delays to events to make
// the horse teleport when you have more time.(its an annoying bug caused by changed)
// in mc
public static void create(Location location, String name) {
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
config.getConfig().set(name.toLowerCase() + ".world", location.getWorld().getName());
config.getConfig().set(name.toLowerCase() + ".pos.X", location.getX());
config.getConfig().set(name.toLowerCase() + ".pos.Y", location.getY());
config.getConfig().set(name.toLowerCase() + ".pos.Z", location.getZ());
config.getConfig().set(name.toLowerCase() + ".pos.pitch", location.getPitch());
config.getConfig().set(name.toLowerCase() + ".pos.yaw", location.getYaw());
config.saveConfig();
}
public static void move(Location location, String name) {
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
config.getConfig().set(name.toLowerCase() + ".world", location.getWorld().getName());
config.getConfig().set(name.toLowerCase() + ".pos.X", location.getX());
config.getConfig().set(name.toLowerCase() + ".pos.Y", location.getY());
config.getConfig().set(name.toLowerCase() + ".pos.Z", location.getZ());
config.getConfig().set(name.toLowerCase() + ".pos.pitch", location.getPitch());
config.getConfig().set(name.toLowerCase() + ".pos.yaw", location.getYaw());
config.saveConfig();
}
public static void rename(String oldName, String newName) {
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
config.getConfig().set(newName.toLowerCase() + ".world", config.getConfig().getString(oldName + ".world"));
config.getConfig().set(newName.toLowerCase() + ".pos.X", config.getConfig().getDouble(oldName + ".pos.X"));
config.getConfig().set(newName.toLowerCase() + ".pos.Y", config.getConfig().getDouble(oldName + ".pos.Y"));
config.getConfig().set(newName.toLowerCase() + ".pos.Z", config.getConfig().getDouble(oldName + ".pos.Z"));
config.getConfig().set(newName.toLowerCase() + ".pos.pitch", config.getConfig().getDouble(oldName + ".pos.pitch"));
config.getConfig().set(newName.toLowerCase() + ".pos.yaw", config.getConfig().getDouble(oldName + ".pos.yaw"));
remove(oldName);
config.saveConfig();
}
public static void remove(String name) {
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
config.getConfig().set(name.toLowerCase() + ".world", null);
config.getConfig().set(name.toLowerCase() + ".pos.X", null);
config.getConfig().set(name.toLowerCase() + ".pos.Y", null);
config.getConfig().set(name.toLowerCase() + ".pos.Z", null);
config.getConfig().set(name.toLowerCase() + ".pos.pitch", null);
config.getConfig().set(name.toLowerCase() + ".pos.yaw", null);
config.getConfig().set(name.toLowerCase() + ".pos", null);
config.getConfig().set(name.toLowerCase(), null);
config.saveConfig();
}
public static boolean warp(Player player, String name) {
if (!(player.hasPermission("advancedportals.warp.*") || player.hasPermission("advancedportals.warp." + name))) {
player.sendMessage(PluginMessages.customPrefixFail + " You don't have permission to warp to " + name + "!");
return false;
}
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
if (config.getConfig().getString(name + ".world") != null) {
Location loc = player.getLocation();
if (Bukkit.getWorld(config.getConfig().getString(name + ".world")) != null) {
loc.setWorld(Bukkit.getWorld(config.getConfig().getString(name + ".world")));
loc.setX(config.getConfig().getDouble(name + ".pos.X"));
loc.setY(config.getConfig().getDouble(name + ".pos.Y"));
loc.setZ(config.getConfig().getDouble(name + ".pos.Z"));
loc.setPitch((float) config.getConfig().getDouble(name + ".pos.pitch"));
loc.setYaw((float) config.getConfig().getDouble(name + ".pos.yaw"));
WarpEffects.activateParticles(player);
WarpEffects.activateSound(player);
Chunk c = loc.getChunk();
Entity riding = player.getVehicle();
if (!c.isLoaded()) c.load();
if (player.getVehicle() != null && TeleportRiding) {
riding.eject();
riding.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);
player.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);
riding.setPassenger(player);
} else {
player.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);
}
WarpEffects.activateParticles(player);
WarpEffects.activateSound(player);
if (PortalMessagesDisplay == 1) {
player.sendMessage("");
player.sendMessage(PluginMessages.customPrefixFail + "\u00A7a You have been warped to \u00A7e" + name.replaceAll("_", " ") + "\u00A7a.");
player.sendMessage("");
} else if (PortalMessagesDisplay == 2) {
plugin.compat.sendActionBarMessage("{\"text\":\"\u00A7aYou have warped to \u00A7e" + name.replaceAll("_", " ") + "\u00A7a.\"}", player);
/**plugin.nmsAccess.sendActionBarMessage("[{text:\"You have warped to \",color:green},{text:\"" + config.getConfig().getString(Portal.portals[portalId].portalName + ".destination").replaceAll("_", " ")
+ "\",color:yellow},{\"text\":\".\",color:green}]", player);*/
}
return true;
} else {
player.sendMessage(PluginMessages.customPrefixFail + "\u00A7c The destination you are trying to warp to seems to be linked to a world that doesn't exist!");
plugin.getLogger().log(Level.SEVERE, "The destination '" + name + "' is linked to the world "
+ config.getConfig().getString(name + ".world") + " which doesnt seem to exist any more!");
}
} else {
player.sendMessage(PluginMessages.customPrefix + "\u00A7c The destination you are currently attempting to warp to doesnt exist!");
plugin.getLogger().log(Level.SEVERE, "The destination '" + name + "' has just had a warp "
+ "attempt and either the data is corrupt or that destination doesn't exist!");
}
return false;
}
}

View File

@ -1,138 +0,0 @@
package com.sekwah.advancedportals.destinations;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.PluginMessages;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class DestinationCommand implements CommandExecutor, TabCompleter {
private AdvancedPortalsPlugin plugin;
public DestinationCommand(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
plugin.getCommand("destination").setExecutor(this);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String command, String[] args) {
if(!(sender instanceof Player)) {
sender.sendMessage(PluginMessages.customPrefixFail + " You cannot use commands with the console.");
return true;
}
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
if (args.length > 0) { switch (args[0].toLowerCase()) {
case "create":
if (sender.hasPermission("advancedportals.desti")) {
if (args.length > 1) {
String posX = config.getConfig().getString(args[1].toLowerCase() + ".pos.X");
if (posX == null) {
sender.sendMessage(PluginMessages.customPrefix + " You have created a new destination called \u00A7e" + args[1] + "!");
Player player = (Player) sender;
Destination.create(player.getLocation(), args[1]);
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " A destination by that name already exists!");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " Please state the name of the destination you would like to create!");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You do not have permission to create destinations!");
}
break;
case "remove":
ConfigAccessor portalConfig = new ConfigAccessor(plugin, "destinations.yml");
if (sender.hasPermission("advancedportals.desti")) {
if (args.length > 1) {
String posX = portalConfig.getConfig().getString(args[1] + ".pos.X");
if (posX != null) {
Destination.remove(args[1]);
sender.sendMessage(PluginMessages.customPrefixFail + " The destination \u00A7e" + args[1] + "\u00A7c has been removed!");
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " No destination by that name exists.");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You need to state the name of the destination you wish to remove.");
}
} else {
sender.sendMessage(PluginMessages.customPrefixFail + " You do not have permission to remove destinations!");
}
break;
case "list":
String message = PluginMessages.customPrefix + " \u00A77Destinations \u00A7c:\u00A7a";
List<Object> destiObj = Arrays.asList(config.getConfig().getKeys(false).toArray());
LinkedList<String> destis = new LinkedList<>();
for (Object object : destiObj.toArray()) {
destis.add(object.toString());
}
Collections.sort(destis);
for (Object desti : destis.toArray()) message = message + " " + desti;
sender.sendMessage(message);
break;
case "help":
sender.sendMessage(PluginMessages.customPrefix + " Destination Help Menu");
sender.sendMessage("\u00A7e\u00A7m----------------------------");
sender.sendMessage("\u00A76/" + command + " create \u00A7c[name] \u00A7a- create destination at your location");
sender.sendMessage("\u00A76/" + command + " remove \u00A7c[name] \u00A7a- remove destination");
sender.sendMessage("\u00A76/" + command + " warp \u00A7c[name] \u00A7a- teleport to destination");
sender.sendMessage("\u00A76/" + command + " list \u00A7a- list all destinations");
sender.sendMessage("\u00A7e\u00A7m----------------------------");
break;
case "warp":
if(args.length >= 2){
Destination.warp((Player) sender, args[1]);
}
else{
sender.sendMessage(PluginMessages.customPrefixFail + " You must specify a warp location!");
}
break;
default:
PluginMessages.UnknownCommand(sender, command);
break;
}
} else {
PluginMessages.UnknownCommand(sender, command);
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String command, String[] args) {
LinkedList<String> autoComplete = new LinkedList<>();
ConfigAccessor config = new ConfigAccessor(plugin, "destinations.yml");
if(args.length > 1 && args[0].equalsIgnoreCase("warp")){
for (String string : config.getConfig().getKeys(false)) {
if (sender.hasPermission("advancedportals.desti.*") | sender.hasPermission("advancedportals.desti." + string))
autoComplete.add(string);
}
}
if (sender.hasPermission("advancedportals.desti") | sender.hasPermission("advancedportals.createportal")) {
if (args.length == 1) {
autoComplete.addAll(Arrays.asList("create", "remove", "help"));
} else if (args[0].toLowerCase().equals("create")) {
}
}
autoComplete.add("warp");
Collections.sort(autoComplete);
for (Object result : autoComplete.toArray()) {
if (!result.toString().startsWith(args[args.length - 1])) {
autoComplete.remove(result);
}
}
return autoComplete;
}
}

View File

@ -1,12 +0,0 @@
package com.sekwah.advancedportals.destinations;
/**
* Created by on 04/08/2016.
*
* TODO load the destinations into memory rather than constantly reading from the yml.
*
* @author sekwah41
*/
public class PortalWarp {
}

View File

@ -1,77 +0,0 @@
package com.sekwah.advancedportals.effects;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class WarpEffects {
private static AdvancedPortalsPlugin plugin = null;
public boolean oldSoundLoc = true;
public static Sound[] sounds = new Sound[2];
public static boolean soundError = false;
public WarpEffects(AdvancedPortalsPlugin pluginTemp) {
plugin = pluginTemp;
sounds[0] = findSound(plugin, "ENTITY_ENDERMEN_TELEPORT", "ENDERMAN_TELEPORT");
// SPIGOT STOP CHANGING THE BLOODY NAMES! we already knew what an explosion was...
sounds[1] = findSound(plugin, "ENTITY_GENERIC_EXPLODE", "EXPLODE");
}
public static Sound findSound(AdvancedPortalsPlugin plugin, String newName, String oldName){
Sound soundFound = null;
try{
soundFound = Sound.valueOf(newName);
plugin.getLogger().info(newName + " found");
} catch (IllegalArgumentException e) {
try {
soundFound = Sound.valueOf(oldName);
plugin.getLogger().info("Using old effect name: " + oldName);
} catch (IllegalArgumentException e2) {
plugin.getLogger().warning("There was an error using both the old and new names for " + newName);
soundError = true;
}
}
return soundFound;
}
public static void activateParticles(Player player) {
Location loc = player.getLocation();
World world = player.getWorld();
switch (plugin.getSettings().getCurrentWarpParticles()){
case 1:
for(int i = 0; i < 10; i++){
world.playEffect(loc, Effect.ENDER_SIGNAL, 0);
}
loc.add(0D, 1D, 0D);
for(int i = 0; i < 10; i++){
world.playEffect(loc, Effect.ENDER_SIGNAL, 0);
}
default: break;
}
}
public static void activateSound(Player player) {
if(!soundError){
Location loc = player.getLocation();
World world = player.getWorld();
switch (plugin.getSettings().getCurrentWarpSound()){
case 1:
world.playSound(loc, sounds[0], 1F, 1F);
default: break;
}
}
}
}

View File

@ -1,53 +0,0 @@
package com.sekwah.advancedportals.listeners;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
/**
* Created by on 29/03/2016.
*
* @author sekwah41
*/
public class BungeeListener implements PluginMessageListener {
private AdvancedPortalsPlugin plugin;
public BungeeListener(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
}
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
if (!channel.equals("BungeeCord")) {
return;
}
ByteArrayDataInput in = ByteStreams.newDataInput(message);
String subchannel = in.readUTF();
if (subchannel.equals("AdvancedPortals")) {
// Any data after this is read like the packets used in the naruto mod
// (same order as sent)
}
}
/**
* Example forward packet.
*
* Construct like the forge packets.
*
* out.writeUTF("Forward"); // So BungeeCord knows to forward it
out.writeUTF("ALL");
out.writeUTF("MyChannel"); // The channel name to check if this your data
ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
DataOutputStream msgout = new DataOutputStream(msgbytes);
msgout.writeUTF("Some kind of data here"); // You can do anything you want with msgout
msgout.writeShort(123);
out.writeShort(msgbytes.toByteArray().length);
out.write(msgbytes.toByteArray());
*
*/
}

View File

@ -1,37 +0,0 @@
package com.sekwah.advancedportals.listeners;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.portals.Portal;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockFromToEvent;
public class FlowStopper implements Listener {
private final AdvancedPortalsPlugin plugin;
// The needed config values will be stored so they are easier to access later
// an example is in the interact event in this if statement if((!UseOnlyServerAxe || event.getItem().getItemMeta().getDisplayName().equals("<EFBFBD>eP...
private boolean WaterFlow = true;
public FlowStopper(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
this.WaterFlow = config.getConfig().getBoolean("StopWaterFlow");
if (WaterFlow) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockFromTo(BlockFromToEvent event) {
if (Portal.inPortalRegion(event.getBlock().getLocation(), 3) | Portal.inPortalRegion(event.getToBlock().getLocation(), 3))
event.setCancelled(true);
}
}

View File

@ -1,277 +0,0 @@
package com.sekwah.advancedportals.listeners;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.PluginMessages;
import com.sekwah.advancedportals.api.events.WarpEvent;
import com.sekwah.advancedportals.portals.AdvancedPortal;
import com.sekwah.advancedportals.portals.Portal;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
public class Listeners implements Listener {
// The needed config values will be stored so they are easier to access later
// an example is in the interact event in this if statement if((!UseOnlyServerAxe || event.getItem().getItemMeta().getDisplayName().equals("\u00A7eP...
private static boolean UseOnlyServerAxe = false;
private static Material WandMaterial;
private final AdvancedPortalsPlugin plugin;
@SuppressWarnings("deprecation")
public Listeners(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
UseOnlyServerAxe = config.getConfig().getBoolean("UseOnlyServerMadeAxe");
String ItemID = config.getConfig().getString("AxeItemId");
if(ItemID == null){
WandMaterial = Material.IRON_AXE;
}
else{
try {
WandMaterial = Material.getMaterial(Integer.parseInt(ItemID));
} catch (Exception e) {
WandMaterial = Material.getMaterial(ItemID);
}
}
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@SuppressWarnings("deprecation")
public static void reloadValues(AdvancedPortalsPlugin plugin) {
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
UseOnlyServerAxe = config.getConfig().getBoolean("UseOnlyServerMadeAxe");
String ItemID = config.getConfig().getString("AxeItemId");
try {
WandMaterial = Material.getMaterial(Integer.parseInt(ItemID));
} catch (Exception e) {
WandMaterial = Material.getMaterial(ItemID);
}
}
@EventHandler
public void onJoinEvent(PlayerJoinEvent event) {
Portal.cooldown.put(event.getPlayer().getName(), System.currentTimeMillis());
}
@EventHandler
public void onWorldChangeEvent(PlayerChangedWorldEvent event) {
Portal.cooldown.put(event.getPlayer().getName(), System.currentTimeMillis());
}
@EventHandler
public void onTeleportEvent(PlayerTeleportEvent event) {
Portal.cooldown.put(event.getPlayer().getName(), System.currentTimeMillis());
}
@EventHandler
public void spawnMobEvent(CreatureSpawnEvent event) {
if(event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NETHER_PORTAL && Portal.inPortalRegion(event.getLocation(), Portal.getPortalProtectionRadius())) {
event.setCancelled(true);
}
}
@EventHandler
public void onLeaveEvent(PlayerQuitEvent event) {
Portal.cooldown.remove(event.getPlayer().getName());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onMoveEvent(PlayerMoveEvent event) {
// will check if the player is in the portal or not.
if (!Portal.portalsActive) {
return;
}
Player player = event.getPlayer();
//Location fromloc = event.getFrom();
Location loc = event.getTo();
Location eyeLoc = new Location(loc.getWorld(), loc.getX(), loc.getY() + player.getEyeHeight(), loc.getZ());
for (AdvancedPortal portal : Portal.portals) {
if (Portal.locationInPortalTrigger(portal, loc) || Portal.locationInPortalTrigger(portal, eyeLoc)) {
if (portal.getTrigger().equals(Material.PORTAL)) {
if (player.getGameMode().equals(GameMode.CREATIVE)) {
player.setMetadata("hasWarped", new FixedMetadataValue(plugin, true));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new RemoveWarpData(player), 10);
}
} else if (portal.getTrigger().equals(Material.LAVA)) {
player.setMetadata("lavaWarped", new FixedMetadataValue(plugin, true));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new RemoveLavaData(player), 10);
}
if (portal.inPortal.contains(player)) return;
WarpEvent warpEvent = new WarpEvent(player, portal);
plugin.getServer().getPluginManager().callEvent(warpEvent);
if (!event.isCancelled()) Portal.activate(player, portal);
portal.inPortal.add(player);
} else portal.inPortal.remove(player);
}
}
// These are here because java 7 can only take finals straight into a runnable
class RemoveLavaData implements Runnable{
private Player player;
public RemoveLavaData(Player player){
this.player = player;
}
@Override
public void run() {
player.removeMetadata("lavaWarped", plugin);
player.setFireTicks(0);
}
};
class RemoveWarpData implements Runnable{
private Player player;
public RemoveWarpData(Player player){
this.player = player;
}
@Override
public void run() {
if (player != null && player.isOnline()) {
player.removeMetadata("hasWarped", plugin);
}
}
};
@EventHandler
public void onCombustEntityEvent(EntityCombustEvent event) {
if (Portal.inPortalTriggerRegion(event.getEntity().getLocation()))
event.setCancelled(true);
}
@EventHandler
public void onDamEvent(EntityDamageEvent event) {
if (event.getCause() == EntityDamageEvent.DamageCause.LAVA || event.getCause() == EntityDamageEvent.DamageCause.FIRE || event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) {
if (event.getEntity().hasMetadata("lavaWarped") | Portal.inPortalTriggerRegion(event.getEntity().getLocation()))
event.setCancelled(true);
}
}
@EventHandler
public void onPortalEvent(PlayerPortalEvent event) {
Player player = event.getPlayer();
if (player.hasMetadata("hasWarped") | Portal.inPortalRegion(event.getFrom(),1))
event.setCancelled(true);
}
@EventHandler
public void onItemInteract(PlayerInteractEvent event) {
// will detect if the player is using an axe so the points of a portal can be set
// also any other detections such as sign interaction or basic block protection
Player player = event.getPlayer();
if (player.hasMetadata("selectingPortal") && (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK)) {
for (AdvancedPortal portal : Portal.portals) {
if (Portal.locationInPortal(portal, event.getClickedBlock().getLocation(), 0)) {
player.sendMessage(PluginMessages.customPrefix + "\u00A7a You have selected: \u00A7e" + portal.getName());
player.setMetadata("selectedPortal", new FixedMetadataValue(plugin, portal.getName())); // adds the name to the metadata of the character
event.setCancelled(true);
player.removeMetadata("selectingPortal", plugin);
return;
}
}
player.sendMessage(PluginMessages.customPrefixFail + "\u00A7c No portal was selected. If you would like to stop selecting please type \u00A7e/portal select \u00A7cagain!");
event.setCancelled(true);
return;
}
if (player.hasPermission("advancedportals.createportal")) {
// UseOnlyServerMadeAxe being set to true makes is so only the axe generated by the server can be used so other iron axes can be used normally,
// by default its false but it is a nice feature in case the user wants to use the axe normally too, such as a admin playing survival or it being used
// as a weapon.
// Null pointer exeption detected here on some servers(try decompiling the jar file to double check)
/*try {
// Use this to surround the code if needed
}
catch(NullPointerException e){
}*/
if (event.getItem() != null && event.getItem().getType() == WandMaterial // was type id
&& (!UseOnlyServerAxe || (checkItemForName(event.getItem()) && event.getItem().getItemMeta().getDisplayName().equals("\u00A7ePortal Region Selector")))) {
// This checks if the action was a left or right click and if it was directly effecting a block.
if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
Location blockloc = event.getClickedBlock().getLocation();
// stores the selection as metadata on the character so then it isn't saved anywhere, if the player logs out it will
// have to be selected again if the player joins, also it does not affect any other players.
player.setMetadata("Pos1X", new FixedMetadataValue(plugin, blockloc.getBlockX()));
player.setMetadata("Pos1Y", new FixedMetadataValue(plugin, blockloc.getBlockY()));
player.setMetadata("Pos1Z", new FixedMetadataValue(plugin, blockloc.getBlockZ()));
player.setMetadata("Pos1World", new FixedMetadataValue(plugin, blockloc.getWorld().getName()));
player.sendMessage("\u00A7eYou have selected pos1! X:" + blockloc.getBlockX() + " Y:" + blockloc.getBlockY()
+ " Z:" + blockloc.getBlockZ() + " World: " + blockloc.getWorld().getName());
// Stops the event so the block is not damaged
event.setCancelled(true);
// Returns the event so no more code is executed(stops unnecessary code being executed)
} else if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Location blockloc = event.getClickedBlock().getLocation();
player.setMetadata("Pos2X", new FixedMetadataValue(plugin, blockloc.getBlockX()));
player.setMetadata("Pos2Y", new FixedMetadataValue(plugin, blockloc.getBlockY()));
player.setMetadata("Pos2Z", new FixedMetadataValue(plugin, blockloc.getBlockZ()));
player.setMetadata("Pos2World", new FixedMetadataValue(plugin, blockloc.getWorld().getName()));
player.sendMessage("\u00A7eYou have selected pos2! X:" + blockloc.getBlockX() + " Y:" + blockloc.getBlockY()
+ " Z:" + blockloc.getBlockZ() + " World: " + blockloc.getWorld().getName());
// Stops the event so the block is not interacted with
event.setCancelled(true);
// Returns the event so no more code is executed(stops unnecessary code being executed)
}
} else if (checkItemForName(event.getItem()) && event.getItem().getItemMeta().getDisplayName().equals("\u00A75Portal Block Placer") &&
event.getAction() == Action.LEFT_CLICK_BLOCK && event.getClickedBlock().getType() == Material.PORTAL) {
Block block = event.getClickedBlock();
if (block.getData() == 1) {
block.setData((byte) 2);
} else {
block.setData((byte) 1);
}
event.setCancelled(true);
}
}
}
private boolean checkItemForName(ItemStack item){
return item != null && item.hasItemMeta() && item.getItemMeta().hasDisplayName();
}
}

View File

@ -1,62 +0,0 @@
package com.sekwah.advancedportals.listeners;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.portals.Portal;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPlaceEvent;
public class PortalPlacer implements Listener {
@SuppressWarnings("unused")
private final AdvancedPortalsPlugin plugin;
// The needed config values will be stored so they are easier to access later
// an example is in the interact event in this if statement if((!UseOnlyServerAxe || event.getItem().getItemMeta().getDisplayName().equals("<EFBFBD>eP...
private boolean PortalPlace = true;
public PortalPlacer(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
this.PortalPlace = config.getConfig().getBoolean("CanBuildPortalBlock");
if (PortalPlace) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event) {
if(event.getPlayer().hasPermission("advancedportals.build") && event.getItemInHand() != null &&
event.getItemInHand().hasItemMeta()){
String name = event.getItemInHand().getItemMeta().getDisplayName();
if(name == null) return;
if (name.equals("\u00A75Portal Block Placer")){
event.getBlockPlaced().setType(Material.PORTAL);
}
else if (name.equals("\u00A78End Portal Block Placer")){
event.getBlockPlaced().setType(Material.ENDER_PORTAL);
}
else if (name.equals("\u00A78Gateway Block Placer")){
event.getBlockPlaced().setType(Material.END_GATEWAY);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockPhysics(BlockPhysicsEvent event) {
Block block = event.getBlock();
Material material = block.getType();
if (material == Material.PORTAL && Portal.inPortalRegion(block.getLocation(), Portal.getPortalProtectionRadius()))
event.setCancelled(true);
}
}

View File

@ -1,75 +0,0 @@
package com.sekwah.advancedportals.listeners;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.PluginMessages;
import com.sekwah.advancedportals.portals.Portal;
import org.bukkit.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.List;
public class PortalProtect implements Listener {
@SuppressWarnings("unused")
private final AdvancedPortalsPlugin plugin;
// The needed config values will be stored so they are easier to access later
// an example is in the interact event in this if statement if((!UseOnlyServerAxe || event.getItem().getItemMeta().getDisplayName().equals("<EFBFBD>eP...
private boolean PortalProtect = true;
private int PortalProtectionRadius = 5;
public PortalProtect(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
this.PortalProtect = config.getConfig().getBoolean("PortalProtection");
if (PortalProtect) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
if (!player.hasPermission("advancedportals.build")
&& Portal.inPortalRegion(event.getBlock().getLocation(), PortalProtectionRadius)) {
event.setCancelled(true);
player.sendMessage(PluginMessages.customPrefixFail + " You don't have permission to build here!");
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
if (!player.hasPermission("advancedportals.build")
&& Portal.inPortalRegion(event.getBlock().getLocation(), PortalProtectionRadius)) {
event.setCancelled(true);
player.sendMessage(PluginMessages.customPrefixFail + " You don't have permission to build here!");
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onExplosion(EntityExplodeEvent event) {
List<Block> blockList = event.blockList();
for (int i = 0; i < blockList.size(); i++) {
Block block = blockList.get(i);
if (Portal.inPortalRegion(block.getLocation(), PortalProtectionRadius)) {
blockList.remove(i);
i--;
}
}
}
}

View File

@ -1,773 +0,0 @@
/*
* Copyright 2011-2013 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.sekwah.advancedportals.metrics;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import java.io.*;
import java.lang.reflect.Method;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public class Metrics {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private static final int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin;
/**
* All of the custom graphs to submit to metrics
*/
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* The scheduled task
*/
private volatile BukkitTask task = null;
public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
/**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned.
*
* @param name The name of the graph
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(final String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
final Graph graph = new Graph(name);
// Now we can add our graph
graphs.add(graph);
// and return back
return graph;
}
/**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
*
* @param graph The name of the graph
*/
public void addGraph(final Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
graphs.add(graph);
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
* ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
*
* @return the File object for the config file
*/
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Gets the online player (backwards compatibility)
*
* @return online player amount
*/
private int getOnlinePlayers() {
try {
Method onlinePlayerMethod = Server.class.getMethod("getOnlinePlayers");
if(onlinePlayerMethod.getReturnType().equals(Collection.class)) {
return ((Collection<?>)onlinePlayerMethod.invoke(Bukkit.getServer())).size();
} else {
return ((Player[])onlinePlayerMethod.invoke(Bukkit.getServer())).length;
}
} catch (Exception ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
}
return 0;
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled
String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion();
int playersOnline = this.getOnlinePlayers();
// END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data
StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
if (graphs.size() > 0) {
synchronized (graphs) {
json.append(',');
json.append('"');
json.append("graphs");
json.append('"');
json.append(':');
json.append('{');
boolean firstGraph = true;
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
Graph graph = iter.next();
StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
json.append(',');
}
json.append(escapeJSON(graph.getName()));
json.append(':');
json.append(graphJson);
firstGraph = false;
}
json.append('}');
}
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
OutputStream os = connection.getOutputStream();
os.write(compressed);
os.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
// close resources
os.close();
reader.close();
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
// Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour")) {
synchronized (graphs) {
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
}
/**
* GZip compress a string of bytes
*
* @param input
* @return
*/
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (Exception e) {
return false;
}
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return
*/
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Represents a custom graph on the website
*/
public static class Graph {
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
*/
private final String name;
/**
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
private Graph(final String name) {
this.name = name;
}
/**
* Gets the graph's name
*
* @return the Graph's name
*/
public String getName() {
return name;
}
/**
* Add a plotter to the graph, which will be used to plot entries
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(final Plotter plotter) {
plotters.add(plotter);
}
/**
* Remove a plotter from the graph
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(final Plotter plotter) {
plotters.remove(plotter);
}
/**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(plotters);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Graph)) {
return false;
}
final Graph graph = (Graph) object;
return graph.name.equals(name);
}
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
}
}
/**
* Interface used to collect custom data for a plugin
*/
public static abstract class Plotter {
/**
* The plot's name
*/
private final String name;
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
this("Default");
}
/**
* Construct a plotter with a specific plot name
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(final String name) {
this.name = name;
}
/**
* Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
* from any thread so care should be taken when accessing resources that need to be synchronized.
*
* @return the current value for the point to be plotted.
*/
public abstract int getValue();
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public String getColumnName() {
return name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {
}
@Override
public int hashCode() {
return getColumnName().hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Plotter)) {
return false;
}
final Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && plotter.getValue() == getValue();
}
}
}

View File

@ -1,109 +0,0 @@
package com.sekwah.advancedportals.portals;
import com.sekwah.advancedportals.api.portaldata.PortalArg;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.HashSet;
public class AdvancedPortal {
private Material trigger = null;
private String worldName = null;
private Location pos1 = null;
private Location pos2 = null;
private String portalName = null;
// TODO store destinations also as variables like portals
private String destiation = null; // Could possibly store the destination name to stop the server having to read the config file
private String bungee = null; // Could possibly store the bungee server name to stop the server having to read the config file
// Bungee will be stored inside the destination.
private PortalArg[] portalArgs = null;
public HashSet<Player> inPortal = new HashSet<Player>();
// TODO think of relaying out the data input to a more logical format.
public AdvancedPortal(String portalName, Material trigger, String destination, Location pos1, Location pos2, PortalArg... portalArgs) {
this(portalName, trigger, pos1, pos2, pos2.getWorld().getName(), portalArgs);
this.destiation = destination;
}
public AdvancedPortal(String portalName, Material trigger, Location pos1, Location pos2, PortalArg... portalArgs) {
this(portalName, trigger, pos1, pos2, pos2.getWorld().getName(), portalArgs);
}
public AdvancedPortal(String portalName, Material trigger, String destination, Location pos1, Location pos2, String worldName, PortalArg... portalArgs) {
this(portalName, trigger, pos1, pos2, worldName, portalArgs);
this.destiation = destination;
}
public AdvancedPortal(String portalName, Material trigger, Location pos1, Location pos2, String worldName, PortalArg... portalArgs) {
this.portalName = portalName;
this.trigger = trigger;
this.pos1 = pos1;
this.pos2 = pos2;
this.worldName = worldName;
this.portalArgs = portalArgs;
}
public String getArg(String arg) {
for (PortalArg portalArg : this.portalArgs) {
if (arg.equals(portalArg.argName)) {
return portalArg.value;
}
}
return null;
}
public PortalArg[] getArgs(){
return this.portalArgs;
}
public boolean hasArg(String arg) {
return this.getArg(arg) != null;
}
public Material getTrigger() {
return this.trigger;
}
public String getWorldName() {
return this.worldName;
}
public Location getPos1() {
return this.pos1;
}
public Location getPos2() {
return this.pos2;
}
public String getName() {
return this.portalName;
}
public String getDestiation() {
return this.destiation;
}
public void setDestiation(String destiation) {
this.destiation = destiation;
}
public String getBungee() {
return this.bungee;
}
public void setBungee(String bungee) {
this.bungee = bungee;
}
}

View File

@ -1,587 +0,0 @@
package com.sekwah.advancedportals.portals;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.sekwah.advancedportals.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.ConfigAccessor;
import com.sekwah.advancedportals.PluginMessages;
import com.sekwah.advancedportals.api.portaldata.PortalArg;
import com.sekwah.advancedportals.destinations.Destination;
import com.sekwah.advancedportals.effects.WarpEffects;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
public class Portal {
public static HashMap<String, Long> cooldown = new HashMap<String, Long>();
// Config values
public static boolean portalsActive = false;
public static AdvancedPortal[] portals = new AdvancedPortal[0];
private static AdvancedPortalsPlugin plugin;
public static ConfigAccessor portalData = new ConfigAccessor(plugin, "portals.yml");
private static boolean showBungeeMessage;
private static int cooldelay;
private static double throwback;
private static Sound portalSound;
private static int portalProtectionRadius;
private static boolean blockSpectatorMode;
public Portal(AdvancedPortalsPlugin plugin) {
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
this.showBungeeMessage = config.getConfig().getBoolean("ShowBungeeWarpMessage", false);
this.cooldelay = config.getConfig().getInt("PortalCooldown", 5);
this.portalProtectionRadius = config.getConfig().getInt("PortalProtectionRadius");
this.throwback = config.getConfig().getDouble("ThrowbackAmount", 0.7);
this.portalSound = WarpEffects.findSound(plugin, "BLOCK_PORTAL_TRAVEL", "PORTAL_TRAVEL");
this.blockSpectatorMode = config.getConfig().getBoolean("BlockSpectatorMode", false);
Portal.plugin = plugin;
Portal.loadPortals();
}
/**
* This can be used to move the get keys to different sections
* <p>
* ConfigurationSection section = portalData.getSection("sectionname");
* <p>
* section.getKeys(false);
*/
public static void loadPortals() {
portalData = new ConfigAccessor(plugin, "portals.yml");
Set<String> PortalSet = portalData.getConfig().getKeys(false);
if (PortalSet.size() > 0) {
portals = new AdvancedPortal[PortalSet.toArray().length];
/*for(int i = 0; i <= PortalSet.toArray().length - 1; i++){
portals[i] = new AdvancedPortal();
}*/
int portalId = 0;
for (Object portal : PortalSet.toArray()) {
ConfigurationSection portalConfigSection = portalData.getConfig().getConfigurationSection(portal.toString());
Material blockType = Material.PORTAL;
String BlockID = portalConfigSection.getString("triggerblock");
try {
Integer.parseInt(BlockID);
plugin.getLogger().info("Block names must be given not IDs");
} catch (NumberFormatException e) {
blockType = Material.getMaterial(BlockID);
}
if (blockType == null) {
blockType = Material.PORTAL;
}
ConfigurationSection portalArgsConf = portalConfigSection.getConfigurationSection("portalArgs");
ArrayList<PortalArg> extraData = new ArrayList<>();
if (portalArgsConf != null) {
Set<String> argsSet = portalArgsConf.getKeys(true);
for (Object argName : argsSet.toArray()) {
if (portalArgsConf.isString(argName.toString())) {
extraData.add(new PortalArg(argName.toString(), portalArgsConf.getString(argName.toString())));
}
}
}
String worldName = portalData.getConfig().getString(portal.toString() + ".world");
if(worldName != null) {
World world = Bukkit.getWorld(worldName);
Location pos1 = new Location(world, portalData.getConfig().getInt(portal.toString() + ".pos1.X"), portalData.getConfig().getInt(portal.toString() + ".pos1.Y"), portalData.getConfig().getInt(portal.toString() + ".pos1.Z"));
Location pos2 = new Location(world, portalData.getConfig().getInt(portal.toString() + ".pos2.X"), portalData.getConfig().getInt(portal.toString() + ".pos2.Y"), portalData.getConfig().getInt(portal.toString() + ".pos2.Z"));
PortalArg[] portalArgs = new PortalArg[extraData.size()];
extraData.toArray(portalArgs);
portals[portalId] = new AdvancedPortal(portal.toString(), blockType, pos1, pos2, worldName, portalArgs);
portals[portalId].setBungee(portalConfigSection.getString("bungee"));
portals[portalId].setDestiation(portalConfigSection.getString("destination"));
portalId++;
}
else{
AdvancedPortal[] tempPortals = portals;
portals = new AdvancedPortal[portals.length - 1];
System.arraycopy(tempPortals, 0, portals, 0, portalId);
}
}
portalsActive = true;
} else {
portalsActive = false;
portals = new AdvancedPortal[0];
}
}
public static String create(Location pos1, Location pos2, String name, String destination, Material triggerBlock, PortalArg... extraData) {
return create(pos1, pos2, name, destination, triggerBlock, null, extraData);
}
public static String create(Location pos1, Location pos2, String name, String destination, Material triggerBlock, String serverName, PortalArg... portalArgs) {
if (!pos1.getWorld().equals(pos2.getWorld())) {
plugin.getLogger().log(Level.WARNING, "pos1 and pos2 must be in the same world!");
return "\u00A7cPortal creation error, pos1 and pos2 must be in the same world!";
}
int LowX = 0;
int LowY = 0;
int LowZ = 0;
int HighX = 0;
int HighY = 0;
int HighZ = 0;
if (pos1.getX() > pos2.getX()) {
LowX = (int) pos2.getX();
HighX = (int) pos1.getX();
} else {
LowX = (int) pos1.getX();
HighX = (int) pos2.getX();
}
if (pos1.getY() > pos2.getY()) {
LowY = (int) pos2.getY();
HighY = (int) pos1.getY();
} else {
LowY = (int) pos1.getY();
HighY = (int) pos2.getY();
}
if (pos1.getZ() > pos2.getZ()) {
LowZ = (int) pos2.getZ();
HighZ = (int) pos1.getZ();
} else {
LowZ = (int) pos1.getZ();
HighZ = (int) pos2.getZ();
}
Location checkpos1 = new Location(pos1.getWorld(), HighX, HighY, HighZ);
Location checkpos2 = new Location(pos2.getWorld(), LowX, LowY, LowZ);
if (checkPortalOverlap(checkpos1, checkpos2)) {
plugin.getLogger().log(Level.WARNING, "portals must not overlap!");
return "\u00A7cPortal creation error, portals must not overlap!";
}
portalData.getConfig().set(name + ".world", pos1.getWorld().getName());
portalData.getConfig().set(name + ".triggerblock", checkMaterial(triggerBlock));
portalData.getConfig().set(name + ".destination", destination);
portalData.getConfig().set(name + ".bungee", serverName);
portalData.getConfig().set(name + ".pos1.X", HighX);
portalData.getConfig().set(name + ".pos1.Y", HighY);
portalData.getConfig().set(name + ".pos1.Z", HighZ);
portalData.getConfig().set(name + ".pos2.X", LowX);
portalData.getConfig().set(name + ".pos2.Y", LowY);
portalData.getConfig().set(name + ".pos2.Z", LowZ);
for (PortalArg arg : portalArgs) {
portalData.getConfig().set(name + ".portalArgs." + arg.argName, arg.value);
}
portalData.saveConfig();
loadPortals();
return "\u00A7aPortal creation successful!";
}
private static boolean checkPortalOverlap(Location pos1, Location pos2) {
if (portalsActive) {
int portalId = 0;
for (@SuppressWarnings("unused") Object portal : Portal.portals) {
if (portals[portalId].getWorldName().equals(pos2.getWorld().getName())) { // checks that the cubes arnt overlapping by seeing if all 4 corners are not in side another
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(), portals[portalId].getPos1().getBlockY(), portals[portalId].getPos1().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(), portals[portalId].getPos1().getBlockY(), portals[portalId].getPos2().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(), portals[portalId].getPos2().getBlockY(), portals[portalId].getPos1().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(), portals[portalId].getPos1().getBlockY(), portals[portalId].getPos1().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(), portals[portalId].getPos2().getBlockY(), portals[portalId].getPos2().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(), portals[portalId].getPos1().getBlockY(), portals[portalId].getPos2().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(), portals[portalId].getPos2().getBlockY(), portals[portalId].getPos2().getBlockZ())) {
return true;
}
if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(), portals[portalId].getPos2().getBlockY(), portals[portalId].getPos1().getBlockZ())) {
return true;
}
}
portalId++;
}
}
return false;
}
private static boolean checkOverLapPortal(Location pos1, Location pos2, int posX, int posY, int posZ) {
if (pos1.getX() >= posX && pos1.getY() >= posX && pos1.getZ() >= posZ) {
if ((pos2.getX()) <= posX && pos2.getY() <= posY && pos2.getZ() <= posZ) {
return true;
}
}
return false;
}
private static String checkMaterial(Material triggerBlock) {
if (triggerBlock.equals(Material.WATER)) {
return "STATIONARY_WATER";
} else if (triggerBlock.equals(Material.LAVA)) {
return "STATIONARY_LAVA";
}
return triggerBlock.toString();
}
@SuppressWarnings("deprecation")
public static String create(Location pos1, Location pos2, String name, String destination, String serverName, PortalArg... extraData) { // add stuff for destination names or coordinates
ConfigAccessor config = new ConfigAccessor(plugin, "config.yml");
Material triggerBlockType;
String BlockID = config.getConfig().getString("DefaultPortalTriggerBlock");
try {
triggerBlockType = Material.getMaterial(Integer.parseInt(BlockID));
} catch (Exception e) {
triggerBlockType = Material.getMaterial(BlockID);
}
if (triggerBlockType == null) {
triggerBlockType = Material.PORTAL;
}
// TODO add a for loop which scans through the addArgs and adds them to the portalData so that the application can use them
String result = create(pos1, pos2, name, destination, triggerBlockType, serverName, extraData);
return result;
}
public static void redefine(Location pos1, Location pos2, String name) {
portalData.getConfig().set(name + ".pos1.X", pos1.getX());
portalData.getConfig().set(name + ".pos1.Y", pos1.getY());
portalData.getConfig().set(name + ".pos1.Z", pos1.getZ());
portalData.getConfig().set(name + ".pos2.X", pos2.getX());
portalData.getConfig().set(name + ".pos2.Y", pos2.getY());
portalData.getConfig().set(name + ".pos2.Z", pos2.getZ());
portalData.saveConfig();
loadPortals();
}
public static String getDestination(String portalName) {
return portalData.getConfig().getString(portalName + ".destination");
}
public static void remove(String name) {
Object[] keys = portalData.getConfig().getKeys(true).toArray();
for (int i = keys.length - 1; i >= 0; i--) {
String key = keys[i].toString();
if (key.startsWith(name + ".")) {
portalData.getConfig().set(key, null);
}
}
portalData.getConfig().set(name, null);
// TODO add code to check if people have the portal selected and notify if removed.
/**Set<String> keys = portalData.getConfig().getKeys(true);
for(String key: keys){
if(key.startsWith(name)){
portalData.getConfig().set(key, null);
}
}*/
/**portalData.getConfig().set(name + ".world", null);
portalData.getConfig().set(name + ".triggerblock", null);
portalData.getConfig().set(name + ".destination", null);
portalData.getConfig().set(name + ".pos1.X", null);
portalData.getConfig().set(name + ".pos1.Y", null);
portalData.getConfig().set(name + ".pos1.Z", null);
portalData.getConfig().set(name + ".pos2.X", null);
portalData.getConfig().set(name + ".pos2.Y", null);
portalData.getConfig().set(name + ".pos2.Z", null);
portalData.getConfig().set(name + ".pos1", null);
portalData.getConfig().set(name + ".getPos2()", null);
portalData.getConfig().set(name, null);*/
portalData.saveConfig();
loadPortals();
}
public static boolean portalExists(String portalName) {
String posX = portalData.getConfig().getString(portalName + ".pos1.X");
return posX != null;
}
public static boolean activate(Player player, String portalName) {
for (AdvancedPortal portal : Portal.portals) {
if (portal.getName().equals(portalName)) return activate(player, portal);
}
plugin.getLogger().log(Level.SEVERE, "Portal not found by name of: " + portalName);
return false;
}
public static boolean activate(Player player, AdvancedPortal portal) {
// add other variables or filter code here, or somehow have a way to register them
// TODO on load and unload recode the permissions to try to register themselves
// https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/plugin/PluginManager.html#addPermission(org.bukkit.permissions.Permission)
// check they havent been registered before too and store a list of ones made by this plugin to remove when portals are unloaded.
// When a portal is added or removed it reloads all portals(i think) so add code for unloading too.
if(blockSpectatorMode && player.getGameMode() == GameMode.SPECTATOR) {
player.sendMessage(PluginMessages.customPrefixFail + "\u00A7c You cannot enter a portal in spectator mode!");
return false;
}
String permission = portal.getArg("permission");
/*if((permission == null || (permission != null && player.hasPermission(permission)) || player.isOp())){*/
// 3 checks, 1st is if it doesnt need perms. 2nd is if it does do they have it. And third is are they op.
if (!(permission == null || (permission != null && player.hasPermission(permission)) || player.isOp())) {
player.sendMessage(PluginMessages.customPrefixFail + "\u00A7c You do not have permission to use this portal!");
failSound(player, portal);
throwPlayerBack(player);
return false;
}
if (cooldown.get(player.getName()) != null) {
int diff = (int) ((System.currentTimeMillis() - cooldown.get(player.getName())) / 1000);
if (diff < cooldelay) {
player.sendMessage(ChatColor.RED + "Please wait " + ChatColor.YELLOW + (cooldelay - diff) + ChatColor.RED + " seconds until attempting to teleport again.");
failSound(player, portal);
throwPlayerBack(player);
return false;
}
}
cooldown.put(player.getName(), System.currentTimeMillis());
boolean showFailMessage = !portal.hasArg("command.1");
//plugin.getLogger().info(portal.getName() + ":" + portal.getDestiation());
boolean warped = false;
if (portal.getBungee() != null) {
if (showBungeeMessage) {
player.sendMessage(PluginMessages.customPrefix + "\u00A7a Attempting to warp to \u00A7e" + portal.getBungee() + "\u00A7a.");
}
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(portal.getBungee());
player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
// Down to bungee to sort out the teleporting but yea theoretically they should warp.
}
else if (portal.getDestiation() != null) {
ConfigAccessor configDesti = new ConfigAccessor(plugin, "destinations.yml");
if (configDesti.getConfig().getString(portal.getDestiation() + ".world") != null) {
warped = Destination.warp(player, portal.getDestiation());
if(!warped){
throwPlayerBack(player);
}
}
} else {
if (showFailMessage) {
player.sendMessage(PluginMessages.customPrefixFail + "\u00A7c The portal you are trying to use doesn't have a destination!");
plugin.getLogger().log(Level.SEVERE, "The portal '" + portal.getName() + "' has just had a warp "
+ "attempt and either the data is corrupt or portal doesn't exist!");
throwPlayerBack(player);
failSound(player, portal);
}
}
if (portal.hasArg("command.1")) {
int commandLine = 1;
String command = portal.getArg("command." + commandLine);//portalData.getConfig().getString(portal.getName()+ ".portalArgs.command." + commandLine);
do {
// (?i) makes the search case insensitive
command = command.replaceAll("@player", player.getName());
plugin.getLogger().log(Level.INFO, "Portal command: " + command);
if (command.startsWith("#") && plugin.getSettings().hasCommandLevel("c")) {
command = command.substring(1);
plugin.getLogger().log(Level.INFO, "Portal command: " + command);
try{
plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
catch(Exception e){
plugin.getLogger().warning("Error while executing: " + command);
}
} else if (command.startsWith("!") && plugin.getSettings().hasCommandLevel("o")) {
command = command.substring(1);
boolean wasOp = player.isOp();
try {
player.setOp(true);
player.chat("/" + command);
//player.performCommand(command);
} finally {
player.setOp(wasOp);
}
} else if (command.startsWith("^")) {
command = command.substring(1);
PermissionAttachment permissionAttachment = null;
try {
permissionAttachment = player.addAttachment(plugin, "*", true);
player.chat("/" + command);
//player.performCommand(command);
} finally {
player.removeAttachment(permissionAttachment);
}
} else {
player.chat("/" + command);
//player.performCommand(command);
}
command = portal.getArg("command." + ++commandLine);
} while (command != null);
}
return warped;
}
private static void failSound(Player player, AdvancedPortal portal) {
if(!(portal.getTrigger() == Material.PORTAL && player.getGameMode() == GameMode.CREATIVE)){
player.playSound(player.getLocation(), portalSound, 0.5f, new Random().nextFloat() * 0.4F + 0.8F);
}
}
public static void rename(String oldName, String newName) {
// set it so it gets all data from one and puts it into another place
ConfigAccessor config = new ConfigAccessor(plugin, "portals.yml");
Set<String> keys = config.getConfig().getKeys(true);
for (String key : keys) {
if (key.startsWith(oldName + ".")) {
if (config.getConfig().getString(key) != null) {
try {
int intData = Integer.parseInt(config.getConfig().getString(key));
config.getConfig().set(key.replace(oldName + ".", newName + "."), intData);
} catch (Exception e) {
config.getConfig().set(key.replace(oldName + ".", newName + "."), config.getConfig().getString(key));
}
}
}
}
config.saveConfig();
remove(oldName);
}
public static boolean addCommand(String portalName, String portalCommand) {
ConfigAccessor config = new ConfigAccessor(plugin, "portals.yml");
if (portalExists(portalName)) {
int commandLine = 0;
while (config.getConfig().getString(portalName + ".portalArgs.command." + ++commandLine) != null); //Loops increasing commandLine till 1 is null
config.getConfig().set(portalName + ".portalArgs.command." + commandLine, portalCommand);
config.saveConfig();
loadPortals();
return true;
} else {
return false;
}
}
public static boolean inPortalTriggerRegion(Location loc) {
for (AdvancedPortal portal : Portal.portals)
if (Portal.locationInPortalTrigger(portal, loc))
return true;
return false;
}
public static boolean locationInPortalTrigger(AdvancedPortal portal, Location loc) {
if (portal.getTrigger().equals(loc.getBlock().getType()))
return locationInPortal(portal, loc, 0);
return false;
}
public static boolean inPortalRegion(Location loc, int additionalArea) {
for (AdvancedPortal portal : Portal.portals)
if (Portal.locationInPortal(portal, loc, additionalArea))
return true;
return false;
}
public static boolean locationInPortal(Location loc, int additionalArea) {
for (AdvancedPortal portal : Portal.portals)
if (Portal.locationInPortal(portal, loc, additionalArea))
return true;
return false;
}
public static boolean locationInPortal(AdvancedPortal portal, Location loc, int additionalArea) {
if (!portalsActive)
return false;
if (loc.getWorld() != null && portal.getWorldName().equals(loc.getWorld().getName()))
if ((portal.getPos1().getX() + 1 + additionalArea) >= loc.getX() && (portal.getPos1().getY() + 1 + additionalArea) > loc.getY() && (portal.getPos1().getZ() + 1 + additionalArea) >= loc.getZ())
if (portal.getPos2().getX() - additionalArea <= loc.getX() && portal.getPos2().getY() - additionalArea <= loc.getY() && portal.getPos2().getZ() - additionalArea <= loc.getZ())
return true;
return false;
}
public static void throwPlayerBack(Player player){
// Not ensured to remove them out of the portal but it makes it feel nicer for the player.
if (throwback > 0) {
Vector velocity = player.getLocation().getDirection();
player.setVelocity(velocity.setY(0).normalize().multiply(-1).setY(throwback));
}
}
public static int getPortalProtectionRadius() {
return portalProtectionRadius;
}
}