3
0
Fork 0

Initial Commit

This commit is contained in:
BuildTools 2021-06-19 19:50:37 +02:00
commit 9ae7e45911
116 changed files with 6876 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
# Project exclude paths
/target/
/.idea/

155
dependency-reduced-pom.xml Normal file
View file

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>nl.iobyte</groupId>
<artifactId>themepark</artifactId>
<version>3.0.0</version>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>com/cryptomorin/xseries/XBlock*</exclude>
<exclude>com/cryptomorin/xseries/XEnchantment*</exclude>
<exclude>com/cryptomorin/xseries/XEntity*</exclude>
<exclude>com/cryptomorin/xseries/XItemStack*</exclude>
<exclude>com/cryptomorin/xseries/XMaterialUtil*</exclude>
<exclude>com/cryptomorin/xseries/XPotion*</exclude>
<exclude>com/cryptomorin/xseries/XSound*</exclude>
<exclude>com/cryptomorin/xseries/XBiome*</exclude>
<exclude>com/cryptomorin/xseries/NMSExtras*</exclude>
<exclude>com/cryptomorin/xseries/NoteBlockMusic*</exclude>
</excludes>
</filter>
</filters>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<repository>
<id>onarandombox</id>
<url>http://repo.onarandombox.com/content/groups/public</url>
</repository>
<repository>
<id>MG-Dev Jenkins CI Maven Repository</id>
<url>https://ci.mg-dev.eu/plugin/repository/everything</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
<exclusion>
<artifactId>json-simple</artifactId>
<groupId>com.googlecode.json-simple</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>annotations</artifactId>
<groupId>org.jetbrains</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.bergerkiller.bukkit</groupId>
<artifactId>TrainCarts</artifactId>
<version>1.16.5-v1</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>LightAPI-fork</artifactId>
<groupId>io.github.qveshn</groupId>
</exclusion>
<exclusion>
<artifactId>SmoothCoastersAPI</artifactId>
<groupId>me.m56738</groupId>
</exclusion>
<exclusion>
<artifactId>cloud-paper</artifactId>
<groupId>org.bergerhealer.cloud.commandframework</groupId>
</exclusion>
<exclusion>
<artifactId>cloud-annotations</artifactId>
<groupId>org.bergerhealer.cloud.commandframework</groupId>
</exclusion>
<exclusion>
<artifactId>cloud-minecraft-extras</artifactId>
<groupId>org.bergerhealer.cloud.commandframework</groupId>
</exclusion>
<exclusion>
<artifactId>commodore</artifactId>
<groupId>me.lucko</groupId>
</exclusion>
<exclusion>
<artifactId>adventure-platform-bukkit</artifactId>
<groupId>net.kyori</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.bergerkiller.bukkit</groupId>
<artifactId>BKCommonLib</artifactId>
<version>1.16.5-v1</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>Mountiplex</artifactId>
<groupId>com.bergerkiller.mountiplex</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

125
pom.xml Normal file
View file

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<groupId>nl.iobyte</groupId>
<artifactId>themepark</artifactId>
<version>3.0.0</version>
<repositories>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<repository>
<id>onarandombox</id>
<url>http://repo.onarandombox.com/content/groups/public</url>
</repository>
<repository>
<id>MG-Dev Jenkins CI Maven Repository</id>
<url>https://ci.mg-dev.eu/plugin/repository/everything</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>nl.iobyte</groupId>
<artifactId>commandapi</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>nl.iobyte</groupId>
<artifactId>menuapi</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.dumptruckman.minecraft</groupId>
<artifactId>JsonConfiguration</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.bergerkiller.bukkit</groupId>
<artifactId>TrainCarts</artifactId>
<version>1.16.5-v1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.bergerkiller.bukkit</groupId>
<artifactId>BKCommonLib</artifactId>
<version>1.16.5-v1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.cryptomorin</groupId>
<artifactId>XSeries</artifactId>
<version>8.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>com/cryptomorin/xseries/XBlock*</exclude>
<exclude>com/cryptomorin/xseries/XEnchantment*</exclude>
<exclude>com/cryptomorin/xseries/XEntity*</exclude>
<exclude>com/cryptomorin/xseries/XItemStack*</exclude>
<exclude>com/cryptomorin/xseries/XMaterialUtil*</exclude>
<exclude>com/cryptomorin/xseries/XPotion*</exclude>
<exclude>com/cryptomorin/xseries/XSound*</exclude>
<exclude>com/cryptomorin/xseries/XBiome*</exclude>
<exclude>com/cryptomorin/xseries/NMSExtras*</exclude>
<exclude>com/cryptomorin/xseries/NoteBlockMusic*</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,75 @@
package nl.iobyte.themepark;
import nl.iobyte.menuapi.MenuAPI;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.commands.ThemeParkCommand;
import nl.iobyte.themepark.listeners.*;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Method;
public class ThemePark extends JavaPlugin {
private static ThemePark instance;
private final ThemeParkAPI api = new ThemeParkAPI();
private boolean disabling = false;
public void onEnable() {
instance = this;
api.enable();
loadCommands();
loadListeners();
loadTrainCarts();
}
private void loadCommands() {
new ThemeParkCommand();
}
private void loadListeners() {
PluginManager pm = Bukkit.getPluginManager();
pm.registerEvents(new PlayerListener(), this);
pm.registerEvents(new RegionListener(), this);
pm.registerEvents(new AttractionListener(), this);
pm.registerEvents(new StatusListener(), this);
pm.registerEvents(new RideCountListener(), this);
pm.registerEvents(new StatusSignListener(), this);
pm.registerEvents(new GeneralListener(), this);
MenuAPI.register(this);
}
private void loadTrainCarts() {
try {
Plugin plugin = Bukkit.getPluginManager().getPlugin("Train_Carts");
if (plugin != null && plugin.isEnabled()) {
Class<?> clazz = Class.forName("com.bergerkiller.bukkit.tc.signactions.SignAction");
Class<?> sign = Class.forName("nl.iobyte.themepark.traincarts.RideCountSign");
Method method = clazz.getMethod("register", clazz);
method.invoke(clazz, sign.newInstance());
}
} catch (Exception e) {
System.out.println("["+getName()+"] Unable to hook into TrainCarts");
}
}
public void onDisable() {
disabling = true;
api.disable();
instance = null;
}
public static ThemePark getInstance() {
return instance;
}
public ThemeParkAPI getAPI() {
return api;
}
public boolean isDisabling() {
return disabling;
}
}

View file

@ -0,0 +1,110 @@
package nl.iobyte.themepark.api;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.AttractionService;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.database.DatabaseService;
import nl.iobyte.themepark.api.event.EventDispatcher;
import nl.iobyte.themepark.api.load.DataLoadService;
import nl.iobyte.themepark.api.menu.MenuService;
import nl.iobyte.themepark.api.ridecount.RideCountService;
import nl.iobyte.themepark.api.sign.SignManager;
public class ThemeParkAPI {
//Data
private ConfigurationManager configurationManager;
private final DataLoadService dataLoadService = new DataLoadService();
private final DatabaseService databaseService = new DatabaseService();
private final MenuService menuService = new MenuService();
private EventDispatcher eventDispatcher;
//Attraction
private final AttractionService attractionService = new AttractionService();
private final RideCountService rideCountService = new RideCountService();
private final SignManager signManager = new SignManager();
/**
* Enable the API
*/
public void enable() {
//Prepare Configuration
configurationManager = new ConfigurationManager(ThemePark.getInstance());
//Load data
eventDispatcher = new EventDispatcher(ThemePark.getInstance());
dataLoadService.init();
}
/**
* Disable the API
*/
public void disable() {
databaseService.stop();
}
/**
* Get the configuration manager
* @return ConfigurationManager
*/
public ConfigurationManager getConfigurationManager() {
return configurationManager;
}
/**
* Get the attraction service
* @return AttractionService
*/
public AttractionService getAttractionService() {
return attractionService;
}
/**
* Get the data load service
* @return DataLoadService
*/
public DataLoadService getDataLoadService() {
return dataLoadService;
}
/**
* Get the menu service
* @return MenuService
*/
public MenuService getMenuService() {
return menuService;
}
/**
* Get the ride count service
* @return RideCountService
*/
public RideCountService getRideCountService() {
return rideCountService;
}
/**
* Get the sign manager
* @return SignManager
*/
public SignManager getSignManager() {
return signManager;
}
/**
* Get the database service
* @return DatabaseService
*/
public DatabaseService getDatabaseService() {
return databaseService;
}
/**
* Get the event dispatcher
* @return EventDispatcher
*/
public EventDispatcher getEventDispatcher() {
return eventDispatcher;
}
}

View file

@ -0,0 +1,190 @@
package nl.iobyte.themepark.api.attraction;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.event.attraction.AttractionCreateEvent;
import nl.iobyte.themepark.api.event.attraction.AttractionRemoveEvent;
import nl.iobyte.themepark.api.event.region.RegionCreateEvent;
import nl.iobyte.themepark.api.event.region.RegionRemoveEvent;
import nl.iobyte.themepark.api.message.Text;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class AttractionService {
private final LinkedHashMap<String, Region> regions = new LinkedHashMap<>();
private final Map<String, Attraction> attractions = new HashMap<>();
/**
* Add Region
* @param region Region
*/
public void addRegion(Region region) {
if(region.getID() == null || region.getID().isEmpty())
return;
if(hasRegion(region.getID()))
return;
regions.put(region.getID(), region);
ThemePark.getInstance().getAPI().getEventDispatcher().call(new RegionCreateEvent(
region
));
}
/**
* Has Region with ID
* @param id String
* @return Boolean
*/
public boolean hasRegion(String id) {
if(id == null || id.isEmpty())
return false;
return regions.containsKey(id);
}
/**
* Get Region by ID
* @param id String
* @return Region
*/
public Region getRegion(String id) {
if(id == null || id.isEmpty())
return null;
return regions.get(id);
}
/**
* Get Map with Regions
* @return LinkedHashMap<String, Region>
*/
public LinkedHashMap<String, Region> getRegions() {
return regions;
}
/**
* Remove Region by ID
* @param id String
* @return Region
*/
public Region removeRegion(String id) {
Region region = regions.remove(id);
if(region == null)
return null;
for(Attraction attraction : region.getAttractions().values())
attractions.remove(attraction.getID());
ThemePark.getInstance().getAPI().getEventDispatcher().call(new RegionRemoveEvent(
region
));
return region;
}
/**
* Add Attraction
* @param attraction Attraction
*/
public void addAttraction(Attraction attraction) {
if(attraction.getID() == null || attraction.getID().isEmpty())
return;
if(hasAttraction(attraction.getID()))
return;
if(!hasRegion(attraction.getRegionID()))
return;
getRegion(attraction.getRegionID()).addAttraction(attraction);
attractions.put(attraction.getID(), attraction);
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionCreateEvent(
attraction
));
}
/**
* Has Attraction with ID
* @param id String
* @return Boolean
*/
public boolean hasAttraction(String id) {
if(id == null || id.isEmpty())
return false;
return attractions.containsKey(id);
}
/**
* Get Attraction by ID
* @param id String
* @return Attraction
*/
public Attraction getAttraction(String id) {
if(id == null || id.isEmpty())
return null;
return attractions.get(id);
}
/**
* Get Attraction by Name
* @param name String
* @return Attraction
*/
public Attraction getAttractionByName(String name) {
if(name == null || name.isEmpty())
return null;
name = Text.strip(name);
for(Attraction attraction : attractions.values())
if(Text.strip(attraction.getName()).equals(name))
return attraction;
return null;
}
public Map<String, Attraction> getAttractionsByStatus(Status status) {
if(status == null)
return null;
Map<String, Attraction> map = new HashMap<>();
for(Map.Entry<String, Attraction> entrySet : attractions.entrySet())
if(entrySet.getValue().getStatus() == status)
map.put(entrySet.getKey(), entrySet.getValue());
return map;
}
/**
* Get Map with Attractions
* @return Map<String, Attraction>
*/
public Map<String, Attraction> getAttractions() {
return attractions;
}
/**
* Remove Attraction by ID
* @param id String
* @return Attraction
*/
public Attraction removeAttraction(String id) {
Attraction attraction = attractions.remove(id);
if(attraction == null)
return null;
getRegion(attraction.getRegionID()).removeAttraction(id);
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionRemoveEvent(
attraction
));
return attraction;
}
}

View file

@ -0,0 +1,187 @@
package nl.iobyte.themepark.api.attraction.enums;
import com.cryptomorin.xseries.XMaterial;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.event.status.*;
import org.bukkit.inventory.ItemStack;
public enum Status {
CONSTRUCTION(1, "&7", "#95a5a6", "Under Contruction", "STAINED_CLAY:1",false),
OPEN(2, "&a", "#4cd137", "Open", "STAINED_CLAY:5", true),
CLOSED(3, "&4", "#e84118", "Closed", "STAINED_CLAY:14", false),
MAINTENANCE(4, "&6", "#f39c12", "Under Maintenance", "STAINED_CLAY:4", false),
MALFUNCTION(5, "&5", "#8e44ad", "Malfunction", "STAINED_CLAY:11", false);
private final int id;
private String color, hex_color, name;
private XMaterial material;
private boolean teleport;
Status(int id, String color, String hex_color, String name, String material, boolean teleport) {
this.id = id;
this.color = color;
this.hex_color = hex_color;
this.name = name;
this.material = XMaterial.matchXMaterial(material).orElse(XMaterial.RED_CONCRETE);
this.teleport = teleport;
}
/**
* Get ID of Status
* @return Integer
*/
public int getID() {
return id;
}
/**
* Get Color of Status
* @return String
*/
public String getColor() {
return color;
}
/**
* Set Color of Status
* @param color String
*/
public void setColor(String color) {
String old = this.color;
this.color = color;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new StatusColorChangeEvent(
this,
old,
color
));
}
/**
* Get HexColor of Status
* @return String
*/
public String getHexColor() {
return hex_color;
}
/**
* Set HexColor of Status
* @param hex_color String
*/
public void setHexColor(String hex_color) {
String old = this.hex_color;
this.hex_color = hex_color;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new StatusHexColorChangeEvent(
this,
old,
hex_color
));
}
/**
* Get Name of Status
* @return String
*/
public String getName() {
return name;
}
/**
* Set Name of Status
* @param name String
*/
public void setName(String name) {
String old = this.name;
this.name = name;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new StatusNameChangeEvent(
this,
old,
name
));
}
/**
* Get XMaterial of Status
* @return XMaterial
*/
public XMaterial getMaterial() {
return material;
}
/**
* Set Material of Status
* @param material Material
*/
public void setMaterial(XMaterial material) {
XMaterial old = this.material;
this.material = material;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new StatusMaterialChangeEvent(
this,
old,
material
));
}
/**
* Get Item of Status
* @return ItemStack
*/
public ItemStack getItem() {
return material.parseItem();
}
/**
* Can Teleport with Status
* @return Boolean
*/
public boolean canTeleport() {
return teleport;
}
/**
* Set if can Teleport with Status
* @param teleport Boolean
*/
public void setCanTeleport(boolean teleport) {
boolean old = this.teleport;
this.teleport = teleport;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new StatusTeleportChangeEvent(
this,
old,
teleport
));
}
/**
* Get Status by name of enum
* @param str String
* @return Status
*/
public static Status get(String str) {
if(str == null || str.isEmpty())
return null;
try {
return Status.valueOf(str.toUpperCase());
} catch (Exception e) {
return null;
}
}
/**
* Get Status by ID
* @param id Integer
* @return String
*/
public static Status get(int id) {
if(id <= 1 || id > values().length)
return null;
for(Status status : values())
if(status.id == id)
return status;
return null;
}
}

View file

@ -0,0 +1,142 @@
package nl.iobyte.themepark.api.attraction.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.event.attraction.*;
import org.bukkit.Location;
public class Attraction {
private final String id;
private String region_id, name,cover;
private Status status;
private transient Location location;
public Attraction(String id, String region_id, String name, String cover, Status status, Location location) {
this.id = id;
this.region_id = region_id;
this.name = name;
this.cover = cover;
this.status = status;
this.location = location;
}
/**
* Get ID of Attraction
* @return String
*/
public String getID() {
return id;
}
/**
* Get RegionID of Attraction
* @return String
*/
public String getRegionID() {
return region_id;
}
/**
* Set RegionID of Attraction
* @param region_id String
*/
public void setRegionID(String region_id) {
String old = this.region_id;
this.region_id = region_id;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionRegionChangeEvent(
this,
old,
region_id
));
}
/**
* Get Name of Attraction
* @return String
*/
public String getName() {
return name;
}
/**
* Set Name of Attraction
* @param name String
*/
public void setName(String name) {
String old = this.name;
this.name = name;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionNameChangeEvent(
this,
old,
name
));
}
/**
* Get Cover of Attraction
* @return String
*/
public String getCover() {
return cover;
}
/**
* Set Cover of Attraction
* @param cover String
*/
public void setCover(String cover) {
String old = this.cover;
this.cover = cover;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionCoverChangeEvent(
this,
old,
cover
));
}
/**
* Get Status of Attraction
* @return Status
*/
public Status getStatus() {
return status;
}
/**
* Set Status of Attraction
* @param status Attraction
*/
public void setStatus(Status status) {
Status old = this.status;
this.status = status;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionStatusChangeEvent(
this,
old,
status
));
}
/**
* Get Location of Attraction
* @return Location
*/
public Location getLocation() {
return location;
}
/**
* Set Location of Attraction
* @param location Attraction
*/
public void setLocation(Location location) {
Location old = this.location;
this.location = location;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new AttractionLocationChangeEvent(
this,
old,
location
));
}
}

View file

@ -0,0 +1,115 @@
package nl.iobyte.themepark.api.attraction.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.config.objects.Configuration;
import nl.iobyte.themepark.api.event.region.RegionNameChangeEvent;
import java.util.LinkedHashMap;
public class Region {
private final String id;
private String name;
private transient final Configuration configuration;
private final LinkedHashMap<String, Attraction> attractions = new LinkedHashMap<>();
public Region(String id, String name) {
this.id = id;
this.name = name;
configuration = new Configuration(ThemePark.getInstance(), "attractions/"+id+".yml", false);
}
/**
* Get ID of Region
* @return String
*/
public String getID() {
return id;
}
/**
* Get Name of Region
* @return String
*/
public String getName() {
return name;
}
/**
* Set Name of Region
* @param name String
*/
public void setName(String name) {
String old = this.name;
this.name = name;
ThemePark.getInstance().getAPI().getEventDispatcher().call(new RegionNameChangeEvent(
this,
old,
name
));
}
/**
* Get Map with Attractions
* @return LinkedHashMap<String, Attraction>
*/
public LinkedHashMap<String, Attraction> getAttractions() {
return attractions;
}
/**
* Get Region Configuration file
* @return Configuration
*/
public Configuration getConfiguration() {
return configuration;
}
/**
* Add Attraction to Region
* @param attraction Attraction
*/
public void addAttraction(Attraction attraction) {
if(attraction.getID() == null || attraction.getID().isEmpty())
return;
if(hasAttraction(attraction.getID()))
return;
attractions.put(attraction.getID(), attraction);
}
/**
* Has Attraction with ID
* @param id String
* @return Attraction
*/
public boolean hasAttraction(String id) {
if(id == null || id.isEmpty())
return false;
return attractions.containsKey(id);
}
/**
* Get Attraction by ID from Region
* @param id String
* @return Attraction
*/
public Attraction getAttraction(String id) {
if(id == null || id.isEmpty())
return null;
return attractions.get(id);
}
/**
* Remove Attraction by ID from Region
* @param id String
* @return Attraction
*/
public Attraction removeAttraction(String id) {
return attractions.remove(id);
}
}

View file

@ -0,0 +1,252 @@
package nl.iobyte.themepark.api.config;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import nl.iobyte.themepark.api.config.objects.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.Plugin;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConfigurationManager {
private final Map<StorageLocation, Configuration> locations = new HashMap<>();
public ConfigurationManager(Plugin plugin) {
for(StorageLocation location : StorageLocation.values())
locations.put(location, new Configuration(plugin, location.getName(), true));
}
/**
* Get configuration instance belonging to a storage location
* @param location StorageLocation
* @return Configuration instance
*/
public Configuration getConfiguration(StorageLocation location) {
if(location == null)
return null;
return locations.get(location);
}
/**
* Save specific storage location
* @param location StorageLocation
*/
public void save(StorageLocation location) {
if(location == null)
return;
getConfiguration(location).save();
}
/**
* Save all storage locations
*/
public void saveAll() {
for(Configuration configuration : locations.values())
configuration.save();
}
/**
* Check if configuration contains storage key
* @param key StorageKey
* @return Boolean
*/
public boolean contains(StorageKey key) {
if(key == null)
return false;
return contains(key.getLocation(), key.getPath());
}
/**
* Check if storage location contains path
* @param location StorageLocation
* @param path String
* @return Boolean
*/
public boolean contains(StorageLocation location, String path) {
if(location == null)
return false;
return getConfiguration(location).contains(path);
}
/**
* Set value to StorageKey
* @param key StorageKey
* @param value Object to set StorageKey to
*/
public void set(StorageKey key, Object value) {
if(key == null)
return;
set(key.getLocation(), key.getPath(), value);
}
/**
* Set value to path in storage location
* @param location StorageLocation
* @param path String
* @param value Object to set path to
*/
public void set(StorageLocation location, String path, Object value) {
if(location == null)
return;
getConfiguration(location).set(path, value);
}
/**
* Get object value of storage key
* @param key StorageKey
* @return Object
*/
public Object get(StorageKey key) {
if(key == null)
return null;
return get(key.getLocation(), key.getPath());
}
/**
* Get object value of path in storage location
* @param location StorageLocation
* @param path Path
* @return Object
*/
public Object get(StorageLocation location, String path) {
if(location == null)
return null;
return getConfiguration(location).get(path);
}
/**
* Get string value of storage key
* @param key StorageKey
* @return String
*/
public String getString(StorageKey key) {
if(key == null)
return null;
return getString(key.getLocation(), key.getPath());
}
/**
* Get string value of path in storage location
* @param location StorageLocation
* @param path Path
* @return String
*/
public String getString(StorageLocation location, String path) {
if(location == null)
return null;
return getConfiguration(location).getString(path);
}
/**
* Get int value of storage key
* @param key StorageKey
* @return int
*/
public int getInt(StorageKey key) {
if(key == null)
return 0;
return getInt(key.getLocation(), key.getPath());
}
/**
* Get int value of path in storage location
* @param location StorageLocation
* @param path Path
* @return int
*/
public int getInt(StorageLocation location, String path) {
if(location == null)
return 0;
return getConfiguration(location).getInt(path);
}
/**
* Get boolean value of storage key
* @param key StorageKey
* @return boolean
*/
public boolean getBoolean(StorageKey key) {
if(key == null)
return false;
return getBoolean(key.getLocation(), key.getPath());
}
/**
* Get boolean value of path in storage location
* @param location StorageLocation
* @param path Path
* @return boolean
*/
public boolean getBoolean(StorageLocation location, String path) {
if(location == null)
return false;
return getConfiguration(location).getBoolean(path);
}
/**
* Get string list value of storage key
* @param key StorageKey
* @return List<String>
*/
public List<String> getStringList(StorageKey key) {
if(key == null)
return null;
return getStringList(key.getLocation(), key.getPath());
}
/**
* Get string list value of path in storage location
* @param location StorageLocation
* @param path Path
* @return List<String>
*/
public List<String> getStringList(StorageLocation location, String path) {
if(location == null)
return null;
return getConfiguration(location).getStringList(path);
}
/**
* Get string list value of storage key
* @param key StorageKey
* @return List<String>
*/
public ConfigurationSection getSection(StorageKey key) {
if(key == null)
return null;
return getSection(key.getLocation(), key.getPath());
}
/**
* Get string list value of path in storage location
* @param location StorageLocation
* @param path Path
* @return List<String>
*/
public ConfigurationSection getSection(StorageLocation location, String path) {
if(location == null)
return null;
return getConfiguration(location).getSection(path);
}
}

View file

@ -0,0 +1,55 @@
package nl.iobyte.themepark.api.config.enums;
public enum StorageKey {
//Database Settings
MYSQL_ENABLED(StorageLocation.SETTINGS, "mysql.enabled"),
MYSQL_URL(StorageLocation.SETTINGS, "mysql.url"),
MYSQL_HOST(StorageLocation.SETTINGS, "mysql.host"),
MYSQL_PORT(StorageLocation.SETTINGS, "mysql.port"),
MYSQL_NAME(StorageLocation.SETTINGS, "mysql.name"),
MYSQL_USERNAME(StorageLocation.SETTINGS, "mysql.username"),
MYSQL_PASSWORD(StorageLocation.SETTINGS, "mysql.password"),
//Menu Settings
MENU_SIZE_MAIN(StorageLocation.MENU, "menu.main.size"),
MENU_TITLE_MAIN(StorageLocation.MENU, "menu.main.title"),
MENU_TITLE_STATUS(StorageLocation.MENU, "menu.status.title"),
//Menu Item
MENU_ITEM_ENABLED(StorageLocation.MENU, "menu.item.enabled"),
MENU_ITEM_MATERIAL(StorageLocation.MENU, "menu.item.material"),
MENU_ITEM_DATA(StorageLocation.MENU, "menu.item.data"),
MENU_ITEM_NAME(StorageLocation.MENU, "menu.item.name"),
MENU_ITEM_SLOT(StorageLocation.MENU, "menu.item.slot"),
MENU_ITEM_CLEAR(StorageLocation.MENU, "menu.item.clear"),
MENU_ITEM_WORLDS(StorageLocation.MENU, "menu.item.worlds"),
//Status Sign
SIGN_STATUS_NAME(StorageLocation.SETTINGS, "sign.status.name"),
SIGN_STATUS_TITLE(StorageLocation.SETTINGS, "sign.status.title");
private final StorageLocation location;
private final String path;
StorageKey(StorageLocation location, String path) {
this.location = location;
this.path = path;
}
/**
* Get storage location key is stored in
* @return StorageLocation
*/
public StorageLocation getLocation() {
return location;
}
/**
* Get path to value
* @return String
*/
public String getPath() {
return path;
}
}

View file

@ -0,0 +1,25 @@
package nl.iobyte.themepark.api.config.enums;
public enum StorageLocation {
SIGN_DATA("sign.yml"),
MESSAGE("message.yml"),
SETTINGS("settings.yml"),
STATUS_SETTINGS("status.yml"),
REGIONS("regions.yml"),
MENU("menu.yml");
private final String name;
StorageLocation(String name) {
this.name = name;
}
/**
* Returns filename of StorageLocation
* @return String
*/
public String getName() {
return name;
}
}

View file

@ -0,0 +1,170 @@
package nl.iobyte.themepark.api.config.objects;
import com.dumptruckman.bukkit.configuration.json.JsonConfiguration;
import nl.iobyte.themepark.logger.ThemeParkLogger;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.util.List;
public class Configuration {
private final Plugin plugin;
private File file;
private FileConfiguration config;
private final String fileName;
public Configuration(Plugin plugin, String fileName, boolean update) {
this.plugin = plugin;
this.fileName = fileName;
load(update);
}
/**
* Load config from file
*/
private void load(boolean update) {
file = new File(plugin.getDataFolder(), fileName);
if(!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
ThemeParkLogger.toConsole("Unable to create parent directories for config file: " + fileName);
return;
}
}
if(!file.exists()) {
if(plugin.getResource(fileName) == null) {
try {
if(!file.createNewFile())
ThemeParkLogger.toConsole("Unable to create config file: " + fileName);
} catch(Exception e) {
ThemeParkLogger.toConsole("Unable to create config file: " + fileName);
return;
}
} else {
plugin.saveResource(fileName, true);
}
}
if(fileName.endsWith(".json")) {
config = JsonConfiguration.loadConfiguration(file);
} else {
config = YamlConfiguration.loadConfiguration(file);
}
if(!update)
return;
new ConfigurationUpdater(this).update();
}
/**
* Get plugin
* @return Plugin
*/
public Plugin getPlugin() {
return plugin;
}
/**
* Get file name of configuration
* @return String
*/
public String getFileName() {
return fileName;
}
/**
* Save config to file
*/
public void save() {
try {
config.save(file);
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* Delete config file
*/
public void delete() {
if(!file.delete())
ThemeParkLogger.toConsole("Unable to remove file: "+fileName);
}
/**
* Check if config contains path
* @param key Path
* @return Boolean
*/
public boolean contains(String key) {
return config.contains(key);
}
/**
* Set config value
* @param key Path to value
* @param value Value
*/
public void set(String key, Object value) {
config.set(key, value);
}
/**
* Get object
* @param key Path to object
* @return Object
*/
public Object get(String key) {
return config.get(key);
}
/**
* Get string
* @param key Path to string
* @return String
*/
public String getString(String key) {
return config.getString(key);
}
/**
* Get integer
* @param key Path to integer
* @return Integer
*/
public int getInt(String key) {
return config.getInt(key);
}
/**
* Get boolean
* @param key Path to boolean
* @return Boolean
*/
public boolean getBoolean(String key) {
return config.getBoolean(key);
}
/**
* Get List of strings
* @param key Path to list
* @return List of strings
*/
public List<String> getStringList(String key) {
return config.getStringList(key);
}
/**
* Get section of config
* @param key Path to section
* @return Section of config
*/
public ConfigurationSection getSection(String key) {
return config.getConfigurationSection(key);
}
}

View file

@ -0,0 +1,77 @@
package nl.iobyte.themepark.api.config.objects;
import nl.iobyte.themepark.utils.VersionComparator;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class ConfigurationUpdater {
private final Configuration config;
public ConfigurationUpdater(Configuration config) {
this.config = config;
}
public String getCurrentVersion() {
if(!config.contains("version"))
return "1.0";
return config.getString("version");
}
public void update() {
if(config.getFileName().endsWith(".json")) {
return;
}
InputStream resource = config.getPlugin().getResource(config.getFileName());
if(resource == null)
return;
FileConfiguration data;
try(InputStreamReader reader = new InputStreamReader(resource, StandardCharsets.UTF_8)) {
data = YamlConfiguration.loadConfiguration(reader);
} catch (Exception e) {
e.printStackTrace();
return;
}
String saved_version = "1.0";
if(data.contains("version"))
saved_version = data.getString("version");
VersionComparator comparator = new VersionComparator();
int i = comparator.compare(saved_version, getCurrentVersion());
if(i <= 0)
return;
insertChanges(data.getConfigurationSection(""), "");
config.set("version", saved_version);
config.save();
}
private void insertChanges(ConfigurationSection section, String root) {
if(section == null || section.getKeys(false).isEmpty())
return;
String path;
for(String str : section.getKeys(false)) {
path = root.equals("") ? str : root + "." + str;
ConfigurationSection s = section.getConfigurationSection(str);
if(s != null) {
insertChanges(s, path);
continue;
}
if(config.contains(path))
continue;
config.set(path, section.get(str));
}
}
}

View file

@ -0,0 +1,94 @@
package nl.iobyte.themepark.api.database;
import nl.iobyte.themepark.api.database.objects.Database;
import nl.iobyte.themepark.api.database.objects.types.NullDatabase;
import nl.iobyte.themepark.scheduler.Task;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DatabaseService {
private final Map<String, Database> databases = new HashMap<>();
/**
* Add Database to DatabaseService
* @param id String
* @param database Database
*/
public void addDatabase(String id, Database database) {
if(id == null || id.isEmpty() || database == null)
return;
if(databases.containsKey(id))
return;
databases.put(id, database);
}
/**
* Get Database
* @param id String
* @return Database
*/
public Database getDatabase(String id) {
if(id == null || id.isEmpty())
return new NullDatabase();
return databases.getOrDefault(id, new NullDatabase());
}
public Task<Boolean> executeAsync(String id, String query, Map<Integer, Object> objects) {
return getDatabase(id).executeAsync(query, objects);
}
public boolean execute(String id, String query, Map<Integer, Object> objects) {
return getDatabase(id).execute(query, objects);
}
public Task<Integer> executeUpdateAsync(String id, String query, Map<Integer, Object> objects) {
return getDatabase(id).executeUpdateAsync(query, objects);
}
public int executeUpdate(String id, String query, Map<Integer, Object> objects) {
return getDatabase(id).executeUpdate(query, objects);
}
public Task<ArrayList<Map<String, Object>>> executeQueryAsync(String id, String query, Map<Integer, Object> objects) {
return getDatabase(id).executeQueryAsync(query, objects);
}
public ArrayList<Map<String, Object>> executeQuery(String id, String query, Map<Integer, Object> objects) {
return getDatabase(id).executeQuery(query, objects);
}
/**
* Check if Database exists
* @param id String
* @return Boolean
*/
public boolean hasDatabase(String id) {
if(id == null || id.isEmpty())
return false;
return databases.containsKey(id);
}
/**
* Remove Database
* @param id String
*/
public void removeDatabase(String id) {
Database db = databases.remove(id);
if(db == null)
return;
db.closeConnection();
}
public void stop() {
for(Database database : databases.values())
database.closeConnection();
}
}

View file

@ -0,0 +1,122 @@
package nl.iobyte.themepark.api.database.objects;
import nl.iobyte.themepark.scheduler.ThemeParkScheduler;
import nl.iobyte.themepark.scheduler.Task;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public abstract class Database {
public abstract Connection getConnection() throws SQLException;
public abstract void closeConnection();
public Task<Boolean> executeAsync(String query, Map<Integer, Object> objects) {
Task<Boolean> task = new Task<>();
ThemeParkScheduler.runAsync(() -> task.success(execute(
query,
objects
)));
return task;
}
public boolean execute(String query, Map<Integer, Object> objects) {
if(query == null || query.isEmpty())
return false;
boolean b = false;
try(Connection conn = getConnection()) {
PreparedStatement statement = conn.prepareStatement(query);
statement.closeOnCompletion();
if(objects != null)
for(Map.Entry<Integer, Object> entry : objects.entrySet())
statement.setObject(entry.getKey(), entry.getValue());
b = statement.execute();
} catch(Exception e) {
System.out.println("Query: "+query);
System.out.println("Map: "+objects);
e.printStackTrace();
}
return b;
}
public Task<Integer> executeUpdateAsync(String query, Map<Integer, Object> objects) {
Task<Integer> task = new Task<>();
ThemeParkScheduler.runAsync(() -> task.success(executeUpdate(
query,
objects
)));
return task;
}
public int executeUpdate(String query, Map<Integer, Object> objects) {
if (query == null || query.isEmpty())
return 0;
int i = 0;
try(Connection conn = getConnection()) {
PreparedStatement statement = conn.prepareStatement(query);
statement.closeOnCompletion();
for (Map.Entry<Integer, Object> entry : objects.entrySet())
statement.setObject(entry.getKey(), entry.getValue());
i = statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return i;
}
public Task<ArrayList<Map<String, Object>>> executeQueryAsync(String query, Map<Integer, Object> objects) {
Task<ArrayList<Map<String, Object>>> task = new Task<>();
ThemeParkScheduler.runAsync(() -> task.success(executeQuery(
query,
objects
)));
return task;
}
public ArrayList<Map<String, Object>> executeQuery(String query, Map<Integer, Object> objects) {
if (query == null || query.isEmpty())
return null;
ArrayList<Map<String, Object>> set = null;
try(Connection conn = getConnection()) {
PreparedStatement statement = conn.prepareStatement(query);
statement.closeOnCompletion();
if (objects != null)
for (Map.Entry<Integer, Object> entry : objects.entrySet())
statement.setObject(entry.getKey(), entry.getValue());
set = new ArrayList<>();
ResultSet result = statement.executeQuery();
ResultSetMetaData metadata = result.getMetaData();
int columnCount = metadata.getColumnCount();
while(result.next()) {
Map<String, Object> map = new HashMap<>();
for(int i = 1; i <= columnCount; i++)
map.put(metadata.getColumnName(i), result.getObject(i));
set.add(map);
}
result.close();
} catch (Exception e) {
e.printStackTrace();
}
return set;
}
}

View file

@ -0,0 +1,47 @@
package nl.iobyte.themepark.api.database.objects.types;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.database.objects.Database;
import nl.iobyte.themepark.logger.ThemeParkLogger;
import java.sql.Connection;
import java.sql.SQLException;
public class MySQLDatabase extends Database {
private final String dbName;
private final HikariDataSource source;
public MySQLDatabase(String url, String host, int port, String dbName, String username, String password) {
if(url == null || url.isEmpty())
url = "jdbc:mysql://%host%:%port%/%database%?useSSL=false";
this.dbName = dbName;
HikariConfig config = new HikariConfig();
config.setPoolName(ThemePark.getInstance().getName());
config.setUsername(username);
config.setPassword(password);
config.setDriverClassName("com.mysql.jdbc.Driver");
config.setMaximumPoolSize(5);
config.setJdbcUrl(url.replace("%host%", host).replace("%port%", String.valueOf(port)).replace("%database%", dbName));
source = new HikariDataSource(config);
}
/**
* Get Connection
* @return Connection
*/
public Connection getConnection() throws SQLException {
return source.getConnection();
}
/**
* Close connection
*/
public void closeConnection() {
ThemeParkLogger.toConsole("Closing the database connection for " + dbName);
source.close();
}
}

View file

@ -0,0 +1,28 @@
package nl.iobyte.themepark.api.database.objects.types;
import nl.iobyte.themepark.api.database.objects.Database;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Map;
public class NullDatabase extends Database {
public Connection getConnection() {
return null;
}
public void closeConnection() {}
public boolean execute(String query, Map<Integer, Object> objects) {
return false;
}
public int executeUpdate(String query, Map<Integer, Object> objects) {
return 0;
}
public ArrayList<Map<String, Object>> executeQuery(String query, Map<Integer, Object> objects) {
return new ArrayList<>();
}
}

View file

@ -0,0 +1,95 @@
package nl.iobyte.themepark.api.database.objects.types;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.database.objects.Database;
import nl.iobyte.themepark.logger.ThemeParkLogger;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class SQLiteDatabase extends Database {
private final String dbName;
private String v;
private HikariDataSource source;
public SQLiteDatabase(String dbName) {
this.dbName = dbName;
File dbFile = new File(ThemePark.getInstance().getDataFolder(), dbName + ".db");
if (!dbFile.exists()) {
try {
ThemeParkLogger.toConsole("Generating the " + dbName + ".db!");
if (!dbFile.createNewFile()) {
ThemeParkLogger.toConsole("Couldn't generate the " + dbName + ".db!");
return;
}
} catch (IOException e) {
ThemeParkLogger.toConsole("Couldn't generate the " + dbName + ".db!");
return;
}
}
HikariConfig config = new HikariConfig();
config.setPoolName(ThemePark.getInstance().getName());
config.setUsername(null);
config.setPassword(null);
config.setDriverClassName("org.sqlite.JDBC");
config.setConnectionTestQuery("SELECT 1");
config.setMaximumPoolSize(5);
Properties prop = new Properties();
prop.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss");
config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath());
config.setDataSourceProperties(prop);
source = new HikariDataSource(config);
try(Connection conn = getConnection()) {
PreparedStatement statement = conn.prepareStatement("SELECT sqlite_version() AS version");
statement.closeOnCompletion();
ResultSet set = statement.executeQuery();
while(set.next()) {
v = set.getString("version");
}
set.close();
} catch(Exception e) {
e.printStackTrace();
}
if(v == null) {
System.out.println("Unable to get SQLite version.");
} else {
System.out.println("SQLite database running on version: "+v);
}
}
public String getVersion() {
return v;
}
/**
* Get Database Connection
* @return Connection
*/
public Connection getConnection() throws SQLException {
return source.getConnection();
}
/**
* Close Connection
*/
public void closeConnection() {
ThemeParkLogger.toConsole("Closing the database connection for " + dbName + ".db!");
source.close();
}
}

View file

@ -0,0 +1,44 @@
package nl.iobyte.themepark.api.event;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
public class EventDispatcher {
private final Plugin plugin;
public EventDispatcher(Plugin plugin) {
this.plugin = plugin;
}
/**
* Dispatch Event without Callback
* @param event Event
*/
public void call(Event event) {
call(event, null);
}
/**
* Dispatch Event with Callback
* @param event Event
* @param callback Runnable
*/
public void call(Event event, Runnable callback) {
PluginManager pm = Bukkit.getPluginManager();
if(Bukkit.isPrimaryThread()) {
pm.callEvent(event);
if(callback != null)
callback.run();
} else {
Bukkit.getScheduler().runTask(plugin, () -> {
pm.callEvent(event);
if(callback != null)
Bukkit.getScheduler().runTaskAsynchronously(plugin, callback);
});
}
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionCoverChangeEvent extends AttractionEvent<String> {
public AttractionCoverChangeEvent(Attraction attraction, String old, String current) {
super(attraction, old, current);
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionCreateEvent extends AttractionEvent<Object> {
public AttractionCreateEvent(Attraction attraction) {
super(attraction, null, null);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionDescriptionChangeEvent extends AttractionEvent<String> {
public AttractionDescriptionChangeEvent(Attraction attraction, String old, String current) {
super(attraction, old, current);
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
import org.bukkit.Location;
public class AttractionLocationChangeEvent extends AttractionEvent<Location> {
public AttractionLocationChangeEvent(Attraction attraction, Location old, Location current) {
super(attraction, old, current);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionNameChangeEvent extends AttractionEvent<String> {
public AttractionNameChangeEvent(Attraction attraction, String old, String current) {
super(attraction, old, current);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionRegionChangeEvent extends AttractionEvent<String> {
public AttractionRegionChangeEvent(Attraction attraction, String old, String current) {
super(attraction, old, current);
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionRemoveEvent extends AttractionEvent<Object> {
public AttractionRemoveEvent(Attraction attraction) {
super(attraction, null, null);
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.attraction;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
public class AttractionStatusChangeEvent extends AttractionEvent<Status> {
public AttractionStatusChangeEvent(Attraction attraction, Status old, Status current) {
super(attraction, old, current);
}
}

View file

@ -0,0 +1,18 @@
package nl.iobyte.themepark.api.event.objects;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
public class AttractionEvent<T> extends ChangeEvent<T> {
private final Attraction attraction;
public AttractionEvent(Attraction attraction, T old, T current) {
super(old, current);
this.attraction = attraction;
}
public Attraction getAttraction() {
return attraction;
}
}

View file

@ -0,0 +1,32 @@
package nl.iobyte.themepark.api.event.objects;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class ChangeEvent<T> extends Event {
private static final HandlerList handlers = new HandlerList();
private final T old, current;
public ChangeEvent(T old, T current) {
this.old = old;
this.current = current;
}
public T getOld() {
return old;
}
public T getCurrent() {
return current;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View file

@ -0,0 +1,18 @@
package nl.iobyte.themepark.api.event.objects;
import nl.iobyte.themepark.api.attraction.objects.Region;
public class RegionEvent<T> extends ChangeEvent<T> {
private final Region region;
public RegionEvent(Region region, T old, T current) {
super(old, current);
this.region = region;
}
public Region getRegion() {
return region;
}
}

View file

@ -0,0 +1,18 @@
package nl.iobyte.themepark.api.event.objects;
import nl.iobyte.themepark.api.attraction.enums.Status;
public class StatusEvent<T> extends ChangeEvent<T> {
private final Status status;
public StatusEvent(Status status, T old, T current) {
super(old, current);
this.status = status;
}
public Status getStatus() {
return status;
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.region;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.event.objects.RegionEvent;
public class RegionCreateEvent extends RegionEvent<Object> {
public RegionCreateEvent(Region region) {
super(region, null, null);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.region;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.event.objects.RegionEvent;
public class RegionNameChangeEvent extends RegionEvent<String> {
public RegionNameChangeEvent(Region region, String old, String current) {
super(region, old, current);
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.region;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.event.objects.RegionEvent;
public class RegionRemoveEvent extends RegionEvent<Object> {
public RegionRemoveEvent(Region region) {
super(region, null, null);
}
}

View file

@ -0,0 +1,19 @@
package nl.iobyte.themepark.api.event.ridecount;
import nl.iobyte.themepark.api.event.objects.ChangeEvent;
import nl.iobyte.themepark.api.ridecount.objects.RideCount;
public class RideCountAddEvent extends ChangeEvent<Integer> {
private final RideCount count;
public RideCountAddEvent(RideCount count, int old, int current) {
super(old, current);
this.count = count;
}
public RideCount getRideCount() {
return count;
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.status;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.event.objects.StatusEvent;
public class StatusColorChangeEvent extends StatusEvent<String> {
public StatusColorChangeEvent(Status status, String old, String current) {
super(status, old, current);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.status;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.event.objects.StatusEvent;
public class StatusHexColorChangeEvent extends StatusEvent<String> {
public StatusHexColorChangeEvent(Status status, String old, String current) {
super(status, old, current);
}
}

View file

@ -0,0 +1,13 @@
package nl.iobyte.themepark.api.event.status;
import com.cryptomorin.xseries.XMaterial;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.event.objects.StatusEvent;
public class StatusMaterialChangeEvent extends StatusEvent<XMaterial> {
public StatusMaterialChangeEvent(Status status, XMaterial old, XMaterial current) {
super(status, old, current);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.status;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.event.objects.StatusEvent;
public class StatusNameChangeEvent extends StatusEvent<String> {
public StatusNameChangeEvent(Status status, String old, String current) {
super(status, old, current);
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.api.event.status;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.event.objects.StatusEvent;
public class StatusTeleportChangeEvent extends StatusEvent<Boolean> {
public StatusTeleportChangeEvent(Status status, boolean old, boolean current) {
super(status, old, current);
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.api.load;
import nl.iobyte.themepark.api.load.interfaces.IDataLoader;
import nl.iobyte.themepark.api.load.objects.*;
import java.util.ArrayList;
import java.util.List;
public class DataLoadService {
private final List<IDataLoader> loaders = new ArrayList<>();
public DataLoadService() {
addLoader(new DatabaseLoader());
addLoader(new StatusDataLoader());
addLoader(new SignDataLoader());
addLoader(new MenuDataLoader());
}
/**
* Add IDataLoader
* @param dataLoader IDataLoader
*/
public void addLoader(IDataLoader dataLoader) {
loaders.add(dataLoader);
}
/**
* Call all IDataLoaders
*/
public void init() {
for(IDataLoader loader : loaders)
loader.load();
}
}

View file

@ -0,0 +1,10 @@
package nl.iobyte.themepark.api.load.interfaces;
public interface IDataLoader {
/**
* Called when loading data
*/
void load();
}

View file

@ -0,0 +1,68 @@
package nl.iobyte.themepark.api.load.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.database.DatabaseService;
import nl.iobyte.themepark.api.database.objects.types.MySQLDatabase;
import nl.iobyte.themepark.api.database.objects.types.SQLiteDatabase;
import nl.iobyte.themepark.api.load.interfaces.IDataLoader;
public class DatabaseLoader implements IDataLoader {
public void load() {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
DatabaseService service = api.getDatabaseService();
ConfigurationManager manager = api.getConfigurationManager();
//Add SQLite Database
service.addDatabase(
"local",
new SQLiteDatabase("sqlite")
);
if(manager.getBoolean(StorageKey.MYSQL_ENABLED))
service.addDatabase(
"remote",
new MySQLDatabase(
manager.getString(StorageKey.MYSQL_URL),
manager.getString(StorageKey.MYSQL_HOST),
manager.getInt(StorageKey.MYSQL_PORT),
manager.getString(StorageKey.MYSQL_NAME),
manager.getString(StorageKey.MYSQL_USERNAME),
manager.getString(StorageKey.MYSQL_PASSWORD)
)
);
//Create Database tables
loadTables(service);
}
private void loadTables(DatabaseService service) {
//Create SQLite Tables
service.execute(
"local",
"CREATE TABLE IF NOT EXISTS counts(uuid VARCHAR(255) NOT NULL, attraction_id VARCHAR(255) NOT NULL, year SMALLINT(2), month SMALLINT(2), week SMALLINT(2), day SMALLINT(2), count SMALLINT(2), UNIQUE(uuid, attraction_id, year, day))",
null
);
//Create MySQL Tables
service.execute(
"remote",
"CREATE TABLE IF NOT EXISTS regions(id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id))",
null
);
service.execute(
"remote",
"CREATE TABLE IF NOT EXISTS attractions(id VARCHAR(255) NOT NULL, region_id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, cover VARCHAR(255) NOT NULL, status_id INT(11), PRIMARY KEY(id))",
null
);
service.execute(
"remote",
"CREATE TABLE IF NOT EXISTS states(id INT(11), name VARCHAR(255) NOT NULL, color VARCHAR(7) NOT NULL, PRIMARY KEY(id))",
null
);
}
}

View file

@ -0,0 +1,18 @@
package nl.iobyte.themepark.api.load.objects;
import nl.iobyte.menuapi.MenuAPI;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.load.interfaces.IDataLoader;
import nl.iobyte.themepark.api.menu.objects.handlers.StatusMenuHandler;
public class MenuDataLoader implements IDataLoader {
public void load() {
//Register default IActionHandlers
MenuAPI.addActionHandler(new StatusMenuHandler());
//Load Menu's
ThemePark.getInstance().getAPI().getMenuService().init();
}
}

View file

@ -0,0 +1,50 @@
package nl.iobyte.themepark.api.load.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import nl.iobyte.themepark.api.load.interfaces.IDataLoader;
import nl.iobyte.themepark.api.sign.objects.StatusSign;
import nl.iobyte.themepark.utils.LocationUtil;
import org.bukkit.Location;
import org.bukkit.block.Sign;
import java.util.List;
public class SignDataLoader implements IDataLoader {
/**
* Called when loading data
*/
public void load() {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
ConfigurationManager manager = api.getConfigurationManager();
for(Attraction attraction : api.getAttractionService().getAttractions().values()) {
if(attraction == null) {
return;
}
if(!manager.contains(StorageLocation.SIGN_DATA, "signs." + attraction.getID())) {
return;
}
List<String> locations = manager.getStringList(StorageLocation.SIGN_DATA, "signs." + attraction.getID());
for(String string : locations) {
Location location = LocationUtil.fromString(string);
if(location == null) {
continue;
}
if(!(location.getBlock().getState() instanceof Sign)) {
continue;
}
api.getSignManager().addSign(new StatusSign(attraction, location));
}
}
}
}

View file

@ -0,0 +1,191 @@
package nl.iobyte.themepark.api.load.objects;
import com.cryptomorin.xseries.XMaterial;
import com.google.common.base.Strings;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.attraction.AttractionService;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.config.objects.Configuration;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import nl.iobyte.themepark.api.database.objects.Database;
import nl.iobyte.themepark.api.load.interfaces.IDataLoader;
import nl.iobyte.themepark.utils.LocationUtil;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import java.util.HashMap;
import java.util.Map;
public class StatusDataLoader implements IDataLoader {
/**
* Called when loading data
*/
public void load() {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
ConfigurationManager manager = api.getConfigurationManager();
//Load data
loadStatus(manager);
loadRegions(api, manager);
//Insert into Database
prepareDatabase(api);
}
private void loadStatus(ConfigurationManager manager) {
if(!manager.contains(StorageLocation.STATUS_SETTINGS, "states"))
return;
ConfigurationSection section = manager.getSection(StorageLocation.STATUS_SETTINGS, "states");
if(section.getKeys(false).isEmpty())
return;
Status status;
String path;
for(String id : section.getKeys(false)) {
status = Status.get(id);
if(status == null)
continue;
path = "states."+id;
if(manager.contains(StorageLocation.STATUS_SETTINGS, path+".name"))
status.setName(manager.getString(StorageLocation.STATUS_SETTINGS, path+".name"));
if(manager.contains(StorageLocation.STATUS_SETTINGS, path+".color"))
status.setColor(manager.getString(StorageLocation.STATUS_SETTINGS, path+".color"));
if(manager.contains(StorageLocation.STATUS_SETTINGS, path+".hex_color"))
status.setHexColor(manager.getString(StorageLocation.STATUS_SETTINGS, path+".hex_color"));
if(manager.contains(StorageLocation.STATUS_SETTINGS, path+".teleport"))
status.setCanTeleport(manager.getBoolean(StorageLocation.STATUS_SETTINGS, path+".teleport"));
XMaterial material = null;
if(manager.contains(StorageLocation.STATUS_SETTINGS, path+".material"))
material = XMaterial.matchXMaterial(manager.getString(StorageLocation.STATUS_SETTINGS, path + ".material")).orElse(XMaterial.RED_CONCRETE);
if(material == null)
continue;
status.setMaterial(material);
}
}
/**
* Load Regions from config
* @param api ThemeParkAPI
* @param manager ConfigurationManager
*/
private void loadRegions(ThemeParkAPI api, ConfigurationManager manager) {
//See if any regions exist
AttractionService attractionService = api.getAttractionService();
if(!manager.contains(StorageLocation.REGIONS, "regions"))
return;
ConfigurationSection section = manager.getSection(StorageLocation.REGIONS, "regions");
if(section.getKeys(false).isEmpty())
return;
//Load regions
for(String id : section.getKeys(false)) {
String name = manager.getString(StorageLocation.REGIONS, "regions."+id+".name");
Region region = new Region(id, name);
attractionService.addRegion(region);
loadAttractions(api, region); //try loading Attractions for Region
}
}
/**
* Load Attractions for specific Region
* @param api ThemeParkAPI
* @param region Region
*/
private void loadAttractions(ThemeParkAPI api, Region region) {
//See if any attractions exist
Configuration config = region.getConfiguration();
if(!config.contains("attractions"))
return;
ConfigurationSection section = config.getSection("attractions");
if(section.getKeys(false).isEmpty())
return;
//Load Attractions
for(String id : section.getKeys(false)) {
String name = config.getString("attractions."+id+".name");
String cover = config.getString("attractions."+id+".cover");
Status status = Status.get(config.getString("attractions."+id+".status"));
Location location = LocationUtil.fromString(config.getString("attractions."+id+".location"));
Attraction attraction = new Attraction(id, region.getID(), name, cover, status, location);
api.getAttractionService().addAttraction(attraction);
}
}
private void prepareDatabase(ThemeParkAPI api) {
AttractionService service = api.getAttractionService();
Database db = api.getDatabaseService().getDatabase("remote");
//Variables
int size;
Map<Integer, Object> parameters = new HashMap<>();
//Prepare Status Query Parameters
for(Status status : Status.values()) {
size = parameters.size();
parameters.put(size + 1, status.getID());
parameters.put(size + 2, status.getName());
parameters.put(size + 3, status.getHexColor());
}
//Execute Status Query
db.executeAsync(
"INSERT IGNORE INTO states(id, name, color) VALUES "+ Strings.repeat("(?,?,?),", Status.values().length - 1)+"(?,?,?)",
new HashMap<>(parameters)
);
//Prepare Region Query Parameters
parameters.clear();
for(Region region : service.getRegions().values()) {
size = parameters.size();
parameters.put(size + 1, region.getID());
parameters.put(size + 2, region.getName());
}
if(parameters.isEmpty())
return;
//Execute Region Query
db.executeAsync(
"INSERT IGNORE INTO regions(id, name) VALUES "+ Strings.repeat("(?,?),", service.getRegions().values().size() - 1)+"(?,?)",
new HashMap<>(parameters)
);
//Prepare Attraction Query Parameters
parameters.clear();
for(Attraction attraction : service.getAttractions().values()) {
size = parameters.size();
parameters.put(size + 1, attraction.getID());
parameters.put(size + 2, attraction.getRegionID());
parameters.put(size + 3, attraction.getName());
parameters.put(size + 4, attraction.getCover());
parameters.put(size + 5, attraction.getStatus().getID());
}
if(parameters.isEmpty())
return;
//Execute Region Query
db.executeAsync(
"INSERT IGNORE INTO attractions(id, region_id, name, cover, status_id) VALUES "+ Strings.repeat("(?,?,?,?,?),", service.getAttractions().values().size() - 1)+"(?,?,?,?,?)",
parameters
);
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.api.menu;
import nl.iobyte.themepark.api.menu.objects.MainMenu;
import nl.iobyte.themepark.api.menu.objects.StatusMenu;
public class MenuService {
private final MainMenu mainMenu = new MainMenu();
private final StatusMenu statusMenu = new StatusMenu();
/**
* Load all menu's
*/
public void init() {
mainMenu.load();
statusMenu.load();
}
/**
* Get main menu
* @return MainMenu
*/
public MainMenu getMainMenu() {
return mainMenu;
}
/**
* Get status menu
* @return StatusMenu
*/
public StatusMenu getStatusMenu() {
return statusMenu;
}
}

View file

@ -0,0 +1,129 @@
package nl.iobyte.themepark.api.menu.objects;
import nl.iobyte.menuapi.MenuAPI;
import nl.iobyte.menuapi.action.HandlerAction;
import nl.iobyte.menuapi.basic.Menu;
import nl.iobyte.menuapi.interfaces.IActionHandler;
import nl.iobyte.menuapi.item.ItemBuilder;
import nl.iobyte.menuapi.item.MenuItem;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import nl.iobyte.themepark.api.menu.objects.handlers.CommandMenuHandler;
import nl.iobyte.themepark.api.menu.objects.handlers.JsonMessageMenuHandler;
import nl.iobyte.themepark.api.menu.objects.handlers.PlainMessageMenuHandler;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
public class MainMenu {
private Menu menu;
public void load() {
ConfigurationManager manager = ThemePark.getInstance().getAPI().getConfigurationManager();
//Prepare Menu
menu = new Menu(manager.getString(StorageKey.MENU_TITLE_MAIN), manager.getInt(StorageKey.MENU_SIZE_MAIN));
//Load Items
loadItems(manager);
//Build Menu
menu.build();
}
private void loadItems(ConfigurationManager manager) {
//See if any items exist
if(!manager.contains(StorageLocation.MENU, "items"))
return;
ConfigurationSection section = manager.getSection(StorageLocation.MENU, "items");
if(section.getKeys(false).isEmpty())
return;
//Load items
String path;
ItemBuilder builder;
MenuItem item;
IActionHandler handler;
for(String id : section.getKeys(false)) {
path = "items."+id;
int slot = manager.getInt(StorageLocation.MENU, path+".slot");
if(slot < 0 || slot >= menu.getSize())
continue;
String name = manager.getString(StorageLocation.MENU, path+".name");
if(name == null || name.equals(""))
name = " ";
Material material = Material.getMaterial(manager.getString(StorageLocation.MENU, path+".material"));
if(material == null)
continue;
int amount = manager.getInt(StorageLocation.MENU, path+".amount");
if(amount < 1)
amount = 1;
short data = Short.parseShort(manager.getString(StorageLocation.MENU, path+".data"));
if(data < 0)
continue;
builder = new ItemBuilder(material, amount, data);
builder.setName(name);
String lore = manager.getString(StorageLocation.MENU, path+".lore");
if(lore == null || lore.equals("")) {
builder.setLore(manager.getStringList(StorageLocation.MENU, path+".lore"));
} else {
builder.setLore(lore);
}
item = new MenuItem(
builder.getItem(),
true
);
handler = getHandler(manager, path);
if(handler != null) {
item.addActions(handler);
} else {
item.addActions(new HandlerAction(
manager.getString(StorageLocation.MENU, path+".action")
));
}
menu.setItem(
slot,
item
);
}
}
private IActionHandler getHandler(ConfigurationManager manager, String path) {
String action = manager.getString(StorageLocation.MENU, path+".action");
if(action == null || action.isEmpty())
return null;
if(MenuAPI.hasActionHandler(action))
return MenuAPI.getActionHandler(action);
switch (action.toUpperCase()) {
case "COMMAND":
return new CommandMenuHandler(manager.getString(StorageLocation.MENU, path+".command"));
case "JSON_MESSAGE":
return new JsonMessageMenuHandler(manager.getString(StorageLocation.MENU, path+".message"));
case "PLAIN_MESSAGE":
return new PlainMessageMenuHandler(manager.getString(StorageLocation.MENU, path+".message"));
default:
return null;
}
}
public void open(Player player) {
menu.open(player);
}
}

View file

@ -0,0 +1,276 @@
package nl.iobyte.themepark.api.menu.objects;
import com.google.common.collect.Iterables;
import nl.iobyte.menuapi.enums.Types;
import nl.iobyte.menuapi.item.ItemBuilder;
import nl.iobyte.menuapi.item.MenuItem;
import nl.iobyte.menuapi.multi.MenuPage;
import nl.iobyte.menuapi.multi.MultiMenu;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.menu.objects.actions.PageAction;
import nl.iobyte.themepark.api.menu.objects.actions.TPAction;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class StatusMenu {
private MultiMenu menu;
private final HashMap<String, List<Integer>> region_index = new HashMap<>();
private final HashMap<String, Integer> attraction_index = new HashMap<>();
/**
* Load the menu
*/
public void load() {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
region_index.clear();
attraction_index.clear();
//Prepare data
LinkedHashMap<Integer, Region> regions = new LinkedHashMap<>();
LinkedHashMap<Integer, List<Attraction>> attractions = new LinkedHashMap<>();
for(Region region : api.getAttractionService().getRegions().values()) {
if(region.getAttractions().isEmpty()) {
regions.put(regions.size(), region);
attractions.put(attractions.size(), new ArrayList<>());
continue;
}
Iterable<List<Attraction>> iterable = Iterables.partition(region.getAttractions().values(), 8);
for(List<Attraction> list : iterable) {
regions.put(regions.size(), region);
attractions.put(attractions.size(), list);
}
}
//Prepare menu
loadMenuPages(api, regions.size());
//Load menu content
loadMenuContent(regions, attractions);
//Load next/previous page items
loadPageItems();
//Build Menu
menu.build();
}
/**
* Update Region item
* @param region Region
*/
public void updateRegion(Region region) {
if(region == null)
return;
if(!region_index.containsKey(region.getID()))
return;
List<Integer> indexes = region_index.get(region.getID());
if(indexes == null || indexes.isEmpty())
return;
for(int slot : indexes) {
menu.setItem(slot, getRegion(region));
menu.updateItem(slot);
}
}
/**
* Update Attraction item
* @param attraction Attraction
*/
public void updateAttraction(Attraction attraction) {
if(attraction == null)
return;
if(!attraction_index.containsKey(attraction.getID()))
return;
int slot = attraction_index.get(attraction.getID());
if(slot < 1)
return;
menu.setItem(slot, getAttraction(attraction));
menu.updateItem(slot);
}
/**
* Open menu on first page for Player
* @param player Player
*/
public void open(Player player) {
open(player, 1);
}
/**
* Open menu for Player
* @param player Player
* @param page Integer
*/
public void open(Player player, int page) {
menu.open(player, page);
}
/**
* Initialize menu and page sizes
* @param api ThemeParkAPI
* @param regions Integer
*/
private void loadMenuPages(ThemeParkAPI api, int regions) {
ArrayList<Integer> page_sizes = new ArrayList<>();
if(regions <= 6) {
if(regions == 0)
regions = 1;
page_sizes.add(regions * 9);
} else {
int pages = regions / 5;
for (int i = 0; i < pages; i++)
page_sizes.add(54);
pages = regions % 5;
if (pages > 0)
page_sizes.add(pages * 9 + 9);
}
menu = new MultiMenu(api.getConfigurationManager().getString(StorageKey.MENU_TITLE_STATUS), page_sizes);
}
/**
* Add regions and attractions to menu
* @param regions LinkedHashMap<Integer, Region>
* @param attractions LinkedHashMap<Integer, List<Attraction>>
*/
private void loadMenuContent(LinkedHashMap<Integer, Region> regions, LinkedHashMap<Integer, List<Attraction>> attractions) {
int region_size = regions.size();
for(int i = 0; i < region_size; i++) {
Region region = regions.get(i);
if(region == null)
continue;
int j = 1;
int start_index = i * 9;
if(region_size > 6)
start_index += (i / 5) * 9;
//Add item index to map
List<Integer> indexes = region_index.computeIfAbsent(region.getID(), s -> new ArrayList<>());
indexes.add(start_index);
region_index.put(region.getID(), indexes);
//Add item to menu
menu.setItem(start_index, new MenuItem(getRegion(region), true));
List<Attraction> list = attractions.get(i);
if(list == null)
continue;
//Add attractions to menu
for(Attraction attraction : list) {
MenuItem item = new MenuItem(getAttraction(attraction), true);
item.addActions(Types.NORMAL.getTypesList(), new TPAction(attraction));
int slot = start_index + j;
attraction_index.put(attraction.getID(), slot);
menu.setItem(slot, item);
j++;
}
}
}
/**
* Load next/previous page items
*/
private void loadPageItems() {
int page_size = menu.getPageSizes().size();
for (int i = 0; i < page_size; i++) {
MenuPage page = menu.getPage(i + 1);
int size = page.getSize();
if (i > 0)
page.setItem(size - 6, getPrevious(i));
if (i < (page_size - 1))
page.setItem(size - 4, getNext(i));
if(page_size > 1) {
ItemBuilder builder = new ItemBuilder(Material.MINECART);
builder.setName("&6Page: &f" + (i + 1));
page.setItem(size - 5, new MenuItem(builder.getItem(), true));
}
}
}
/**
* Get ItemStack of Region
* @param region Region
* @return ItemStack
*/
private static ItemStack getRegion(Region region) {
ItemBuilder builder = new ItemBuilder(Material.NAME_TAG);
builder.setName(region.getName());
return builder.getItem();
}
/**
* Get ItemStack of Attraction
* @param attraction Attraction
* @return ItemStack
*/
private static ItemStack getAttraction(Attraction attraction) {
ItemBuilder builder = new ItemBuilder(attraction.getStatus().getItem());
builder.setName(attraction.getName())
.setLore(attraction.getStatus().getColor() + attraction.getStatus().getName());
return builder.getItem();
}
/**
* Get next page MenuItem
* @param page Integer
* @return MenuItem
*/
private MenuItem getNext(int page) {
return getPage("&6&LNext \u23F5", page + 1);
}
/**
* Get previous page MenuItem
* @param page Integer
* @return MenuItem
*/
private MenuItem getPrevious(int page) {
return getPage("&6&L\u23F4 Previous", page - 1);
}
/**
* Get next/previous page MenuItem
* @param text String
* @param page Integer
* @return MenuItem
*/
private MenuItem getPage(String text, int page) {
ItemBuilder builder = new ItemBuilder(Material.ARROW);
builder.setName(text);
MenuItem item = new MenuItem(builder.getItem(), true);
item.addActions(new PageAction(
menu,
page + 1
));
return item;
}
}

View file

@ -0,0 +1,21 @@
package nl.iobyte.themepark.api.menu.objects.actions;
import nl.iobyte.menuapi.action.MenuAction;
import nl.iobyte.menuapi.multi.MultiMenu;
import org.bukkit.entity.Player;
public class PageAction extends MenuAction {
private final MultiMenu menu;
private final int page;
public PageAction(MultiMenu menu, int page) {
this.menu = menu;
this.page = page;
}
public void execute(Player player) {
menu.open(player, page);
}
}

View file

@ -0,0 +1,20 @@
package nl.iobyte.themepark.api.menu.objects.actions;
import nl.iobyte.menuapi.action.MenuAction;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class TPAction extends MenuAction {
private final Attraction attraction;
public TPAction(Attraction attraction) {
this.attraction = attraction;
}
public void execute(Player player) {
Bukkit.dispatchCommand(player, "pp attraction warp "+attraction.getID());
}
}

View file

@ -0,0 +1,34 @@
package nl.iobyte.themepark.api.menu.objects.handlers;
import nl.iobyte.menuapi.enums.Types;
import nl.iobyte.menuapi.interfaces.IActionHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import java.util.List;
public class CommandMenuHandler implements IActionHandler {
private final String command;
public CommandMenuHandler(String command) {
if(command.startsWith("/"))
command = command.replaceFirst("/", "");
this.command = command;
}
public String getID() {
return "COMMAND";
}
public List<ClickType> getClickTypes() {
return Types.NORMAL.getTypesList();
}
public void execute(Player player) {
player.closeInventory();
Bukkit.dispatchCommand(player, command);
}
}

View file

@ -0,0 +1,38 @@
package nl.iobyte.themepark.api.menu.objects.handlers;
import nl.iobyte.menuapi.enums.Types;
import nl.iobyte.menuapi.interfaces.IActionHandler;
import nl.iobyte.themepark.utils.PlaceHolder;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import java.util.List;
public class JsonMessageMenuHandler implements IActionHandler {
private final String message;
public JsonMessageMenuHandler(String message) {
this.message = message;
}
public String getID() {
return "JSON_MESSAGE";
}
public List<ClickType> getClickTypes() {
return Types.NORMAL.getTypesList();
}
public void execute(Player player) {
player.closeInventory();
Bukkit.dispatchCommand(
Bukkit.getConsoleSender(),
"tellraw "+player.getName()+" "+PlaceHolder.setPlaceHolders(
player,
message
)
);
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.api.menu.objects.handlers;
import nl.iobyte.menuapi.enums.Types;
import nl.iobyte.menuapi.interfaces.IActionHandler;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.utils.PlaceHolder;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import java.util.List;
public class PlainMessageMenuHandler implements IActionHandler {
private final String message;
public PlainMessageMenuHandler(String message) {
this.message = Text.color(message);
}
public String getID() {
return "PLAIN_MESSAGE";
}
public List<ClickType> getClickTypes() {
return Types.NORMAL.getTypesList();
}
public void execute(Player player) {
player.closeInventory();
player.sendMessage(PlaceHolder.setPlaceHolders(
player,
message
));
}
}

View file

@ -0,0 +1,24 @@
package nl.iobyte.themepark.api.menu.objects.handlers;
import nl.iobyte.menuapi.enums.Types;
import nl.iobyte.menuapi.interfaces.IActionHandler;
import nl.iobyte.themepark.ThemePark;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import java.util.List;
public class StatusMenuHandler implements IActionHandler {
public String getID() {
return "STATUS_MENU";
}
public List<ClickType> getClickTypes() {
return Types.NORMAL.getTypesList();
}
public void execute(Player player) {
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().open(player);
}
}

View file

@ -0,0 +1,63 @@
package nl.iobyte.themepark.api.message;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import org.bukkit.entity.Player;
public enum MessageKey {
//Prefix
PREFIX("prefix"),
//Session
CLIENT_UNABLE_TO_CONNECT("client.connect.unable"),
CLIENT_GENERATE_TO_CONNECT("client.connect.generate"),
CLIENT_CLICK_TO_CONNECT("client.connect.click"),
CLIENT_HOVER_TO_CONNECT("client.connect.hover"),
//Connection
CLIENT_CONNECTION_EXISTS("client.connection.exists"),
CLIENT_CONNECTION_OPEN("client.connection.open"),
CLIENT_CONNECTION_CLOSED("client.connection.closed"),
//Ridecount
RIDECOUNT_ADD("ridecount.add"),
//Attraction Teleport
ATTRACTION_TELEPORT_STATUS("attraction.teleport.status"),
ATTRACTION_TELEPORT_SUCCESS("attraction.teleport.success");
private final String path;
MessageKey(String path) {
this.path = path;
}
/**
* Get path to message
* @return String
*/
public String getPath() {
return path;
}
/**
* Get and color message from config
* @return String
*/
public String getMessage() {
String msg = Text.color(ThemePark.getInstance().getAPI().getConfigurationManager().getString(StorageLocation.MESSAGE, path));
if(this != MessageKey.PREFIX)
msg = msg.replace("{prefix}", MessageKey.PREFIX.getMessage());
return msg;
}
/**
* Send message with color to Player
* @param player Player
*/
public void send(Player player) {
player.sendMessage(getMessage());
}
}

View file

@ -0,0 +1,25 @@
package nl.iobyte.themepark.api.message;
import org.bukkit.ChatColor;
public class Text {
/**
* Color text
* @param str String
* @return String
*/
public static String color(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
/**
* Strip text of color
* @param str String
* @return String
*/
public static String strip(String str) {
return ChatColor.stripColor(color(str));
}
}

View file

@ -0,0 +1,110 @@
package nl.iobyte.themepark.api.ridecount;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ridecount.objects.AttractionCount;
import nl.iobyte.themepark.api.ridecount.objects.RideCount;
import nl.iobyte.themepark.api.ridecount.objects.TopData;
import org.bukkit.Bukkit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class RideCountService {
private final Map<String, AttractionCount> counts = new ConcurrentHashMap<>();
private final TopData topData = new TopData();
private boolean changed = false;
public AttractionCount getCount(String id) {
if(id == null || id.isEmpty())
return null;
if(!ThemePark.getInstance().getAPI().getAttractionService().hasAttraction(id))
return null;
return counts.computeIfAbsent(id, k -> new AttractionCount(id));
}
public void setCount(String id, UUID uuid, int amount, int total_amount) {
if(amount == 0 || total_amount == 0 || id == null || id.isEmpty() || uuid == null)
return;
AttractionCount count = getCount(id);
if(count == null)
return;
count.setCount(uuid, amount, total_amount);
}
public RideCount getCount(String id, UUID uuid) {
if(id == null || id.isEmpty() || uuid == null)
return null;
AttractionCount count = getCount(id);
if(count == null)
return null;
return count.getCount(uuid);
}
public void addCount(String id, UUID uuid, int amount) {
if(amount == 0 || id == null || id.isEmpty() || uuid == null)
return;
AttractionCount count = getCount(id);
if(count == null)
return;
count.addCount(uuid, amount);
changed = true;
}
public void clearCount(UUID uuid) {
if(uuid == null)
return;
for(AttractionCount attractionCount : counts.values())
attractionCount.removeCount(uuid);
}
public boolean hasChanged() {
return changed;
}
public List<RideCount> getChanges(long timestamp) {
List<RideCount> list = new ArrayList<>();
for(AttractionCount attractionCount : counts.values())
for(Map<Integer, Map<UUID, RideCount>> m1 : attractionCount.getCounts().values())
for(Map<UUID, RideCount> m2 : m1.values())
for(RideCount count : m2.values())
if(count.getUpdatedAt() != -1 && count.getUpdatedAt() > timestamp)
list.add(count);
return list;
}
public void clearNonApplicable() {
changed = false;
Calendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DAY_OF_YEAR);
for(AttractionCount attractionCount : counts.values()) {
attractionCount.removeOld(
year,
day
);
Map<UUID, RideCount> map = attractionCount.getCounts(year, day);
if(map == null)
return;
map.entrySet().removeIf(e -> Bukkit.getPlayer(e.getValue().getUUID()) == null);
}
}
public TopData getTopData() {
return topData;
}
}

View file

@ -0,0 +1,151 @@
package nl.iobyte.themepark.api.ridecount.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.event.ridecount.RideCountAddEvent;
import nl.iobyte.themepark.scheduler.ThemeParkScheduler;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class AttractionCount {
private final String attraction_id;
private final Map<Integer, Map<Integer, Map<UUID, RideCount>>> counts = new ConcurrentHashMap<>();
private int current_year, current_month, current_week, current_day;
private long next_day;
public AttractionCount(String attraction_id) {
this.attraction_id = attraction_id;
updateTimes();
}
public String getAttractionID() {
return attraction_id;
}
public Map<Integer, Map<Integer, Map<UUID, RideCount>>> getCounts() {
return counts;
}
public Map<Integer, Map<UUID, RideCount>> getCounts(int year) {
return counts.get(year);
}
public Map<UUID, RideCount> getCounts(int year, int day) {
Map<Integer, Map<UUID, RideCount>> map = getCounts(year);
if(map == null)
return null;
return map.get(day);
}
public void remove() {
counts.clear();
}
public void removeOld(int year, int day) {
counts.entrySet().removeIf(e -> e.getKey() != year);
counts.values().forEach(m -> m.entrySet().removeIf(e -> e.getKey() != day));
}
private Map<UUID, RideCount> get(int year, int day) {
Map<Integer, Map<UUID, RideCount>> ym = counts.computeIfAbsent(year, k -> new ConcurrentHashMap<>());
return ym.computeIfAbsent(day, k -> new ConcurrentHashMap<>());
}
public void setCount(UUID uuid, int amount, int total_amount) {
if(next_day <= System.currentTimeMillis())
updateTimes();
Map<UUID, RideCount> counts = get(current_year, current_day);
counts.computeIfAbsent(uuid, k -> new RideCount(
uuid,
attraction_id,
amount,
total_amount,
current_year,
current_month,
current_week,
current_day
));
}
public RideCount getCount(UUID uuid) {
if(next_day <= System.currentTimeMillis())
updateTimes();
Map<UUID, RideCount> counts = get(current_year, current_day);
return counts.get(uuid);
}
public void addCount(UUID uuid, int amount) {
if(next_day <= System.currentTimeMillis())
updateTimes();
ThemeParkScheduler.runAsync(() -> {
Map<UUID, RideCount> counts = get(current_year, current_day);
RideCount rc = counts.computeIfAbsent(uuid, k -> {
ArrayList<Map<String, Object>> result = ThemePark.getInstance().getAPI().getDatabaseService().executeQuery(
"local",
"SELECT sum(count) AS total_count FROM counts WHERE uuid=? AND attraction_id=? AND year=? AND month=? GROUP BY uuid",
new HashMap<Integer, Object>(){{
put(1, uuid);
put(2, attraction_id);
put(3, current_year);
put(4, current_month);
}}
);
int total_amount = 0;
if(result != null)
for(Map<String, Object> row : result)
total_amount = (int) row.get("total_count");
return new RideCount(
uuid,
attraction_id,
0,
total_amount,
current_year,
current_month,
current_week,
current_day
);
});
//Event Parameters
int old = rc.getCount();
int current = old + amount;
//Add amount -> execute event
rc.addCount(amount);
ThemePark.getInstance().getAPI().getEventDispatcher().call(new RideCountAddEvent(
rc,
old,
current
));
});
}
public void removeCount(UUID uuid) {
for(Map<Integer, Map<UUID, RideCount>> m1 : counts.values())
for(Map<UUID, RideCount> m2 : m1.values())
m2.entrySet().removeIf(e -> e.getKey() == uuid && e.getValue().getUpdatedAt() == -1);
}
private void updateTimes() {
Calendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
current_year = calendar.get(Calendar.YEAR);
current_month = calendar.get(Calendar.MONTH) + 1;
current_week = calendar.get(Calendar.WEEK_OF_YEAR);
current_day = calendar.get(Calendar.DAY_OF_YEAR);
next_day = calendar.getTimeInMillis();
}
}

View file

@ -0,0 +1,81 @@
package nl.iobyte.themepark.api.ridecount.objects;
import java.util.UUID;
public class RideCount {
private final UUID uuid;
private final String attraction_id;
private final int year, month, week, day;
private int count, total_count;
private long updated_at;
public RideCount(UUID uuid, String attraction_id, int count, int total_count, int year, int month, int week, int day) {
this(
uuid,
attraction_id,
count,
total_count,
year,
month,
week,
day,
-1
);
}
public RideCount(UUID uuid, String attraction_id, int count, int total_count, int year, int month, int week, int day, long updated_at) {
this.uuid = uuid;
this.attraction_id = attraction_id;
this.count = count;
this.total_count = total_count;
this.year = year;
this.month = month;
this.week = week;
this.day = day;
this.updated_at = updated_at;
}
public UUID getUUID() {
return uuid;
}
public String getAttractionID() {
return attraction_id;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getWeek() {
return week;
}
public int getDay() {
return day;
}
public int getCount() {
return count;
}
public int getTotalCount() {
return total_count;
}
public void addCount(int count) {
this.count += count;
this.total_count += count;
updated_at = System.currentTimeMillis();
}
public long getUpdatedAt() {
return updated_at;
}
}

View file

@ -0,0 +1,143 @@
package nl.iobyte.themepark.api.ridecount.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.database.objects.Database;
import nl.iobyte.themepark.scheduler.ThemeParkScheduler;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public class TopData {
public CompletableFuture<HashMap<UUID, Integer>> getDay(Attraction attraction) {
return get(attraction, 0);
}
public CompletableFuture<HashMap<UUID, Integer>> getWeek(Attraction attraction) {
return get(attraction, 1);
}
public CompletableFuture<HashMap<UUID, Integer>> getMonth(Attraction attraction) {
return get(attraction, 2);
}
public CompletableFuture<HashMap<UUID, Integer>> getYear(Attraction attraction) {
return get(attraction, 3);
}
private CompletableFuture<HashMap<UUID, Integer>> get(Attraction attraction, int i) {
CompletableFuture<HashMap<UUID, Integer>> fc = new CompletableFuture<>();
if(attraction == null) {
fc.complete(null);
return fc;
}
ThemeParkAPI api = ThemePark.getInstance().getAPI();
if(!api.getAttractionService().hasAttraction(attraction.getID())) {
fc.complete(null);
return fc;
}
Database db = api.getDatabaseService().getDatabase("local");
if(db == null) {
fc.complete(null);
return fc;
}
ThemeParkScheduler.runAsync(() -> {
Calendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
HashMap<Integer, Object> map = new HashMap<>();
map.put(1, attraction.getID());
String timeSort;
switch (i) {
case 0:
timeSort = "day=? AND year=?";
map.put(2, calendar.get(Calendar.DAY_OF_YEAR));
map.put(3, calendar.get(Calendar.YEAR));
break;
case 1:
timeSort = "week=? AND year=?";
map.put(2, calendar.get(Calendar.WEEK_OF_YEAR));
map.put(3, calendar.get(Calendar.YEAR));
break;
case 2:
timeSort = "month=? AND year=?";
map.put(2, calendar.get(Calendar.MONTH) + 1);
map.put(3, calendar.get(Calendar.YEAR));
break;
default:
timeSort = "year=?";
map.put(2, calendar.get(Calendar.YEAR));
break;
}
ArrayList<Map<String, Object>> results = db.executeQuery("SELECT uuid, SUM(count) AS count FROM counts WHERE attraction_id=? AND "+timeSort+" GROUP BY uuid ORDER BY count DESC LIMIT 3", map);
if(results == null || results.isEmpty()) {
fc.complete(null);
return;
}
HashMap<UUID, Integer> top = new HashMap<>();
for(Map<String, Object> m : results) {
UUID uuid = UUID.fromString((String) m.get("uuid"));
int points = (int) m.get("count");
if(points < 0)
continue;
top.put(uuid, points);
}
fc.complete(top);
});
return fc;
}
public CompletableFuture<HashMap<UUID, Integer>> getTotal(Attraction attraction) {
CompletableFuture<HashMap<UUID, Integer>> fc = new CompletableFuture<>();
if(attraction == null) {
fc.complete(null);
return fc;
}
ThemeParkAPI api = ThemePark.getInstance().getAPI();
if(!api.getAttractionService().hasAttraction(attraction.getID())) {
fc.complete(null);
return fc;
}
Database db = api.getDatabaseService().getDatabase("local");
if(db == null) {
fc.complete(null);
return fc;
}
ThemeParkScheduler.runAsync(() -> {
HashMap<Integer, Object> map = new HashMap<>();
map.put(1, attraction.getID());
ArrayList<Map<String, Object>> results = db.executeQuery("SELECT uuid, SUM(count) AS count FROM counts WHERE attraction_id=? GROUP BY uuid ORDER BY count DESC LIMIT 3", map);
if(results == null || results.isEmpty()) {
fc.complete(null);
return;
}
HashMap<UUID, Integer> top = new HashMap<>();
for(Map<String, Object> m : results) {
UUID uuid = UUID.fromString((String) m.get("uuid"));
int points = (int) m.get("count");
if(points < 0)
continue;
top.put(uuid, points);
}
fc.complete(top);
});
return fc;
}
}

View file

@ -0,0 +1,119 @@
package nl.iobyte.themepark.api.sign;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import nl.iobyte.themepark.api.sign.objects.StatusSign;
import nl.iobyte.themepark.utils.LocationUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import java.util.ArrayList;
import java.util.HashMap;
public class SignManager {
private final HashMap<Attraction, ArrayList<StatusSign>> signs = new HashMap<>();
public HashMap<Attraction, ArrayList<StatusSign>> getSigns() {
return signs;
}
public void addSign(StatusSign sign) {
if(sign == null || sign.getLocation() == null)
return;
if(!(sign.getLocation().getBlock().getState() instanceof Sign))
return;
if(signs.containsKey(sign.getAttraction())) {
signs.get(sign.getAttraction()).add(sign);
return;
}
ArrayList<StatusSign> array = new ArrayList<>();
array.add(sign);
signs.put(sign.getAttraction(), array);
}
public boolean hasSigns(Attraction attraction) {
if(attraction == null)
return false;
return signs.containsKey(attraction) && (signs.get(attraction).size() > 0);
}
public boolean isSign(Attraction attraction, Location location) {
if(attraction == null || location == null)
return false;
ArrayList<StatusSign> array = signs.get(attraction);
if(array == null)
return false;
String loc = LocationUtil.toString(location);
for(StatusSign sign : array) {
String str = LocationUtil.toString(sign.getLocation());
if(loc.equals(str))
return true;
}
return false;
}
public void update(Attraction attraction) {
if(attraction == null)
return;
if(!hasSigns(attraction))
return;
for(StatusSign sign : signs.get(attraction))
sign.update();
}
public void remove(Attraction attraction) {
if(attraction == null || !signs.containsKey(attraction))
return;
for(StatusSign sign : signs.get(attraction))
sign.getLocation().getBlock().setType(Material.AIR);
signs.remove(attraction);
ThemePark.getInstance().getAPI().getConfigurationManager().set(StorageLocation.SIGN_DATA, "signs."+attraction.getID(), null);
}
public void removeSign(StatusSign sign) {
if(sign == null || sign.getLocation() == null || sign.getAttraction() == null)
return;
if(!hasSigns(sign.getAttraction()))
return;
Location loc1 = sign.getLocation();
String str1 = LocationUtil.toString(loc1);
ArrayList<StatusSign> array = signs.get(sign.getAttraction());
for(StatusSign s : new ArrayList<>(array)) {
Location loc2 = s.getLocation();
if(loc1 == null || loc2 == null)
return;
String str2 = LocationUtil.toString(loc2);
if(!str1.equals(str2))
return;
array.remove(s);
}
if(array.isEmpty()) {
signs.remove(sign.getAttraction());
ThemePark.getInstance().getAPI().getConfigurationManager().set(StorageLocation.SIGN_DATA, "signs."+sign.getAttraction().getID(), null);
return;
}
signs.put(sign.getAttraction(), array);
}
}

View file

@ -0,0 +1,44 @@
package nl.iobyte.themepark.api.sign.objects;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.Location;
import org.bukkit.block.Sign;
public class StatusSign {
private final Attraction attraction;
private final Location location;
public StatusSign(Attraction attraction, Location location) {
this.attraction = attraction;
this.location = location;
}
public Attraction getAttraction() {
return attraction;
}
public Location getLocation() {
return location;
}
public void update() {
Status status = attraction.getStatus();
if(!location.getChunk().isLoaded())
location.getChunk().load();
if(!(location.getBlock().getState() instanceof Sign)) {
ThemePark.getInstance().getAPI().getSignManager().removeSign(this);
return;
}
Sign sign = (Sign) location.getBlock().getState();
sign.setLine(1, Text.color(attraction.getName()));
sign.setLine(2, Text.color(status.getColor()+status.getName()));
sign.update();
}
}

View file

@ -0,0 +1,44 @@
package nl.iobyte.themepark.commands;
import nl.iobyte.commandapi.CommandFactory;
import nl.iobyte.commandapi.middlewares.PermissionMiddleware;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.commands.subcommands.HelpCommand;
import nl.iobyte.themepark.commands.subcommands.ItemCommand;
import nl.iobyte.themepark.commands.subcommands.MenuCommand;
import nl.iobyte.themepark.commands.subcommands.attraction.AttractionCommands;
import nl.iobyte.themepark.commands.subcommands.region.RegionCommands;
import nl.iobyte.themepark.commands.subcommands.ridecount.RideCountCommands;
import nl.iobyte.themepark.commands.subcommands.status.StatusCommands;
public class ThemeParkCommand {
//Load command data
public ThemeParkCommand() {
CommandFactory factory = new CommandFactory("themepark");
factory.addSubCommand(new HelpCommand(factory))
.addSubCommand(new MenuCommand());
//Admin
factory.addSubCommand(new ItemCommand());
//Region
RegionCommands.load(factory);
//Attraction
AttractionCommands.load(factory);
//Status
StatusCommands.load(factory);
//RideCount
RideCountCommands.load(factory);
//Middleware
factory.addMiddleware(new PermissionMiddleware());
//Register command
factory.registerCommand(ThemePark.getInstance());
}
}

View file

@ -0,0 +1,43 @@
package nl.iobyte.themepark.commands.arguments;
import nl.iobyte.commandapi.interfaces.ICommandArgument;
import nl.iobyte.commandapi.objects.ArgumentCheck;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class AttractionArgument implements ICommandArgument<Attraction> {
/**
* Message to display when giving an error
* @return String
*/
public String getMessage(String[] args) {
return "No Attraction found with ID: "+ ChatColor.WHITE+args[0];
}
/**
* Check if argument is valid Attraction
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return Boolean
*/
public ArgumentCheck checkArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return new ArgumentCheck(ThemePark.getInstance().getAPI().getAttractionService().hasAttraction(args[0]), 1);
}
/**
* Get Attraction passed by command
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return Attraction
*/
public Attraction getArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return ThemePark.getInstance().getAPI().getAttractionService().getAttraction(args[0]);
}
}

View file

@ -0,0 +1,42 @@
package nl.iobyte.themepark.commands.arguments;
import nl.iobyte.commandapi.interfaces.ICommandArgument;
import nl.iobyte.commandapi.objects.ArgumentCheck;
import nl.iobyte.themepark.ThemePark;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class NoAttractionArgument implements ICommandArgument<String> {
/**
* Message to display when giving an error
* @return String
*/
public String getMessage(String[] args) {
return "Attraction with ID: "+ChatColor.WHITE+args[0]+ChatColor.RED+" already exists";
}
/**
* Check if argument is a not existing Attraction
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return Boolean
*/
public ArgumentCheck checkArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return new ArgumentCheck(!ThemePark.getInstance().getAPI().getAttractionService().hasAttraction(args[0]), 1);
}
/**
* Get String passed by command
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return String
*/
public String getArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return args[0];
}
}

View file

@ -0,0 +1,42 @@
package nl.iobyte.themepark.commands.arguments;
import nl.iobyte.commandapi.interfaces.ICommandArgument;
import nl.iobyte.commandapi.objects.ArgumentCheck;
import nl.iobyte.themepark.ThemePark;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class NoRegionArgument implements ICommandArgument<String> {
/**
* Message to display when giving an error
* @return String
*/
public String getMessage(String[] args) {
return "Region with ID: "+ChatColor.WHITE+args[0]+ChatColor.RED+" already exists";
}
/**
* Check if argument is a not existing Attraction
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return Boolean
*/
public ArgumentCheck checkArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return new ArgumentCheck(!ThemePark.getInstance().getAPI().getAttractionService().hasRegion(args[0]), 1);
}
/**
* Get String passed by command
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return String
*/
public String getArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return args[0];
}
}

View file

@ -0,0 +1,43 @@
package nl.iobyte.themepark.commands.arguments;
import nl.iobyte.commandapi.interfaces.ICommandArgument;
import nl.iobyte.commandapi.objects.ArgumentCheck;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Region;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class RegionArgument implements ICommandArgument<Region> {
/**
* Message to display when giving an error
* @return String
*/
public String getMessage(String[] args) {
return "No Region found with ID: "+ ChatColor.WHITE+args[0];
}
/**
* Check if argument is valid Region
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return Boolean
*/
public ArgumentCheck checkArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return new ArgumentCheck(ThemePark.getInstance().getAPI().getAttractionService().hasRegion(args[0]), 1);
}
/**
* Get Region passed by command
* @param sender CommandSender
* @param args Arguments passed by Command
* @param previousArguments Previous arguments
* @return Region
*/
public Region getArgument(CommandSender sender, String[] args, List<Object> previousArguments) {
return ThemePark.getInstance().getAPI().getAttractionService().getRegion(args[0]);
}
}

View file

@ -0,0 +1,71 @@
package nl.iobyte.themepark.commands.subcommands;
import nl.iobyte.commandapi.CommandFactory;
import nl.iobyte.commandapi.arguments.number.IntegerArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class HelpCommand extends SubCommand {
private final CommandFactory factory;
public HelpCommand(CommandFactory factory) {
super(new String[]{"help"});
this.factory = factory;
addSyntax("/themepark help");
addSyntax("/themepark help <page>")
.addArgument(new IntegerArgument());
}
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
//Send CommandSender list of commands it has access to
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
List<SubCommand> commands = factory.getApplicableSubCommands(sender);
if(commands.size() <= 5) {
sendSinglePage(sender, commands);
return;
}
sendMultiPage(sender, commands, list, i);
}
private void sendSinglePage(CommandSender sender, List<SubCommand> commands) {
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &l&f====<"));
for (SubCommand command : commands)
sender.sendMessage(Text.color("&f" + command.getApplicableSyntaxList(sender).get(0).getUsage()));
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &l&f====<"));
}
private void sendMultiPage(CommandSender sender, List<SubCommand> commands, List<Object> list, int i) {
int page = 1;
int pages = (int) Math.ceil(((double) commands.size()) / 5);
if(i == 1)
page = (Integer) list.get(0);
if(page < 1 || page > pages) {
sender.sendMessage(Text.color("&6&lThemePark &f➢ Page &6"+page+" &fdoesn't exist"));
return;
}
page--;
int start = page * 5;
int end = page * 5 + 5;
if(end > commands.size())
end = commands.size();
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &f(&6"+(page + 1)+"&f/&6"+pages+"&f) &l&f====<"));
for(i = start; i < end; i++)
sender.sendMessage(Text.color("&f" + commands.get(i).getApplicableSyntaxList(sender).get(0).getUsage()));
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &l&f====<"));
}
}

View file

@ -0,0 +1,43 @@
package nl.iobyte.themepark.commands.subcommands;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.menuapi.item.ItemBuilder;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class ItemCommand extends SubCommand {
public ItemCommand() {
super("themepark.admin", "item");
addSyntax("/themepark item")
.setAllowConsole(false);
}
public void onPlayerCommand(Player player, List<Object> objects, int i) {
ConfigurationManager manager = ThemePark.getInstance().getAPI().getConfigurationManager();
Material material = Material.getMaterial(manager.getString(StorageKey.MENU_ITEM_MATERIAL));
short data = Short.parseShort(manager.getString(StorageKey.MENU_ITEM_DATA));
String name = Text.color(manager.getString(StorageKey.MENU_ITEM_NAME));
if(material == null || name.isEmpty())
return;
ItemBuilder builder = new ItemBuilder(material, 1, data);
builder.setName(name);
player.getInventory().addItem(builder.getItem());
player.updateInventory();
player.sendMessage(Text.color("&6&lThemeParkMC &f➢ Added item to your inventory"));
}
//Give CommandSender overview of Plugin status
public void onConsoleCommand(CommandSender sender, List<Object> objects, int i) {}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.commands.subcommands;
import nl.iobyte.commandapi.arguments.StringArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.menu.MenuService;
import nl.iobyte.themepark.scheduler.ThemeParkScheduler;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class MenuCommand extends SubCommand {
public MenuCommand() {
super(null, "menu");
addSyntax("/themepark menu");
addSyntax("/themepark menu")
.addArgument(new StringArgument("status"));
}
public void onPlayerCommand(Player player, List<Object> objects, int i) {
MenuService service = ThemePark.getInstance().getAPI().getMenuService();
if(i == 0) {
ThemeParkScheduler.runSync(() -> service.getMainMenu().open(player));
return;
}
ThemeParkScheduler.runSync(() -> service.getStatusMenu().open(player));
}
public void onConsoleCommand(CommandSender sender, List<Object> objects, int i) {}
}

View file

@ -0,0 +1,19 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.CommandFactory;
public class AttractionCommands {
public static void load(CommandFactory factory) {
factory.addSubCommand(new AttractionListCommand())
.addSubCommand(new AttractionWarpCommand())
.addSubCommand(new AttractionCreateCommand())
.addSubCommand(new AttractionRegionCommand())
.addSubCommand(new AttractionNameCommand())
.addSubCommand(new AttractionCoverCommand())
.addSubCommand(new AttractionStatusCommand())
.addSubCommand(new AttractionLocationCommand())
.addSubCommand(new AttractionRemoveCommand());
}
}

View file

@ -0,0 +1,34 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.arguments.StringArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionCoverCommand extends SubCommand {
public AttractionCoverCommand() {
super("themepark.admin", "attraction", "cover");
addSyntax("/themepark attraction cover <id> <url>")
.addArgument(new AttractionArgument())
.addArgument(new StringArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
String url = (String) list.get(1);
attraction.setCover(url);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the cover of attraction &f"+attraction.getID()));
}
}

View file

@ -0,0 +1,76 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.arguments.MessageArgument;
import nl.iobyte.commandapi.arguments.StringArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.NoAttractionArgument;
import nl.iobyte.themepark.commands.arguments.RegionArgument;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionCreateCommand extends SubCommand {
public AttractionCreateCommand() {
super("themepark.admin", "attraction", "create");
addSyntax("/themepark attraction create <id> <region_id> <name>")
.addArgument(new NoAttractionArgument())
.addArgument(new RegionArgument())
.addArgument(new MessageArgument());
addSyntax("/themepark attraction create <id> <region_id> <name> <status>")
.addArgument(new NoAttractionArgument())
.addArgument(new RegionArgument())
.addArgument(new MessageArgument())
.addArgument(new EnumArgument(Status.values()));
addSyntax("/themepark attraction create <id> <region_id> <name> <status> <url>")
.addArgument(new NoAttractionArgument())
.addArgument(new RegionArgument())
.addArgument(new MessageArgument())
.addArgument(new EnumArgument(Status.values()))
.addArgument(new StringArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
String id = (String) list.get(0);
Region region = (Region) list.get(1);
String name = (String) list.get(2);
Status status = Status.CONSTRUCTION;
if(i != 0)
status = (Status) list.get(3);
String cover = "https://via.placeholder.com/500x500";
if(i > 1)
cover = (String) list.get('4');
Location location = null;
if(sender instanceof Player)
location = ((Player) sender).getLocation();
ThemePark.getInstance().getAPI().getAttractionService().addAttraction(new Attraction(
id,
region.getID(),
name,
cover,
status,
location
));
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully created attraction &f"+id));
}
}

View file

@ -0,0 +1,107 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import com.google.common.collect.Iterables;
import nl.iobyte.commandapi.arguments.number.IntegerArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.RegionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collection;
import java.util.List;
public class AttractionListCommand extends SubCommand {
public AttractionListCommand() {
super("themepark.admin", "attraction", "list");
addSyntax("/themepark attraction list");
addSyntax("/themepark attraction list <page>")
.addArgument(new IntegerArgument());
addSyntax("/themepark attraction list <region>")
.addArgument(new RegionArgument());
addSyntax("/themepark attraction list <region> <page>")
.addArgument(new RegionArgument())
.addArgument(new IntegerArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
int page = 1;
String title = "&6&lThemePark";
Collection<Attraction> attractions;
if(i < 2) {
if(i == 1)
page = (Integer) list.get(0);
attractions = ThemePark.getInstance().getAPI().getAttractionService().getAttractions().values();
} else {
if(i == 3)
page = (Integer) list.get(1);
Region region = (Region) list.get(0);
title = region.getName();
attractions = region.getAttractions().values();
}
if(attractions.size() <= 5) {
sendSinglePage(sender, title, attractions);
} else {
sendMultiPage(sender, page, title, attractions);
}
}
private void sendSinglePage(CommandSender sender, String title, Collection<Attraction> attractions) {
sender.sendMessage(Text.color("&f&l>==== &r"+title+" &l&f====<"));
if(attractions.isEmpty()) {
sender.sendMessage(Text.color("&6No attractions found"));
} else {
for (Attraction attraction : attractions)
sender.sendMessage(Text.color(
"&6ID: &f" + attraction.getID()
+ " &6Region: &f" + attraction.getRegionID()
+ " &6Name: &r" + attraction.getName()
+ " &6Status: &r" + attraction.getStatus().getColor() + attraction.getStatus().getName()));
}
sender.sendMessage(Text.color("&f&l>==== &r"+title+" &l&f====<"));
}
private void sendMultiPage(CommandSender sender, int page, String title, Collection<Attraction> attractions) {
int pages = (int) Math.ceil(((double) attractions.size()) / 5);
if(page < 1 || page > pages) {
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ Page &6"+page+" &fdoesn't exist"));
return;
}
int i = 0;
for(List<Attraction> lr : Iterables.partition(attractions, 5)) {
i++;
if(i != page)
continue;
sender.sendMessage(Text.color("&f&l>==== &r"+title+" &f(&6"+page+"&f/&6"+pages+"&f) &l&f====<"));
for(Attraction attraction : lr)
sender.sendMessage(Text.color(
"&6ID: &f"+attraction.getID()
+" &6Region: &f"+attraction.getRegionID()
+" &6Name: &r"+attraction.getName()
+" &6Status: &r"+attraction.getStatus().getColor()+attraction.getStatus().getName()));
sender.sendMessage(Text.color("&f&l>==== &r"+title+" &l&f====<"));
break;
}
}
}

View file

@ -0,0 +1,31 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionLocationCommand extends SubCommand {
public AttractionLocationCommand() {
super("themepark.admin", "attraction", "location");
addSyntax("/themepark attraction location <id>")
.addArgument(new AttractionArgument())
.setAllowConsole(false);
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
attraction.setLocation(player.getLocation());
player.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the location of attraction &f"+attraction.getID()));
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {}
}

View file

@ -0,0 +1,34 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.arguments.MessageArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionNameCommand extends SubCommand {
public AttractionNameCommand() {
super("themepark.admin", "attraction", "name");
addSyntax("/themepark attraction name <id> <name>")
.addArgument(new AttractionArgument())
.addArgument(new MessageArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
String name = (String) list.get(1);
attraction.setName(name);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the name of attraction &f"+attraction.getID()));
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import nl.iobyte.themepark.commands.arguments.RegionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionRegionCommand extends SubCommand {
public AttractionRegionCommand() {
super("themepark.admin", "attraction", "region");
addSyntax("/themepark attraction region <attraction_id> <region_id>")
.addArgument(new AttractionArgument())
.addArgument(new RegionArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
Region region = (Region) list.get(1);
attraction.setRegionID(region.getID());
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the region of attraction &f"+attraction.getID()));
}
}

View file

@ -0,0 +1,33 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionRemoveCommand extends SubCommand {
public AttractionRemoveCommand() {
super("themepark.admin", "attraction", "remove");
addSyntax("/themepark attraction remove <id>")
.addArgument(new AttractionArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
ThemePark.getInstance().getAPI().getAttractionService().removeAttraction(attraction.getID());
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully removed attraction &f"+attraction.getID()));
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionStatusCommand extends SubCommand {
public AttractionStatusCommand() {
super("themepark.admin", "attraction", "status");
addSyntax("/themepark attraction status <id> <status>")
.addArgument(new AttractionArgument())
.addArgument(new EnumArgument(Status.values()));
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
Status status = (Status) list.get(1);
attraction.setStatus(status);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the status of attraction &f"+attraction.getID()));
}
}

View file

@ -0,0 +1,50 @@
package nl.iobyte.themepark.commands.subcommands.attraction;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.MessageKey;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import nl.iobyte.themepark.scheduler.ThemeParkScheduler;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class AttractionWarpCommand extends SubCommand {
public AttractionWarpCommand() {
super("themepark.admin", "attraction", "warp");
addSyntax("/themepark attraction warp <id>")
.addArgument(new AttractionArgument())
.setAllowConsole(false);
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
if(!attraction.getStatus().canTeleport()) {
String message = MessageKey.ATTRACTION_TELEPORT_STATUS.getMessage();
message = message.replace("{name}", attraction.getName());
message = message.replace("{status}", attraction.getStatus().getColor() + attraction.getStatus().getName());
player.sendMessage(Text.color(message));
return;
}
if(attraction.getLocation() == null) {
player.sendMessage(Text.color("&6&lThemeParkMC &f➢ &4No location available for this attraction"));
return;
}
ThemeParkScheduler.runSync(() -> {
player.teleport(attraction.getLocation());
String message = MessageKey.ATTRACTION_TELEPORT_SUCCESS.getMessage();
message = message.replace("{name}", attraction.getName());
player.sendMessage(Text.color(message));
});
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {}
}

View file

@ -0,0 +1,14 @@
package nl.iobyte.themepark.commands.subcommands.region;
import nl.iobyte.commandapi.CommandFactory;
public class RegionCommands {
public static void load(CommandFactory factory) {
factory.addSubCommand(new RegionListCommand())
.addSubCommand(new RegionCreateCommand())
.addSubCommand(new RegionNameCommand())
.addSubCommand(new RegionRemoveCommand());
}
}

View file

@ -0,0 +1,39 @@
package nl.iobyte.themepark.commands.subcommands.region;
import nl.iobyte.commandapi.arguments.MessageArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.NoRegionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class RegionCreateCommand extends SubCommand {
public RegionCreateCommand() {
super("themepark.admin", "region", "create");
addSyntax("/themepark region create <id> <name>")
.addArgument(new NoRegionArgument())
.addArgument(new MessageArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
String id = (String) list.get(0);
String name = (String) list.get(1);
ThemePark.getInstance().getAPI().getAttractionService().addRegion(new Region(
id,
name
));
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully created region &f"+id));
}
}

View file

@ -0,0 +1,78 @@
package nl.iobyte.themepark.commands.subcommands.region;
import com.google.common.collect.Iterables;
import nl.iobyte.commandapi.arguments.number.IntegerArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collection;
import java.util.List;
public class RegionListCommand extends SubCommand {
public RegionListCommand() {
super("themepark.admin", "region", "list");
addSyntax("/themepark region list");
addSyntax("/themepark region list <page>")
.addArgument(new IntegerArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Collection<Region> regions = ThemePark.getInstance().getAPI().getAttractionService().getRegions().values();
if(regions.size() <= 5) {
sendSinglePage(sender, regions);
} else {
sendMultiPage(sender, regions, list, i);
}
}
private void sendSinglePage(CommandSender sender, Collection<Region> regions) {
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &l&f====<"));
if(regions.isEmpty()) {
sender.sendMessage(Text.color("&6No regions found"));
} else {
for (Region region : regions)
sender.sendMessage(Text.color("&6ID: &f" + region.getID() + " &6Name: &r" + region.getName()));
}
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &l&f====<"));
}
private void sendMultiPage(CommandSender sender, Collection<Region> regions, List<Object> list, int i) {
int page = 1;
int pages = (int) Math.ceil(((double) regions.size()) / 5);
if(i == 1)
page = (Integer) list.get(0);
if(page < 1 || page > pages) {
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ Page &6"+page+" &fdoesn't exist"));
return;
}
i = 0;
for(List<Region> lr : Iterables.partition(regions, 5)) {
i++;
if(i != page)
continue;
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &f(&6"+(page + 1)+"&f/&6"+pages+"&f) &l&f====<"));
for(Region region : lr)
sender.sendMessage(Text.color("&6ID: &f"+region.getID()+" &6Name: &r"+region.getName()));
sender.sendMessage(Text.color("&f&l>==== &6&lThemePark &l&f====<"));
break;
}
}
}

View file

@ -0,0 +1,34 @@
package nl.iobyte.themepark.commands.subcommands.region;
import nl.iobyte.commandapi.arguments.MessageArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.RegionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class RegionNameCommand extends SubCommand {
public RegionNameCommand() {
super("themepark.admin", "region", "name");
addSyntax("/themepark region name <id> <name>")
.addArgument(new RegionArgument())
.addArgument(new MessageArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Region region = (Region) list.get(0);
String name = (String) list.get(1);
region.setName(name);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the name of region &f"+region.getID()));
}
}

View file

@ -0,0 +1,32 @@
package nl.iobyte.themepark.commands.subcommands.region;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.RegionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class RegionRemoveCommand extends SubCommand {
public RegionRemoveCommand() {
super("themepark.admin", "region", "remove");
addSyntax("/themepark region remove <id>")
.addArgument(new RegionArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Region region = (Region) list.get(0);
ThemePark.getInstance().getAPI().getAttractionService().removeRegion(region.getID());
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully removed region &f"+region.getID()));
}
}

View file

@ -0,0 +1,48 @@
package nl.iobyte.themepark.commands.subcommands.ridecount;
import nl.iobyte.commandapi.arguments.PlayersArgument;
import nl.iobyte.commandapi.arguments.number.IntegerArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class RideCountAddCommand extends SubCommand {
public RideCountAddCommand() {
super("themepark.admin", "ridecount", "add");
addSyntax("/themepark ridecount add <attraction> <selector> <amount>")
.addArgument(new AttractionArgument())
.addArgument(new PlayersArgument())
.addArgument(new IntegerArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
List<Player> players = (List<Player>) list.get(1);
int amount = (Integer) list.get(2);
for(Player player : players)
ThemePark.getInstance().getAPI().getRideCountService().addCount(
attraction.getID(),
player.getUniqueId(),
amount
);
sender.sendMessage(Text.color(
"&6&lThemeParkMC &f➢ &aSuccessfully added count of: &6"+amount+"x &ato attraction: &f"+attraction.getID()+" &afor &6"+players.size()+" &aplayers"
));
}
}

View file

@ -0,0 +1,12 @@
package nl.iobyte.themepark.commands.subcommands.ridecount;
import nl.iobyte.commandapi.CommandFactory;
public class RideCountCommands {
public static void load(CommandFactory factory) {
factory.addSubCommand(new RideCountGetCommand())
.addSubCommand(new RideCountAddCommand());
}
}

View file

@ -0,0 +1,44 @@
package nl.iobyte.themepark.commands.subcommands.ridecount;
import nl.iobyte.commandapi.arguments.PlayerArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.api.ridecount.objects.RideCount;
import nl.iobyte.themepark.commands.arguments.AttractionArgument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class RideCountGetCommand extends SubCommand {
public RideCountGetCommand() {
super("themepark.admin", "ridecount", "get");
addSyntax("/themepark ridecount get <attraction> <player>")
.addArgument(new AttractionArgument())
.addArgument(new PlayerArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Attraction attraction = (Attraction) list.get(0);
Player player = (Player) list.get(1);
RideCount count = ThemePark.getInstance().getAPI().getRideCountService().getCount(
attraction.getID(),
player.getUniqueId()
);
sender.sendMessage(Text.color(
"&6&lThemeParkMC &f➢ You have ridden attraction: &f"+attraction.getID()+" &ffor &6"+(count == null ? 0 : count.getCount())+"x"
));
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.commands.subcommands.status;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.arguments.StringArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class StatusColorCommand extends SubCommand {
public StatusColorCommand() {
super("themepark.admin", "status", "color");
addSyntax("/themepark status color <id> <color>")
.addArgument(new EnumArgument(Status.values()))
.addArgument(new StringArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Status status = (Status) list.get(0);
String color = (String) list.get(1);
status.setColor(color);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the color of status &f"+status.toString()));
}
}

View file

@ -0,0 +1,15 @@
package nl.iobyte.themepark.commands.subcommands.status;
import nl.iobyte.commandapi.CommandFactory;
public class StatusCommands {
public static void load(CommandFactory factory) {
factory.addSubCommand(new StatusNameCommand())
.addSubCommand(new StatusColorCommand())
.addSubCommand(new StatusHexColorCommand())
.addSubCommand(new StatusMaterialCommand())
.addSubCommand(new StatusTeleportCommand());
}
}

View file

@ -0,0 +1,36 @@
package nl.iobyte.themepark.commands.subcommands.status;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.arguments.StringArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class StatusHexColorCommand extends SubCommand {
public StatusHexColorCommand() {
super("themepark.admin", "status", "hex_color");
addSyntax("/themepark status hex_color <id> <color>")
.addArgument(new EnumArgument(Status.values()))
.addArgument(new StringArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Status status = (Status) list.get(0);
String hex_color = (String) list.get(1);
status.setHexColor(hex_color);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the hex color of status &f"+status.toString()));
}
}

View file

@ -0,0 +1,53 @@
package nl.iobyte.themepark.commands.subcommands.status;
import com.cryptomorin.xseries.XMaterial;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.arguments.MaterialArgument;
import nl.iobyte.commandapi.arguments.number.ShortArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class StatusMaterialCommand extends SubCommand {
public StatusMaterialCommand() {
super("themepark.admin", "status", "material");
addSyntax("/themepark status material <status> <material>")
.addArgument(new EnumArgument(Status.values()))
.addArgument(new MaterialArgument());
addSyntax("/themepark status material <status> <material> <data>")
.addArgument(new EnumArgument(Status.values()))
.addArgument(new MaterialArgument())
.addArgument(new ShortArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Status status = (Status) list.get(0);
XMaterial material;
if(i == 0) {
material = XMaterial.matchXMaterial((Material) list.get(1));
} else {
material = XMaterial.matchXMaterial(list.get(1).toString()+":"+list.get(2).toString()).orElse(null);
if(material == null) {
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &4Unable to parse specified material:data"));
return;
}
}
status.setMaterial(material);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the material of status &f"+status.toString()));
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.commands.subcommands.status;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.arguments.MessageArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class StatusNameCommand extends SubCommand {
public StatusNameCommand() {
super("themepark.admin", "status", "name");
addSyntax("/themepark status name <id> <name>")
.addArgument(new EnumArgument(Status.values()))
.addArgument(new MessageArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Status status = (Status) list.get(0);
String name = (String) list.get(1);
status.setName(name);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed the name of status &f"+status.toString()));
}
}

View file

@ -0,0 +1,35 @@
package nl.iobyte.themepark.commands.subcommands.status;
import nl.iobyte.commandapi.arguments.BooleanArgument;
import nl.iobyte.commandapi.arguments.EnumArgument;
import nl.iobyte.commandapi.interfaces.SubCommand;
import nl.iobyte.themepark.api.attraction.enums.Status;
import nl.iobyte.themepark.api.message.Text;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class StatusTeleportCommand extends SubCommand {
public StatusTeleportCommand() {
super("themepark.admin", "status", "teleport");
addSyntax("/themepark status teleport <id> <teleport>")
.addArgument(new EnumArgument(Status.values()))
.addArgument(new BooleanArgument());
}
@Override
public void onPlayerCommand(Player player, List<Object> list, int i) {
onConsoleCommand(player, list, i);
}
@Override
public void onConsoleCommand(CommandSender sender, List<Object> list, int i) {
Status status = (Status) list.get(0);
boolean b = (boolean) list.get(1);
status.setCanTeleport(b);
sender.sendMessage(Text.color("&6&lThemeParkMC &f➢ &aSuccessfully changed if status &f"+status.toString()+" &acan teleport"));
}
}

View file

@ -0,0 +1,212 @@
package nl.iobyte.themepark.listeners;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.attraction.AttractionService;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.config.objects.Configuration;
import nl.iobyte.themepark.api.event.attraction.*;
import nl.iobyte.themepark.utils.LocationUtil;
import nl.iobyte.themepark.utils.StatusMessage;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.util.HashMap;
public class AttractionListener implements Listener {
@EventHandler
public void onCreate(AttractionCreateEvent e) {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
Attraction attraction = e.getAttraction();
Region region = api.getAttractionService().getRegion(
attraction.getRegionID()
);
//Add to Region's config
String path = "attractions."+attraction.getID();
Configuration config = region.getConfiguration();
config.set(path+".name", attraction.getName());
config.set(path+".cover", attraction.getCover());
config.set(path+".status", attraction.getStatus().toString());
config.set(path+".location", LocationUtil.toString(attraction.getLocation()));
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().load();
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"INSERT IGNORE INTO attractions(id, region_id, name, cover, status_id) VALUES (?,?,?,?,?)",
new HashMap<Integer, Object>() {{
put(1, attraction.getID());
put(2, attraction.getRegionID());
put(3, attraction.getName());
put(4, attraction.getCover());
put(5, attraction.getStatus().getID());
}}
);
}
@EventHandler
public void onRegionChange(AttractionRegionChangeEvent e) {
Attraction attraction = e.getAttraction();
AttractionService service = ThemePark.getInstance().getAPI().getAttractionService();
//Remove from old Region
Region region = service.getRegion(e.getOld());
region.removeAttraction(attraction.getID());
//Remove from old Region's config
Configuration config = region.getConfiguration();
config.set("attractions."+attraction.getID(), null);
//Add to new Region
region = service.getRegion(e.getCurrent());
region.addAttraction(attraction);
//Add to new Region's config
String path = "attractions."+attraction.getID();
config = region.getConfiguration();
config.set(path+".name", attraction.getName());
config.set(path+".cover", attraction.getCover());
config.set(path+".status", attraction.getStatus().toString());
config.set(path+".location", LocationUtil.toString(attraction.getLocation()));
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().load();
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"UPDATE attractions SET region_id=? WHERE id=?",
new HashMap<Integer, Object>() {{
put(1, e.getCurrent());
put(2, attraction.getID());
}}
);
}
@EventHandler
public void onNameChange(AttractionNameChangeEvent e) {
Attraction attraction = e.getAttraction();
Region region = ThemePark.getInstance().getAPI().getAttractionService().getRegion(
attraction.getRegionID()
);
//Change name in Region's config
Configuration config = region.getConfiguration();
config.set("attractions."+attraction.getID()+".name", e.getCurrent());
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().updateAttraction(attraction);
//Update Sign
ThemePark.getInstance().getAPI().getSignManager().update(attraction);
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"UPDATE attractions SET name=? WHERE id=?",
new HashMap<>() {{
put(1, e.getCurrent());
put(2, attraction.getID());
}}
);
}
@EventHandler
public void onCoverChange(AttractionCoverChangeEvent e) {
Attraction attraction = e.getAttraction();
Region region = ThemePark.getInstance().getAPI().getAttractionService().getRegion(
attraction.getRegionID()
);
//Change cover in Region's config
Configuration config = region.getConfiguration();
config.set("attractions."+attraction.getID()+".cover", e.getCurrent());
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"UPDATE attractions SET cover=? WHERE id=?",
new HashMap<Integer, Object>() {{
put(1, e.getCurrent());
put(2, attraction.getID());
}}
);
}
@EventHandler
public void onStatusChange(AttractionStatusChangeEvent e) {
Attraction attraction = e.getAttraction();
Region region = ThemePark.getInstance().getAPI().getAttractionService().getRegion(
attraction.getRegionID()
);
//Change status in Region's config
Configuration config = region.getConfiguration();
config.set("attractions."+attraction.getID()+".status", e.getCurrent().toString());
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().updateAttraction(attraction);
//Update Sign
ThemePark.getInstance().getAPI().getSignManager().update(attraction);
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"UPDATE attractions SET status_id=? WHERE id=?",
new HashMap<>() {{
put(1, e.getCurrent().getID());
put(2, attraction.getID());
}}
);
//Send Message
StatusMessage.broadcast(attraction);
}
@EventHandler
public void onLocationChange(AttractionLocationChangeEvent e) {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
Attraction attraction = e.getAttraction();
Region region = api.getAttractionService().getRegion(
attraction.getRegionID()
);
//Change location in Region's config
Configuration config = region.getConfiguration();
config.set("attractions."+attraction.getID()+".location", LocationUtil.toString(e.getCurrent()));
}
@EventHandler
public void onRemove(AttractionRemoveEvent e) {
ThemeParkAPI api = ThemePark.getInstance().getAPI();
Attraction attraction = e.getAttraction();
Region region = api.getAttractionService().getRegion(
attraction.getRegionID()
);
//Remove from Region's config
Configuration config = region.getConfiguration();
config.set("attractions."+attraction.getID(), null);
//Update Menu
api.getMenuService().getStatusMenu().load();
//Update Sign
ThemePark.getInstance().getAPI().getSignManager().remove(attraction);
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"DELETE attractions, ridecounts FROM attractions LEFT JOIN attractions.id=ridecounts.attraction_id WHERE attractions.id=?",
new HashMap<>() {{
put(1, attraction.getID());
}}
);
}
}

View file

@ -0,0 +1,54 @@
package nl.iobyte.themepark.listeners;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.AttractionService;
import nl.iobyte.themepark.api.attraction.objects.Attraction;
import nl.iobyte.themepark.api.event.objects.AttractionEvent;
import nl.iobyte.themepark.api.event.objects.RegionEvent;
import nl.iobyte.themepark.api.event.objects.StatusEvent;
import nl.iobyte.themepark.api.menu.objects.StatusMenu;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class GeneralListener implements Listener {
@EventHandler
public void onRegion(RegionEvent<?> e) {
StatusMenu menu = ThemePark.getInstance().getAPI().getMenuService().getStatusMenu();
if(e.getCurrent() == null) {
menu.load();
return;
}
menu.updateRegion(e.getRegion());
}
@EventHandler
public void onAttraction(AttractionEvent<?> e) {
StatusMenu menu = ThemePark.getInstance().getAPI().getMenuService().getStatusMenu();
if(e.getCurrent() == null) {
menu.load();
return;
}
String name = e.getEventName();
if(name.contains("Location") || name.contains("Cover"))
return;
menu.updateAttraction(e.getAttraction());
}
@EventHandler
public void onStatus(StatusEvent<?> e) {
String name = e.getEventName();
if(!name.contains("Name") && !name.contains("Color"))
return;
StatusMenu menu = ThemePark.getInstance().getAPI().getMenuService().getStatusMenu();
AttractionService service = ThemePark.getInstance().getAPI().getAttractionService();
for(Attraction attraction : service.getAttractions().values())
if(attraction.getStatus() == e.getStatus())
menu.updateAttraction(attraction);
}
}

View file

@ -0,0 +1,208 @@
package nl.iobyte.themepark.listeners;
import nl.iobyte.menuapi.item.ItemBuilder;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.ThemeParkAPI;
import nl.iobyte.themepark.api.config.ConfigurationManager;
import nl.iobyte.themepark.api.config.enums.StorageKey;
import nl.iobyte.themepark.api.message.Text;
import nl.iobyte.themepark.scheduler.ThemeParkScheduler;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.*;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public class PlayerListener implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
ThemeParkAPI api = ThemePark.getInstance().getAPI();
//Handle Menu item onJoin
doItem(player);
//Load RideCount data
Calendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
api.getDatabaseService().executeQueryAsync(
"local",
"SELECT count, attraction_id, (SELECT sum(count) FROM counts AS t1 WHERE t1.uuid=t2.uuid AND t1.attraction_id=t2.attraction_id AND t1.year=t2.year AND t1.month=? GROUP BY t1.uuid) AS total_count FROM counts AS t2 WHERE uuid=? AND year=? AND day=?",
new HashMap<>() {{
put(1, calendar.get(Calendar.MONTH));
put(2, player.getUniqueId().toString());
put(3, calendar.get(Calendar.YEAR));
put(4, calendar.get(Calendar.DAY_OF_YEAR));
}}
).setWhenSuccessful(result -> {
if(result != null)
for(Map<String, Object> row : result)
api.getRideCountService().setCount(
(String) row.get("attraction_id"),
player.getUniqueId(),
(int) row.get("count"),
(int) (row.get("total_count") == null ? row.get("count") : row.get("total_count"))
);
});
}
@EventHandler
public void onSwitch(PlayerChangedWorldEvent e) {
//Handle Menu item onSwitch
doItem(e.getPlayer());
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
Player player = e.getPlayer();
UUID uuid = player.getUniqueId();
//Clear Unwanted RideCount
ThemeParkScheduler.runAsync(() -> ThemePark.getInstance().getAPI().getRideCountService().clearCount(uuid));
}
//Handle Menu item
@EventHandler
public void onInteract(PlayerInteractEvent e) {
if(e.getItem() == null)
return;
ConfigurationManager manager = ThemePark.getInstance().getAPI().getConfigurationManager();
Material material = Material.getMaterial(manager.getString(StorageKey.MENU_ITEM_MATERIAL));
ItemStack item = e.getItem();
if(item.getType() != material)
return;
if(!item.hasItemMeta())
return;
String name = Text.color(manager.getString(StorageKey.MENU_ITEM_NAME));
if(!item.getItemMeta().getDisplayName().equals(name))
return;
if(e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK)
return;
e.setCancelled(true);
Player player = e.getPlayer();
ThemePark.getInstance().getAPI().getMenuService().getMainMenu().open(player);
}
//Handle Menu item drop
@EventHandler
public void onDrop(PlayerDropItemEvent e) {
Player player = e.getPlayer();
if(player.hasPermission("themepark.admin"))
return;
ConfigurationManager manager = ThemePark.getInstance().getAPI().getConfigurationManager();
if(!manager.getBoolean(StorageKey.MENU_ITEM_ENABLED))
return;
Material material = Material.getMaterial(manager.getString(StorageKey.MENU_ITEM_MATERIAL));
ItemStack item = e.getItemDrop().getItemStack();
if(item.getType() != material)
return;
if(!item.hasItemMeta())
return;
String name = Text.color(manager.getString(StorageKey.MENU_ITEM_NAME));
if(!item.getItemMeta().getDisplayName().equals(name))
return;
e.setCancelled(true);
}
@EventHandler
public void onClick(InventoryClickEvent e) {
Player player = (Player) e.getWhoClicked();
if(player.hasPermission("themepark.admin"))
return;
Inventory inventory = e.getClickedInventory();
if(inventory.getType() != InventoryType.PLAYER)
return;
ConfigurationManager manager = ThemePark.getInstance().getAPI().getConfigurationManager();
if(!manager.getBoolean(StorageKey.MENU_ITEM_ENABLED))
return;
ItemStack item = e.getCursor();
if(item == null)
return;
Material material = Material.getMaterial(manager.getString(StorageKey.MENU_ITEM_MATERIAL));
if(item.getType() != material)
return;
if(!item.hasItemMeta())
return;
String name = Text.color(manager.getString(StorageKey.MENU_ITEM_NAME));
if(!item.getItemMeta().getDisplayName().equals(name))
return;
e.setCancelled(true);
}
/**
* Called on join / world switch
* @param player Player
*/
private void doItem(Player player) {
ConfigurationManager manager = ThemePark.getInstance().getAPI().getConfigurationManager();
CompletableFuture<ItemStack> fc = new CompletableFuture<>();
Bukkit.getScheduler().runTaskAsynchronously(ThemePark.getInstance(), () -> {
if(!manager.getBoolean(StorageKey.MENU_ITEM_ENABLED)) {
fc.complete(null);
return;
}
Material material = Material.getMaterial(manager.getString(StorageKey.MENU_ITEM_MATERIAL));
short data = Short.parseShort(manager.getString(StorageKey.MENU_ITEM_DATA));
String name = Text.color(manager.getString(StorageKey.MENU_ITEM_NAME));
if(material == null || name.isEmpty()) {
fc.complete(null);
return;
}
ItemBuilder builder = new ItemBuilder(material, 1, data);
builder.setName(name);
if(manager.getBoolean(StorageKey.MENU_ITEM_CLEAR))
player.getInventory().clear();
List<String> worlds = manager.getStringList(StorageKey.MENU_ITEM_WORLDS);
if(worlds != null && !worlds.isEmpty()) {
if (worlds.contains(player.getLocation().getWorld().getName())) {
fc.complete(new ItemStack(Material.AIR));
return;
}
}
fc.complete(builder.getItem());
});
fc.thenAccept(item -> {
if(item == null)
return;
int slot = manager.getInt(StorageKey.MENU_ITEM_SLOT);
player.getInventory().setItem(slot, item);
player.updateInventory();
});
}
}

View file

@ -0,0 +1,90 @@
package nl.iobyte.themepark.listeners;
import nl.iobyte.themepark.ThemePark;
import nl.iobyte.themepark.api.attraction.objects.Region;
import nl.iobyte.themepark.api.config.enums.StorageLocation;
import nl.iobyte.themepark.api.event.region.RegionCreateEvent;
import nl.iobyte.themepark.api.event.region.RegionNameChangeEvent;
import nl.iobyte.themepark.api.event.region.RegionRemoveEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.util.HashMap;
public class RegionListener implements Listener {
@EventHandler
public void onCreate(RegionCreateEvent e) {
Region region = e.getRegion();
//Add Region to config
ThemePark.getInstance().getAPI().getConfigurationManager().set(
StorageLocation.REGIONS,
"regions."+region.getID()+".name",
region.getName()
);
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().load();
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"INSERT IGNORE INTO regions(id, name) VALUES (?,?)",
new HashMap<>() {{
put(1, region.getID());
put(2, region.getName());
}}
);
}
@EventHandler
public void onNameChange(RegionNameChangeEvent e) {
Region region = e.getRegion();
//Change Region name in config
ThemePark.getInstance().getAPI().getConfigurationManager().set(
StorageLocation.REGIONS,
"regions."+region.getID()+".name",
region.getName()
);
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().updateRegion(region);
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"UPDATE regions SET name=? WHERE id=?",
new HashMap<>() {{
put(1, region.getName());
put(2, region.getID());
}}
);
}
@EventHandler
public void onRemove(RegionRemoveEvent e) {
Region region = e.getRegion();
region.getConfiguration().delete();
//Remove Region from config
ThemePark.getInstance().getAPI().getConfigurationManager().set(
StorageLocation.REGIONS,
"regions."+region.getID(),
null
);
//Update Menu
ThemePark.getInstance().getAPI().getMenuService().getStatusMenu().load();
//Update MySQL Database
ThemePark.getInstance().getAPI().getDatabaseService().executeAsync(
"remote",
"DELETE regions, attractions, ridecounts FROM regions LEFT JOIN attractions ON regions.id=attractions.region_id LEFT JOIN ridecounts ON attractions.id=ridecounts.attraction_id WHERE regions.id=?",
new HashMap<>() {{
put(1, region.getID());
}}
);
}
}

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