Add custom item costs

Refactor code
This commit is contained in:
Jakub Kolář 2016-04-15 23:30:08 +02:00
parent ec1d71680a
commit 6c50eaf6c4
57 changed files with 3593 additions and 1349 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
*.iml
*.jar
/target/
/.classpath
/.project

18
jar/all-jar.xml Normal file
View File

@ -0,0 +1,18 @@
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>boosCooldowns</id>
<formats>
<format>jar</format> <!-- the result is a jar file -->
</formats>
<includeBaseDirectory>false</includeBaseDirectory> <!-- strip the module prefixes -->
<dependencySets>
<dependencySet>
<unpack>true</unpack> <!-- unpack , then repack the jars -->
<useTransitiveDependencies>false</useTransitiveDependencies> <!-- do not pull in any transitive dependencies -->
</dependencySet>
</dependencySets>
</assembly>

78
jar/pom.xml Normal file
View File

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jar</artifactId>
<dependencies>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_8_R3</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_9_R1</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_8_R1</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_8_R2</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>plugin</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>package-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<finalName>boosCooldowns</finalName>
<descriptors>
<descriptor>all-jar.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

55
nms/NMS/pom.xml Normal file
View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>NMS</artifactId>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>${minecraft.version}-${bukkit.version}-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!--Bukkit API-->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>${minecraft.version}-${bukkit.version}-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_8_R3</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_9_R1</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_8_R1</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS_hook_1_8_R2</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,83 @@
package nms;
import org.bukkit.plugin.Plugin;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMS {
private static NMSHook hook;
private static String version;
private static boolean compatible = false;
/**
* Gets the server version and adjusts this API accordingly.
*
* @param pl (Plugin) - the instance of your plugin
* @return (NMSSetupResponse) - the setup response.
*/
public static NMSSetupResponse setup(Plugin pl) {
String version;
try {
version = pl.getServer().getClass().getPackage().getName().replace('.', ',').split(",")[3];
} catch (ArrayIndexOutOfBoundsException e) {
return new NMSSetupResponse(null, false);
}
if (version.equals("v1_9_R1")) {
hook = new NMSHook_v1_9_R1();
} else if (version.equals("v1_8_R3")) {
hook = new NMSHook_v1_8_R3();
} else if (version.equals("v1_8_R2")) {
hook = new NMSHook_v1_8_R2();
} else if (version.equals("v1_8_R1")) {
hook = new NMSHook_v1_8_R1();
}
compatible = hook != null;
return new NMSSetupResponse(version, compatible);
}
/**
* Gets the NMS hook, if NMS is hooked.
*
* @return (NMSHook) - the NMSHook.
* @throws NMSNotHookedException if NMS is not hooked (by using {@link #setup(Plugin)})
*/
public static NMSHook getHook()
throws NMSNotHookedException {
if (!compatible) {
throw new NMSNotHookedException();
}
return hook;
}
/**
* Gets the found server version.
*
* @return (String) - the server version in form of "v1_9_R1" or null
*/
public static String getVersion() {
return version;
}
/**
* Checks whether this API is compatible with the found server version.
*
* @return
*/
public static boolean isCompatibleVersionFound() {
return compatible;
}
}

View File

@ -0,0 +1,28 @@
package nms;
import org.bukkit.entity.Player;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public interface NMSHook {
/**
* Sends a JSON message to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendJSON(String json, Player player);
/**
* Sends an actionbar to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendActionBar(String json, Player player);
}

View File

@ -0,0 +1,20 @@
package nms;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMSNotHookedException
extends Exception {
/**
*
*/
private static final long serialVersionUID = -1482736539139159745L;
public NMSNotHookedException() {
super("NMS not hooked!");
}
}

View File

@ -0,0 +1,36 @@
package nms;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMSSetupResponse {
private String version;
private boolean compatible;
protected NMSSetupResponse(String version, boolean compatible) {
this.version = version;
this.compatible = compatible;
}
/**
* Gets the found server version in form of "v1_9_R1".
*
* @return (String) - the server version or null if it's not found.
*/
public String getVersion() {
return version;
}
/**
* Gets if the found server version is compatible with this API.
*
* @return
*/
public boolean isCompatible() {
return compatible;
}
}

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>NMS_hook_1_8_R1</artifactId>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
package nms;
import org.bukkit.entity.Player;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public interface NMSHook {
/**
* Sends a JSON message to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendJSON(String json, Player player);
/**
* Sends an actionbar to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendActionBar(String json, Player player);
}

View File

@ -0,0 +1,25 @@
package nms;
import org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_8_R1.ChatSerializer;
import net.minecraft.server.v1_8_R1.PacketPlayOutChat;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMSHook_v1_8_R1
implements NMSHook {
public void sendJSON(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json)));
}
public void sendActionBar(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json), (byte) 2));
}
}

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>NMS_hook_1_8_R2</artifactId>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8.3-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
package nms;
import org.bukkit.entity.Player;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public interface NMSHook {
/**
* Sends a JSON message to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendJSON(String json, Player player);
/**
* Sends an actionbar to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendActionBar(String json, Player player);
}

View File

@ -0,0 +1,25 @@
package nms;
import org.bukkit.craftbukkit.v1_8_R2.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_8_R2.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_8_R2.PacketPlayOutChat;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMSHook_v1_8_R2
implements NMSHook {
public void sendJSON(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json)));
}
public void sendActionBar(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json), (byte) 2));
}
}

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>NMS_hook_1_8_R3</artifactId>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
package nms;
import org.bukkit.entity.Player;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public interface NMSHook {
/**
* Sends a JSON message to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendJSON(String json, Player player);
/**
* Sends an actionbar to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendActionBar(String json, Player player);
}

View File

@ -0,0 +1,25 @@
package nms;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_8_R3.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_8_R3.PacketPlayOutChat;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMSHook_v1_8_R3
implements NMSHook {
public void sendJSON(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json)));
}
public void sendActionBar(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json), (byte) 2));
}
}

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>NMS_hook_1_9_R1</artifactId>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.9.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,28 @@
package nms;
import org.bukkit.entity.Player;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public interface NMSHook {
/**
* Sends a JSON message to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendJSON(String json, Player player);
/**
* Sends an actionbar to a player.
*
* @param json (String) - the plain JSON
* @param player (Player) - the player
*/
public void sendActionBar(String json, Player player);
}

View File

@ -0,0 +1,29 @@
package nms;
import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_9_R1.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_9_R1.PacketPlayOutChat;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class NMSHook_v1_9_R1
implements NMSHook {
public void sendJSON(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json)));
}
public void sendActionBar(String json, Player player) {
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutChat(ChatSerializer.a(json), (byte) 2));
}
}

73
plugin/pom.xml Normal file
View File

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>boosCooldowns</artifactId>
<groupId>cz.boosik</groupId>
<relativePath>../pom.xml</relativePath>
<version>${boosCooldowns.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>plugin</artifactId>
<dependencies>
<!--Spigot API-->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>${minecraft.version}-${bukkit.version}-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>${minecraft.version}-${bukkit.version}-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!--Bukkit API-->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>${minecraft.version}-${bukkit.version}-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>cz.boosik</groupId>
<artifactId>NMS</artifactId>
<version>3.11.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>plugin</finalName>
<sourceDirectory>${basedir}/src/main/java/</sourceDirectory>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,289 @@
package com.coloredcarrot.mcapi.json;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import nms.NMS;
import nms.NMSNotHookedException;
import nms.NMSSetupResponse;
/**
* A JSON Object is the base for any JSON message using this library.
* It contains one or more JSONComponentSimple Objects used to make up the whole JSON message.
* All rights reserved,
*
* @author ColoredCarrot
* @see JSONComponentSimple
*/
public class JSON {
private List<JSONComponentSimple> components = new ArrayList<JSONComponentSimple>();
private String generatedJSON;
private boolean generated;
/**
* Constructs a new JSON Object with a base JSONComponentSimple Object.
*
* @param JSONComponentSimple (JSONComponentSimple) - the base JSONComponentSimple Object
*/
public JSON(JSONComponentSimple jsonComponent) {
if (jsonComponent == null) {
throw new IllegalArgumentException("component cannot be null!");
}
components.add(jsonComponent);
generatedJSON = "";
generated = false;
}
/**
* Constructs a new JSON Object with already containing multiple JSONComponentSimple Objects.
*
* @param components (JSONComponentSimple[]) - the JSONComponentSimple Objects
*/
public JSON(JSONComponentSimple... components) {
if (components == null) {
throw new IllegalArgumentException("component cannot be null!");
}
if (components.length > 0) {
for (JSONComponentSimple component : components) {
this.components.add(component);
}
}
generatedJSON = "";
generated = false;
}
/**
* This method needs to be called in the onEnable() method.
*
* @see NMS#setup()
*/
public static NMSSetupResponse setup(Plugin pl) {
return NMS.setup(pl);
}
/**
* Sends a JSON message to a player.
*
* @param to (Player) - the player to send the message to
* @param json (String) - the raw JSON to send
*/
public static void sendJSON(Player to, String json) {
if (to == null) {
throw new IllegalArgumentException("player cannot be null!");
}
if (json == null) {
throw new IllegalArgumentException("json cannot be null!");
}
try {
NMS.getHook().sendJSON(json, to);
} catch (NMSNotHookedException e) {
e.printStackTrace();
}
}
/**
* Sends a JSON Object to a player.
* This method is in no way different from sendJSON(Player, String); in fact, it actually calls it.
*
* @param to (Player) - the player to send the message to
* @param json (JSON) - the JSON Object to send
*/
public static void sendJSON(Player to, JSON json) {
sendJSON(to, json.get());
}
/**
* Combines multiple JSON Objects into a single one, using .clone() on all components.
*
* @param jsons (JSON[]) - the JSON Objects to combine
* @return (JSON) - the combined JSON.
*/
public static JSON combineToNewJSON(JSON... jsons) {
JSON baseJSON;
baseJSON = (JSON) jsons[0].clone();
for (int i = 1; i < jsons.length; i++) {
for (JSONComponentSimple comp : jsons[i].getComponents()) {
baseJSON.add(comp.clone());
}
}
return baseJSON;
}
/**
* returns a new JSON Object, invoking .clone() on all JSONComponentSimple Objects in this JSON Object.
*/
@Override
public JSON clone() {
JSONComponentSimple[] comps = new JSONComponentSimple[components.size()];
for (int i = 0; i < components.size(); i++) {
comps[i] = components.get(i).clone();
}
return new JSON(comps);
}
/**
* Adds a JSONComponentSimple to this JSON Object.
*
* @param component (JSONComponentSimple) - the JSONComponentSimple to add.
* @return (JSON) - this JSON Object, for chaining.
*/
public JSON add(JSONComponentSimple component) {
if (component == null) {
throw new IllegalArgumentException("component cannot be null!");
}
components.add(component);
generated = false;
return this;
}
/**
* Removes a JSONComponentSimple from this JSON Object.
*
* @param component (JSONComponentSimple) - the JSONComponentSimple to remove.
* @return (JSON) - this JSON Object, for chaining.
*/
public JSON remove(JSONComponentSimple component) {
if (component == null) {
throw new IllegalArgumentException("component cannot be null!");
}
components.remove(component);
generated = false;
return this;
}
/**
* Gets all the JSONComponentSimple Objects included in this JSON Object.
*
* @return (List: JSONComponentSimple) - all JSONComponentSimple Objects.
*/
public List<JSONComponentSimple> getComponents() {
return components;
}
/**
* Combines this JSON Object with other JSON Objects.
* Be careful; this doesn't invoke .clone() !
*
* @param jsons (JSON[]) - the JSON Objects to add to this one
* @return JSON - this JSON Object, with all other JSON Objects added.
*/
public JSON combine(JSON... jsons) {
for (JSON json : jsons) {
for (JSONComponentSimple component : json.getComponents()) {
this.add(component);
}
}
return this;
}
/**
* Generates the JSON String.
* You should have no need to use this method as it's automatically called on get() and send(Player).
*
* @return (JSON) - this JSON Object, for chaining.
*/
public JSON generate() {
generatedJSON = "{\"text\":\"\",\"extra\":[";
for (JSONComponentSimple component : components) {
generatedJSON += component.get() + ",";
}
generatedJSON = generatedJSON.substring(0, generatedJSON.length() - 1) + "]}";
generated = true;
return this;
}
/**
* Generates and then returns the raw JSON message.
*
* @return (String) - the raw JSON matching this JSON Object.
*/
public String get() {
if (!generated) {
generate();
}
return generatedJSON;
}
/**
* Generates and then sends the raw JSON matching this JSON Object to a player.
*
* @param player (Player) - the player to send the message to
* @return (JSON) - this JSON Object, for chaining.
*/
public JSON send(Player player) {
if (player == null) {
throw new IllegalArgumentException("player cannot be null!");
}
sendJSON(player, get());
return this;
}
/**
* Returns a non-JSON version of this JSON Object. Does not contain hover- or click actions.
*
* @return (String) - the ChatColor version
* @see JSONComponentSimple#getChatColorVersion()
*/
public String getChatColorVersion() {
String s = "";
for (JSONComponentSimple comp : components) {
s += ChatColor.RESET + comp.getChatColorVersion();
}
return s;
}
}

View File

@ -0,0 +1,192 @@
package com.coloredcarrot.mcapi.json;
/**
* Represents a click action.
* All rights reserved.
*
* @param <T> - the Type of the value associated with the class implementing this interface
* @author ColoredCarrot
* @see {@link #getValue()}, {@link #setValue(Object)}
*/
public interface JSONClickAction<T> {
/**
* Gets the value associated with this JSONClickAction.
*
* @return (?) - the value.
* @see #setValue(Object)
*/
public T getValue();
/**
* Sets the value of this JSONClickAction.
*
* @param newValue (?) - the new value
* @return (JSONHoverAction: ?) - this JSONClickAction Object, for chaining.
*/
public JSONClickAction<T> setValue(T newValue);
/**
* Gets the value associated with this JSONClickAction transformed to a String.
*
* @return (String) - the value as a String.
* @see #getValue()
*/
public String getValueString();
/**
* Gets the action name associated with this JSONClickAction.
* Example: "run_command"
*
* @return (String) - the action name.
*/
public String getActionName();
/**
* Runs a command as the player who clicks on the text in the chat.
*/
public class RunCommand
implements JSONClickAction<String> {
/**
* The action name
*
* @see #getActionName()
*/
public static final String NAME = "run_command";
private String value;
/**
* Constructs a {@link JSONClickAction.RunCommand}.
*
* @param value (String) - the value associated with this JSONClickAction
*/
public RunCommand(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public JSONClickAction<String> setValue(String newValue) {
value = newValue;
return this;
}
@Override
public String getValueString() {
return "\"" + value + "\"";
}
@Override
public String getActionName() {
return NAME;
}
}
/**
* Pastes a command in the chat of the player who clicks on the text in the chat.
*/
public class SuggestCommand
implements JSONClickAction<String> {
/**
* The action name
*
* @see #getActionName()
*/
public static final String NAME = "suggest_command";
private String value;
/**
* Constructs a {@link JSONClickAction.SuggestCommand}.
*
* @param value (String) - the value associated with this JSONClickAction
*/
public SuggestCommand(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public JSONClickAction<String> setValue(String newValue) {
value = newValue;
return this;
}
@Override
public String getValueString() {
return "\"" + value + "\"";
}
@Override
public String getActionName() {
return NAME;
}
}
/**
* Opens a URL in the default browser of the player who clicks on the text in the chat.
*/
public class OpenURL
implements JSONClickAction<String> {
/**
* The action name
*
* @see #getActionName()
*/
public static final String NAME = "open_url";
private String value;
/**
* Constructs a {@link JSONClickAction.OpenURL}.
*
* @param value (String) - the value associated with this JSONClickAction
*/
public OpenURL(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public JSONClickAction<String> setValue(String newValue) {
value = newValue;
return this;
}
@Override
public String getValueString() {
return ("\"" + value + "\"").replace(" ", "%20");
}
@Override
public String getActionName() {
return NAME;
}
}
}

View File

@ -0,0 +1,64 @@
package com.coloredcarrot.mcapi.json;
import org.bukkit.ChatColor;
/**
* An enum representing a Color that is accepted in the JSON message format.
* All rights reserved.
*
* @author ColoredCarrot
* @see {@link JSONComponent#setColor(JSONColor)}, {@link JSONComponent#getColor()}
*/
public enum JSONColor {
AQUA("&b"),
BLACK("&0"),
BLUE("&9"),
DARK_AQUA("&3"),
DARK_BLUE("&1"),
DARK_GRAY("&8"),
DARK_GREEN("&2"),
DARK_PURPLE("&5"),
DARK_RED("&4"),
GOLD("&6"),
GRAY("&7"),
GREEN("&a"),
LIGHT_PURPLE("&d"),
RED("&c"),
WHITE("&f"),
YELLOW("&e");
private final String code;
JSONColor(String code) {
this.code = code;
}
public static JSONColor fromString(String text) {
if (text != null) {
for (JSONColor b : JSONColor.values()) {
if (text.equalsIgnoreCase(b.code)) {
return b;
}
}
}
return null;
}
public String getCode() {
return code;
}
/**
* Transforms super.toString() into lowercase letters which are accepted by the JSON message format.
*/
@Override
public String toString() {
return super.toString().toLowerCase();
}
public ChatColor toChatColor() {
return ChatColor.valueOf(name());
}
}

View File

@ -0,0 +1,114 @@
package com.coloredcarrot.mcapi.json;
/**
* All rights reserved.
*
* @author ColoredCarrot
*/
public class JSONComponent
extends JSONComponentSimple {
private JSONHoverAction<?> hoverAction;
private JSONClickAction<?> clickAction;
public JSONComponent(String text) {
super(text);
}
/**
* Constructs a new JSONComponent with all the attributes this one has.
*/
@Override
public JSONComponent clone() {
return (JSONComponent) new JSONComponent(getText())
.setHoverAction(hoverAction)
.setClickAction(clickAction)
.setColor(getColor())
.setBold(isBold())
.setItalic(isItalic())
.setStrikethrough(isStrikethrough())
.setUnderlined(isUnderlined())
.setObfuscated(isObfuscated());
}
/**
* Generates the raw json message matching this JSONComponent.
* Generally speaking, you should not have a use for this method as get() calls it as well.
*
* @return (JSONComponent) - this JSONComponent Object, for chaining.
* @see JSONComponent#get()
*/
@Override
public JSONComponent generate() {
super.generate();
generatedJSON = generatedJSON.substring(0, generatedJSON.length() - 1);
if (hoverAction != null) {
generatedJSON += ",\"hoverEvent\":{\"action\":\"" + hoverAction.getActionName() + "\",\"value\":\"" + hoverAction.getValueString() + "}";
}
if (clickAction != null) {
generatedJSON += ",\"clickEvent\":{\"action\":\"" + clickAction.getActionName() + "\",\"value\":" + clickAction.getValueString() + "}";
}
generatedJSON += "}";
return this;
}
/**
* Gets the hover action for this JSONComponent.
*
* @return (JSONHoverAction: ?) - the hover action.
*/
public JSONHoverAction<?> getHoverAction() {
return hoverAction;
}
/**
* Sets the hover action for this JSONComponent.
*
* @param hoverAction (JSONHoverAction: ?) - the hover action
* @return (JSONComponent) - this JSONComponent Object, for chaining.
* @see #getHoverAction()
*/
public JSONComponent setHoverAction(JSONHoverAction<?> hoverAction) {
if (hoverAction == null) {
throw new IllegalArgumentException("hoverAction cannot be null!");
}
this.hoverAction = hoverAction;
super.generated = false;
return this;
}
/**
* Gets the click action for this JSONComponent.
*
* @return (JSONClickAction: ?) - the click action.
*/
public JSONClickAction<?> getClickAction() {
return clickAction;
}
/**
* Sets the click action for this JSONComponent.
*
* @param clickAction (JSONClickAction: ?) - the click action
* @return (JSONComponent) - this JSONComponent Object, for chaining.
* @see #getClickAction()
*/
public JSONComponent setClickAction(JSONClickAction<?> clickAction) {
if (clickAction == null) {
throw new IllegalArgumentException("clickAction cannot be null!");
}
this.clickAction = clickAction;
resetGenerationStatus();
return this;
}
}

View File

@ -0,0 +1,405 @@
package com.coloredcarrot.mcapi.json;
import org.bukkit.entity.Player;
import net.md_5.bungee.api.ChatColor;
/**
* The base class of the JSONComponent class.
* This class does not support hover and click actions.
* All rights reserved.
*
* @author ColoredCarrot
*/
public class JSONComponentSimple {
protected String generatedJSON;
protected boolean generated = false;
private String text;
private JSONColor color;
private boolean bold = false,
italic = false,
strikethrough = false,
underlined = false,
obfuscated = false;
/**
* Constructs a new JSONComponent with a given base text.
*
* @param text (String) - the base text this JSONComponent contains
*/
public JSONComponentSimple(String text) {
if (text == null) {
throw new IllegalArgumentException("text cannot be null!");
}
if (text.contains("|||")) {
throw new IllegalArgumentException("text cannot contain the following char sequence: |||");
}
this.text = text;
color = JSONColor.WHITE;
}
/**
* Generates a JSONComponent from a string following the following format:<br />
* {@code text|||color|||bold|||italic|||strikethrough|||underlined|||obfuscated}<br />
* <b>Important!</b> Hover and click action data is not supported!
*
* @param str (String) - the string generated by {@link JSONComponent#toString()}
* @return (JSONComponent) - the JSONComponent matching the String or null if the String is invalid.
* @see #toString()
*/
public static JSONComponentSimple fromString(String str) {
try {
String[] parts = str.split("|||");
if (parts == null || parts.length != 7) {
return null;
}
return new JSONComponentSimple(parts[0])
.setColor(JSONColor.valueOf(parts[1]))
.setBold(Boolean.valueOf(parts[2]))
.setItalic(Boolean.valueOf(parts[3]))
.setStrikethrough(Boolean.valueOf(parts[4]))
.setUnderlined(Boolean.valueOf(parts[5]))
.setObfuscated(Boolean.valueOf(parts[6]));
} catch (Exception e) {
return null;
}
}
/**
* Constructs a new JSONComponentSimple Object, with all the attributes this one has.
*/
@Override
public JSONComponentSimple clone() {
return new JSONComponentSimple(text)
.setColor(color)
.setBold(bold)
.setItalic(italic)
.setStrikethrough(strikethrough)
.setUnderlined(underlined)
.setObfuscated(obfuscated);
}
/**
* Generates the raw json message matching this JSONComponent.
* Generally speaking, you should not have a use for this method as get() calls it as well.
*
* @return (JSONComponent) - this JSONComponent Object, for chaining.
* @see JSONComponent#get()
*/
public JSONComponentSimple generate() {
generatedJSON = "{\"text\":\"" + text + "\",\"color\":\"" + color.toString() + "\",\"bold\":\"" + bold + "\",\"italic\":\"" + italic + "\",\"strikethrough\":\"" + strikethrough + "\",\"underlined\":\"" + underlined + "\",\"obfuscated\":\"" + obfuscated + "\"}";
generated = true;
return this;
}
/**
* Combines this JSONComponent with a number of other JSONComponents, creating a new JSON Object.
*
* @param withComponents (JSONComponent[]) - the JSONComponent Objects to combine this JSONComponent with
* @return (JSON) - a newly created JSON Object containing this and all specified JSONComponent Objects.
*/
public JSON combine(JSONComponentSimple... withComponents) {
JSON json = new JSON(this);
for (JSONComponentSimple with : withComponents) {
json.add(with);
}
return json;
}
/**
* Adds this JSONComponent to a JSON Object.
*
* @param json (JSON) - the JSON to add this JSONComponent to
* @return (JSONComponent) - this JSONComponent Object, for chaining.
* @see JSON#add(JSONComponent)
* @see JSONComponent#toJSON()
*/
public JSONComponentSimple addToJSON(JSON json) {
json.add(this);
return this;
}
/**
* Transforms this JSONComponent to a JSON Object.
*
* @return (JSON) - this JSONComponent as a JSON Object.
*/
public JSON toJSON() {
return new JSON(this);
}
/**
* Gets the raw JSON message of this JSONComponent.
*
* @return (String) - the raw JSON message.
*/
public String get() {
if (!generated) {
generate();
}
return generatedJSON;
}
/**
* Sends get() to a player.
*
* @param player (Player) - the player to send the message to
* @return (JSONComponent) - this JSONComponent Object, for chaining.
* @see JSONComponent_old#get()
*/
public JSONComponentSimple send(Player to) {
JSON.sendJSON(to, get());
return this;
}
/**
* Transforms this JSONComponent into a String readable by {@link JSONComponent#fromString(String)}.<br />
* It follows the following format:<br />
* {@code text|||color|||bold|||italic|||strikethrough|||underlined|||obfuscated}<br />
* <b>Important!</b> This will erase all hover and click action data!
*
* @see #fromString(String)
*/
@Override
public String toString() {
return text + "|||" + color.toString() + "|||" + bold + "|||" + italic + "|||" + strikethrough + "|||" + underlined + "|||" + obfuscated;
}
/**
* Returns a non-JSON version of this JSONComponentSimple, following the following pattern:
* ChatColor.COLOR + (bold ? ChatColor.BOLD) + (italic ? ChatColor.ITALIC) + (strikethrough ? ChatColor.STRIKETHROUGH) + (underlined ? ChatColor.UNDERLINE) + (obfuscated ? ChatColor.MAGIG) + text
*
* @return (String) - the ChatColor version
* @see JSON#getChatColorVersion()
*/
public String getChatColorVersion() {
return ChatColor.valueOf(color.name())
+ (bold ? ChatColor.BOLD.toString() : "")
+ (italic ? ChatColor.ITALIC.toString() : "")
+ (strikethrough ? ChatColor.STRIKETHROUGH.toString() : "")
+ (underlined ? ChatColor.UNDERLINE.toString() : "")
+ (obfuscated ? ChatColor.MAGIC.toString() : "")
+ text;
}
/**
* Gets the text this JSONComponent holds.
*
* @return (String) - the text that this JSONComponent holds.
* @see JSONComponent_old#setText(String)
*/
public String getText() {
return text;
}
/**
* Sets the text of this JSONComponent.
*
* @param text (String) - the new text
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setText(String text) {
if (text == null) {
throw new IllegalArgumentException("text cannot be null!");
}
if (text.contains("|||")) {
throw new IllegalArgumentException("text cannot contain the following char sequence: |||");
}
this.text = text;
generated = false;
return this;
}
/**
* Gets the color of the text that this JSONComponent holds.
*
* @return (JSONColor) - the color of the text that this JSONComponent holds.
* @see JSONComponent_old#setColor(JSONColor)
*/
public JSONColor getColor() {
return color;
}
/**
* Sets the color of this JSONComponent.
*
* @param color (JSONColor) - the color to set this JSONObject to
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setColor(JSONColor color) {
if (color == null) {
throw new IllegalArgumentException("color cannot be null!");
}
this.color = color;
generated = false;
return this;
}
/**
* Gets whether the text of this JSONComponent is bold.
*
* @return (boolean) - whether it is bold.
* @see JSONComponent_old#setBold(boolean)
*/
public boolean isBold() {
return bold;
}
/**
* Sets whether the text of this JSONComponent should be bold.
*
* @param bold (boolean) - whether the text should be bold
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setBold(boolean bold) {
this.bold = bold;
generated = false;
return this;
}
/**
* Gets whether the text of this JSONComponent is italic.
*
* @return (boolean) - whether it is italic.
* @see JSONComponent_old#setItalic(boolean)
*/
public boolean isItalic() {
return italic;
}
/**
* Sets whether the text of this JSONComponent should be italic.
*
* @param italic (boolean) - whether the text should be italic
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setItalic(boolean italic) {
this.italic = italic;
generated = false;
return this;
}
/**
* Gets whether the text of this JSONComponent is strikethrough.
*
* @return (boolean) - whether it is strikethrough.
* @see JSONComponent_old#setStrikethrough(boolean)
*/
public boolean isStrikethrough() {
return strikethrough;
}
/**
* Sets whether the text of this JSONComponent should be strikethrough.
*
* @param strikethrough (boolean) - whether the text should be strikethrough
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setStrikethrough(boolean strikethrough) {
this.strikethrough = strikethrough;
generated = false;
return this;
}
/**
* Gets whether the text of this JSONComponent is underlined.
*
* @return (boolean) - whether it is underlined.
* @see JSONComponent_old#setUnderlined(boolean)
*/
public boolean isUnderlined() {
return underlined;
}
/**
* Sets whether the text of this JSONComponent should be underlined.
*
* @param underlined (boolean) - whether the text should be underlined
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setUnderlined(boolean underlined) {
this.underlined = underlined;
generated = false;
return this;
}
/**
* Gets whether the text of this JSONComponent is obfuscated.
*
* @return (boolean) - whether it is obfuscated.
* @see JSONComponent_old#setObfuscated(boolean)
*/
public boolean isObfuscated() {
return obfuscated;
}
/**
* Sets whether the text of this JSONComponent should be obfuscated.
*
* @param obfuscated (boolean) - whether the text should be obfuscated
* @return (JSONComponent) - this JSONComponent Object, for chaining.
*/
public JSONComponentSimple setObfuscated(boolean obfuscated) {
this.obfuscated = obfuscated;
generated = false;
return this;
}
/**
* Gets whether the raw json for this JSONComponent has already been generated.
* Generally speaking, you should have no use for this method.
*
* @return (boolean) - whether it was already generated.
*/
public boolean isGenerated() {
return generated;
}
/**
* Resets the generation status of this JSONComponentSimple Object, forcing the next get() method to run generate().
*
* @return (JSONComponentSimple) - this JSONComponentSimple Object, for chaining.
* @see {@link #generate()}, {@link #get()}
*/
public JSONComponentSimple resetGenerationStatus() {
generated = false;
return this;
}
}

View File

@ -0,0 +1,254 @@
package com.coloredcarrot.mcapi.json;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
/**
* Represents a hover action.
* All rights reserved.
*
* @param <T> - the Type of the value associated with the class implementing this interface
* @author ColoredCarrot
* @see {@link #getValue()}, {@link #setValue(Object)}
*/
public interface JSONHoverAction<T> {
/**
* Gets the value associated with this JSONHoverAction.
*
* @return (?) - the value.
* @see #setValue(Object)
*/
public T getValue();
/**
* Sets the value of this JSONHoverAction.
*
* @param newValue (?) - the new value
* @return (JSONHoverAction: ?) - this JSONHoverAction Object, for chaining.
*/
public JSONHoverAction<T> setValue(T newValue);
/**
* Gets the value associated with this JSONHoverAction transformed to a String.
*
* @return (String) - the value as a String.
* @see #getValue()
*/
public String getValueString();
/**
* Gets the action name associated with this JSONHoverAction.
* Example: "show_text"
*
* @return (String) - the action name.
*/
public String getActionName();
/**
* Shows some JSON-formed text when hovering over the text in the chat.
*/
public class ShowText
implements JSONHoverAction<JSON> {
/**
* The action name
*
* @see #getActionName()
*/
public static final String NAME = "show_text";
private JSON value;
/**
* Constructs a {@link JSONHoverAction.ShowText}
*
* @param value (JSON) - the value associated with this JSONHoverAction
*/
public ShowText(JSON value) {
this.value = value;
}
@Override
public JSON getValue() {
return value;
}
@Override
public JSONHoverAction<JSON> setValue(JSON newValue) {
value = newValue;
return this;
}
@Override
public String getValueString() {
return value.get();
}
@Override
public String getActionName() {
return NAME;
}
}
/**
* Shows an item when hovering over the text in the chat.
*/
public class ShowItem
implements JSONHoverAction<Material> {
/**
* The action name
*
* @see #getActionName()
*/
public static final String NAME = "show_item";
private Material value;
/**
* Constructs a {@link JSONHoverAction.ShowItem}
*
* @param value (JSON) - the value associated with this JSONHoverAction
*/
public ShowItem(Material value) {
this.value = value;
}
@Override
public Material getValue() {
return value;
}
@Override
public JSONHoverAction<Material> setValue(Material newValue) {
value = newValue;
return this;
}
@Override
public String getValueString() {
return value.toString().toLowerCase();
}
@Override
public String getActionName() {
return NAME;
}
}
/**
* Shows an item stack when hovering over the text in the chat.
*/
class ShowItemStack
implements JSONHoverAction<ItemStack> {
/**
* The action name
*
* @see #getActionName()
*/
public static final String NAME = "show_item";
private ItemStack value;
/**
* Constructs a {@link JSONHoverAction.ShowItem}
*
* @param value (JSON) - the value associated with this JSONHoverAction
*/
public ShowItemStack(ItemStack value) {
this.value = value;
}
public static String toTitleCase(String givenString) {
if (givenString == null || "".equals(givenString)) {
return "";
}
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
@Override
public ItemStack getValue() {
return value;
}
@Override
public JSONHoverAction<ItemStack> setValue(ItemStack newValue) {
value = newValue;
return this;
}
@Override
public String getValueString() {
String material = value.getData().getItemType().toString().toLowerCase();
String value2 = "{id:minecraft:" + material + ",Damage:" + value.getDurability() + ",tag:{";
if (value.getItemMeta().hasEnchants()) {
value2 += "ench:[";
int i = 0;
int size = value.getItemMeta().getEnchants().keySet().size();
for (Enchantment ench : value.getItemMeta().getEnchants().keySet()) {
if (i + 1 == size) {
value2 += i + ":{lvl:" + value.getItemMeta().getEnchants().get(ench) + "s,id:" + ench.getId() + "}";
} else {
value2 += i + ":{lvl:" + value.getItemMeta().getEnchants().get(ench) + "s,id:" + ench.getId() + "},";
}
i++;
}
value2 += "],";
}
value2 += "display:{Name:\\\"" + (value
.getItemMeta()
.getDisplayName() != null && value
.getItemMeta()
.getDisplayName() != "" ? value
.getItemMeta()
.getDisplayName() : toTitleCase(value.getType().toString().toLowerCase())) + "\\\"";
if (value.getItemMeta().hasLore()) {
value2 += ",Lore:[";
int i = 0;
for (String lore : value.getItemMeta().getLore()) {
value2 = value2 + (value.getItemMeta().getLore().size() == 1 || value
.getItemMeta()
.getLore()
.get(value
.getItemMeta()
.getLore()
.size() - 1) == lore ? (i + ":\\\"" + lore + "\\\"") : (i + ":\\\"" + lore + "\\\","));
i++;
}
value2 += "]";
}
value2 += "}}}\"";
return value2;
}
@Override
public String getActionName() {
return NAME;
}
}
}

View File

@ -1,11 +1,14 @@
package cz.boosik.boosCooldown;
import cz.boosik.boosCooldown.Listeners.*;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosLimitManager;
import cz.boosik.boosCooldown.Runnables.BoosGlobalLimitResetRunnable;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@ -20,16 +23,24 @@ import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.mcstats.MetricsLite;
import util.boosChat;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import com.coloredcarrot.mcapi.json.JSON;
import cz.boosik.boosCooldown.Listeners.BoosEntityDamageListener;
import cz.boosik.boosCooldown.Listeners.BoosPlayerDeathListener;
import cz.boosik.boosCooldown.Listeners.BoosPlayerGameModeChangeListener;
import cz.boosik.boosCooldown.Listeners.BoosPlayerInteractListener;
import cz.boosik.boosCooldown.Listeners.BoosPlayerMoveListener;
import cz.boosik.boosCooldown.Listeners.BoosPlayerToggleSneakListener;
import cz.boosik.boosCooldown.Listeners.BoosPlayerToggleSprintListener;
import cz.boosik.boosCooldown.Listeners.BoosSignChangeListener;
import cz.boosik.boosCooldown.Listeners.BoosSignInteractListener;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosLimitManager;
import cz.boosik.boosCooldown.Runnables.BoosGlobalLimitResetRunnable;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;
import nms.NMSSetupResponse;
import util.boosChat;
public class BoosCoolDown extends JavaPlugin implements Runnable {
@ -78,7 +89,8 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
time = 1;
}
BoosCoolDown.getLog().info("[boosCooldowns] Starting timer for " + time + " seconds to reset limits for command " + key);
scheduler.scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("boosCooldowns"), new BoosGlobalLimitResetRunnable(key),
scheduler.scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("boosCooldowns"),
new BoosGlobalLimitResetRunnable(key),
time * 20);
} else {
BoosCoolDown.getLog().info("[boosCooldowns] Stoping timer to reset limits for command " + key);
@ -104,7 +116,9 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
time = 1;
}
BoosCoolDown.getLog().info("[boosCooldowns] Starting timer for " + time + " seconds to reset limits for command " + key);
scheduler.scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("boosCooldowns"), new BoosGlobalLimitResetRunnable(key), time * 20);
scheduler.scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("boosCooldowns"),
new BoosGlobalLimitResetRunnable(key),
time * 20);
} else {
BoosCoolDown.getLog().info("[boosCooldowns] Stoping timer to reset limits for command " + key);
}
@ -188,7 +202,7 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
startLimitResetTimersGlobal();
return true;
} else if (args[0].equalsIgnoreCase("confirmations")) {
BoosConfigManager.toggleConfirmations((Player)sender);
BoosConfigManager.toggleConfirmations((Player) sender);
return true;
}
} else if (args.length == 2) {
@ -198,7 +212,8 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
if (sender.hasPermission("booscooldowns.clearcooldowns") && args[0].equalsIgnoreCase("clearcooldowns")) {
String co = "cooldown";
BoosConfigManager.clearSomething(co, uuid);
boosChat.sendMessageToCommandSender(sender, "&6[" + pdfFile.getName() + "]&e" + " cooldowns of player " + jmeno + " cleared");
boosChat.sendMessageToCommandSender(sender,
"&6[" + pdfFile.getName() + "]&e" + " cooldowns of player " + jmeno + " cleared");
return true;
} else if (sender.hasPermission("booscooldowns.clearuses") && command.equalsIgnoreCase("booscooldowns") && args[0].equalsIgnoreCase(
"clearuses")) {
@ -284,7 +299,8 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
// + " Invalid command or access denied!");
return false;
}
} return false;
}
return false;
}
@ -315,7 +331,10 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
BukkitScheduler scheduler = this.getServer().getScheduler();
startLimitResetTimersGlobal();
if (BoosConfigManager.getAutoSave()) {
scheduler.scheduleSyncRepeatingTask(this, this, BoosConfigManager.getSaveInterval() * 1200, BoosConfigManager.getSaveInterval() * 1200);
scheduler.scheduleSyncRepeatingTask(this,
this,
BoosConfigManager.getSaveInterval() * 1200,
BoosConfigManager.getSaveInterval() * 1200);
}
if (BoosConfigManager.getClearOnRestart()) {
@ -327,6 +346,16 @@ public class BoosCoolDown extends JavaPlugin implements Runnable {
} catch (IOException e) {
// Failed to submit the stats :-(
}
NMSSetupResponse nmsSetupResponse = JSON.setup(this);
if (nmsSetupResponse.isCompatible()) {
getLogger().info("[" + pdfFile.getName() + "]" + " Hooked server version " + nmsSetupResponse.getVersion());
} else {
getLogger().warning("[" + pdfFile.getName() + "]" + " Your server version (" + (nmsSetupResponse.getVersion() == null ? "UNKNOWN" : nmsSetupResponse
.getVersion()) + ") is not compatible with this plugin!");
getServer().getPluginManager().disablePlugin(this);
return;
}
}

View File

@ -1,5 +1,8 @@
package cz.boosik.boosCooldown;
import static cz.boosik.boosCooldown.Managers.BoosItemCostManager.getItemStackJson;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -16,6 +19,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import com.coloredcarrot.mcapi.json.JSON;
import cz.boosik.boosCooldown.Managers.BoosAliasManager;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosCoolDownManager;
@ -27,18 +31,17 @@ import cz.boosik.boosCooldown.Managers.BoosXpCostManager;
import util.boosChat;
public class BoosCoolDownListener implements Listener {
public static Map<String, Boolean> commandQueue = new ConcurrentHashMap();
private static BoosCoolDown plugin;
public BoosCoolDownListener(BoosCoolDown instance) {
plugin = instance;
}
public static Map<String, Boolean> commandQueue = new ConcurrentHashMap();
private void checkRestrictions(PlayerCommandPreprocessEvent event,
Player player, String regexCommad, String originalCommand,
int warmupTime, int cooldownTime, double price, String item,
int count, int limit, int xpPrice) {
int count, String name, List<String> lore, List<String> enchants, int limit, int xpPrice) {
boolean blocked = false;
String perm = BoosConfigManager.getPermission(player, regexCommad);
if (!(perm == null)) {
@ -63,7 +66,7 @@ public class BoosCoolDownListener implements Listener {
warmupTime, cooldownTime);
}
} else if (BoosPriceManager.has(player, price)
& BoosItemCostManager.has(player, item, count)
& BoosItemCostManager.has(player, item, count, name, lore, enchants)
& BoosXpCostManager.has(player, xpPrice)) {
if (BoosCoolDownManager.coolDown(player, regexCommad,
originalCommand, cooldownTime)) {
@ -71,7 +74,7 @@ public class BoosCoolDownListener implements Listener {
}
}
if (BoosPriceManager.has(player, price)
& BoosItemCostManager.has(player, item, count)
& BoosItemCostManager.has(player, item, count, name, lore, enchants)
& BoosXpCostManager.has(player, xpPrice)) {
if (!event.isCancelled()) {
BoosPriceManager.payForCommand(event, player, regexCommad,
@ -79,7 +82,7 @@ public class BoosCoolDownListener implements Listener {
}
if (!event.isCancelled()) {
BoosItemCostManager.payItemForCommand(event, player,
regexCommad, originalCommand, item, count);
regexCommad, originalCommand, item, count, name, lore, enchants);
}
if (!event.isCancelled()) {
BoosXpCostManager.payXPForCommand(event, player,
@ -100,14 +103,15 @@ public class BoosCoolDownListener implements Listener {
msg = msg.replaceAll("&command&", originalCommand);
boosChat.sendMessageToPlayer(player, msg);
}
if (!BoosItemCostManager.has(player, item, count)
if (!BoosItemCostManager.has(player, item, count, name, lore, enchants)
&& !warmupInProgress && !cooldownInProgress) {
String msg = "";
msg = String.format(
BoosConfigManager.getInsufficientItemsMessage(),
(count + " " + item));
BoosConfigManager.getInsufficientItemsMessage(), "");
JSON json = getItemStackJson(1, item, count, name, lore, enchants);
msg = msg.replaceAll("&command&", originalCommand);
boosChat.sendMessageToPlayer(player, msg);
json.send(player);
}
if (!BoosXpCostManager.has(player, xpPrice)
&& !warmupInProgress && !cooldownInProgress) {
@ -194,6 +198,9 @@ public class BoosCoolDownListener implements Listener {
Set<String> commands = BoosConfigManager.getCommands(player);
boolean on;
String item = "";
String name = "";
List<String> lore = new ArrayList<>();
List<String> enchants = new ArrayList<>();
int count = 0;
int warmupTime = 0;
double price = 0;
@ -229,8 +236,14 @@ public class BoosCoolDownListener implements Listener {
if (BoosConfigManager.getItemCostEnabled()) {
item = BoosConfigManager.getItemCostItem(regexCommad,
player);
name = BoosConfigManager.getItemCostName(regexCommad,
player);
lore = BoosConfigManager.getItemCostLore(regexCommad,
player);
count = BoosConfigManager.getItemCostCount(regexCommad,
player);
enchants = BoosConfigManager.getItemCostEnchants(regexCommad,
player);
}
if (BoosConfigManager.getLimitEnabled()) {
limit = BoosConfigManager.getLimit(regexCommad, player);
@ -242,7 +255,7 @@ public class BoosCoolDownListener implements Listener {
.keySet()
.contains(uuid + "@" + originalCommand) && commandQueue.get(uuid + "@" + originalCommand))) {
this.checkRestrictions(event, player, regexCommad, originalCommand,
warmupTime, cooldownTime, price, item, count, limit,
warmupTime, cooldownTime, price, item, count, name, lore, enchants, limit,
xpPrice);
} else {
if ((price > 0 || xpPrice > 0 || count > 0 || limit > 0) && !BoosWarmUpManager.isWarmUpProcess(player,
@ -270,8 +283,10 @@ public class BoosCoolDownListener implements Listener {
}
if (count > 0) {
String itemMessage = BoosConfigManager.getItsItemCostMessage();
itemMessage = itemMessage.replace("&itemprice&", String.valueOf(count)).replace("&itemname&", item);
itemMessage = itemMessage.replace("&itemprice&", "").replace("&itemname&", "");
JSON json = getItemStackJson(2, item, count, name, lore, enchants);
boosChat.sendMessageToPlayer(player, " " + itemMessage);
json.send(player);
}
if (limit > 0) {
int uses = BoosLimitManager.getUses(player, regexCommad);
@ -286,7 +301,7 @@ public class BoosCoolDownListener implements Listener {
return;
} else {
this.checkRestrictions(event, player, regexCommad, originalCommand,
warmupTime, cooldownTime, price, item, count, limit,
warmupTime, cooldownTime, price, item, count, name, lore, enchants, limit,
xpPrice);
}
}

View File

@ -1,30 +1,31 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import util.boosChat;
public class BoosEntityDamageListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
if (entity != null && entity instanceof Player) {
Player player = (Player) entity;
if (!player.hasPermission("booscooldowns.nocancel.damage")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player, BoosConfigManager
.getWarmUpCancelledByDamageMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import util.boosChat;
public class BoosEntityDamageListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
if (entity != null && entity instanceof Player) {
Player player = (Player) entity;
if (!player.hasPermission("booscooldowns.nocancel.damage")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player, BoosConfigManager
.getWarmUpCancelledByDamageMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
}
}

View File

@ -1,51 +1,52 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosCoolDownManager;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
public class BoosPlayerDeathListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerDeath(PlayerDeathEvent event) {
Entity entity = event.getEntity();
if (entity != null) {
Player player = (Player) entity;
clearCooldownsOnDeath(player);
clearUsesOnDeath(player);
startCooldownsOnDeath(player);
}
}
private void startCooldownsOnDeath(Player player) {
if (player != null) {
if (BoosConfigManager.getStartCooldownsOnDeath()) {
BoosCoolDownManager.startAllCooldowns(player, "");
}
}
}
private void clearUsesOnDeath(Player player) {
if (player != null
&& player.hasPermission("booscooldowns.clear.uses.death")) {
if (BoosConfigManager.getCleanUsesOnDeath()) {
BoosConfigManager.clearSomething("uses", player.getUniqueId());
}
}
}
private void clearCooldownsOnDeath(Player player) {
if (player != null
&& player.hasPermission("booscooldowns.clear.cooldowns.death")) {
if (BoosConfigManager.getCleanCooldownsOnDeath()) {
BoosConfigManager.clearSomething("cooldown",
player.getUniqueId());
}
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosCoolDownManager;
public class BoosPlayerDeathListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerDeath(PlayerDeathEvent event) {
Entity entity = event.getEntity();
if (entity != null) {
Player player = (Player) entity;
clearCooldownsOnDeath(player);
clearUsesOnDeath(player);
startCooldownsOnDeath(player);
}
}
private void startCooldownsOnDeath(Player player) {
if (player != null) {
if (BoosConfigManager.getStartCooldownsOnDeath()) {
BoosCoolDownManager.startAllCooldowns(player, "");
}
}
}
private void clearUsesOnDeath(Player player) {
if (player != null
&& player.hasPermission("booscooldowns.clear.uses.death")) {
if (BoosConfigManager.getCleanUsesOnDeath()) {
BoosConfigManager.clearSomething("uses", player.getUniqueId());
}
}
}
private void clearCooldownsOnDeath(Player player) {
if (player != null
&& player.hasPermission("booscooldowns.clear.cooldowns.death")) {
if (BoosConfigManager.getCleanCooldownsOnDeath()) {
BoosConfigManager.clearSomething("cooldown",
player.getUniqueId());
}
}
}
}

View File

@ -1,31 +1,32 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import util.boosChat;
public class BoosPlayerGameModeChangeListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
Entity entity = event.getPlayer();
if (entity != null) {
Player player = (Player) entity;
if (!player
.hasPermission("booscooldowns.nocancel.gamemodechange")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player, BoosConfigManager
.getCancelWarmupByGameModeChangeMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import util.boosChat;
public class BoosPlayerGameModeChangeListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
Entity entity = event.getPlayer();
if (entity != null) {
Player player = (Player) entity;
if (!player
.hasPermission("booscooldowns.nocancel.gamemodechange")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player, BoosConfigManager
.getCancelWarmupByGameModeChangeMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
}
}

View File

@ -1,60 +1,61 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import util.boosChat;
public class BoosPlayerInteractListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerInteract(PlayerInteractEvent event) {
Entity entity = event.getPlayer();
if (entity != null) {
Player player = (Player) entity;
if (!player
.hasPermission("booscooldowns.dontblock.interact")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
if (event.getClickedBlock().getType().name()
.equals("CHEST")
|| event.getClickedBlock().getType().name()
.equals("FURNACE")
|| event.getClickedBlock().getType().name()
.equals("BURNING_FURNACE")
|| event.getClickedBlock().getType().name()
.equals("WORKBENCH")
|| event.getClickedBlock().getType().name()
.equals("DISPENSER")
|| event.getClickedBlock().getType().name()
.equals("JUKEBOX")
|| event.getClickedBlock().getType().name()
.equals("LOCKED_CHEST")
|| event.getClickedBlock().getType().name()
.equals("ENCHANTMENT_TABLE")
|| event.getClickedBlock().getType().name()
.equals("BREWING_STAND")
|| event.getClickedBlock().getType().name()
.equals("CAULDRON")
|| event.getClickedBlock().getType().name()
.equals("STORAGE_MINECART")
|| event.getClickedBlock().getType().name()
.equals("TRAPPED_CHEST")
|| event.getClickedBlock().getType().name()
.equals("DROPPER")
|| event.getClickedBlock().getType().name()
.equals("HOPPER")) {
event.setCancelled(true);
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getInteractBlockedMessage());
}
}
}
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import util.boosChat;
public class BoosPlayerInteractListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerInteract(PlayerInteractEvent event) {
Entity entity = event.getPlayer();
if (entity != null) {
Player player = (Player) entity;
if (!player
.hasPermission("booscooldowns.dontblock.interact")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
if (event.getClickedBlock().getType().name()
.equals("CHEST")
|| event.getClickedBlock().getType().name()
.equals("FURNACE")
|| event.getClickedBlock().getType().name()
.equals("BURNING_FURNACE")
|| event.getClickedBlock().getType().name()
.equals("WORKBENCH")
|| event.getClickedBlock().getType().name()
.equals("DISPENSER")
|| event.getClickedBlock().getType().name()
.equals("JUKEBOX")
|| event.getClickedBlock().getType().name()
.equals("LOCKED_CHEST")
|| event.getClickedBlock().getType().name()
.equals("ENCHANTMENT_TABLE")
|| event.getClickedBlock().getType().name()
.equals("BREWING_STAND")
|| event.getClickedBlock().getType().name()
.equals("CAULDRON")
|| event.getClickedBlock().getType().name()
.equals("STORAGE_MINECART")
|| event.getClickedBlock().getType().name()
.equals("TRAPPED_CHEST")
|| event.getClickedBlock().getType().name()
.equals("DROPPER")
|| event.getClickedBlock().getType().name()
.equals("HOPPER")) {
event.setCancelled(true);
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getInteractBlockedMessage());
}
}
}
}
}
}

View File

@ -1,33 +1,36 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import util.boosChat;
public class BoosPlayerMoveListener implements Listener {
private int tempTimer = 0;
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerMove(PlayerMoveEvent event) {
if (tempTimer < 10) {
tempTimer = tempTimer + 1;
} else {
Player player = event.getPlayer();
if (player != null
&& !player.hasPermission("booscooldowns.nocancel.move")) {
if (BoosWarmUpManager.hasWarmUps(player) && (event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event.getTo().getZ() || event.getFrom().getY() != event.getTo().getY())) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getWarmUpCancelledByMoveMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
tempTimer = 0;
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import util.boosChat;
public class BoosPlayerMoveListener implements Listener {
private int tempTimer = 0;
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerMove(PlayerMoveEvent event) {
if (tempTimer < 10) {
tempTimer = tempTimer + 1;
} else {
Player player = event.getPlayer();
if (player != null
&& !player.hasPermission("booscooldowns.nocancel.move")) {
if (BoosWarmUpManager.hasWarmUps(player) && (event.getFrom().getX() != event.getTo().getX() || event.getFrom().getZ() != event
.getTo()
.getZ() || event.getFrom().getY() != event.getTo().getY())) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getWarmUpCancelledByMoveMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
tempTimer = 0;
}
}
}

View File

@ -1,27 +1,28 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import util.boosChat;
public class BoosPlayerToggleSneakListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerToggleSneak(PlayerToggleSneakEvent event) {
Player player = event.getPlayer();
if (player != null
&& !player.hasPermission("booscooldowns.nocancel.sneak")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCancelWarmupOnSneakMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import util.boosChat;
public class BoosPlayerToggleSneakListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerToggleSneak(PlayerToggleSneakEvent event) {
Player player = event.getPlayer();
if (player != null
&& !player.hasPermission("booscooldowns.nocancel.sneak")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCancelWarmupOnSneakMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
}

View File

@ -1,27 +1,28 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import util.boosChat;
public class BoosPlayerToggleSprintListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerToggleSprint(PlayerToggleSprintEvent event) {
Player player = event.getPlayer();
if (player != null
&& !player.hasPermission("booscooldowns.nocancel.sprint")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCancelWarmupOnSprintMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import util.boosChat;
public class BoosPlayerToggleSprintListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onPlayerToggleSprint(PlayerToggleSprintEvent event) {
Player player = event.getPlayer();
if (player != null
&& !player.hasPermission("booscooldowns.nocancel.sprint")) {
if (BoosWarmUpManager.hasWarmUps(player)) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCancelWarmupOnSprintMessage());
BoosWarmUpManager.cancelWarmUps(player);
}
}
}
}

View File

@ -1,37 +1,38 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import util.boosChat;
public class BoosSignChangeListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
String line1 = event.getLine(0);
String line2 = event.getLine(1);
if (line1.equals("[boosCooldowns]")) {
if (line2.equals("player")
&& !player
.hasPermission("booscooldowns.signs.player.place")) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCannotCreateSignMessage());
event.getBlock().breakNaturally();
event.setCancelled(true);
}
if (line2.equals("server")
&& !player
.hasPermission("booscooldowns.signs.server.place")) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCannotCreateSignMessage());
event.getBlock().breakNaturally();
event.setCancelled(true);
}
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import util.boosChat;
public class BoosSignChangeListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
String line1 = event.getLine(0);
String line2 = event.getLine(1);
if (line1.equals("[boosCooldowns]")) {
if (line2.equals("player")
&& !player
.hasPermission("booscooldowns.signs.player.place")) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCannotCreateSignMessage());
event.getBlock().breakNaturally();
event.setCancelled(true);
}
if (line2.equals("server")
&& !player
.hasPermission("booscooldowns.signs.server.place")) {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCannotCreateSignMessage());
event.getBlock().breakNaturally();
event.setCancelled(true);
}
}
}
}

View File

@ -1,65 +1,67 @@
package cz.boosik.boosCooldown.Listeners;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.BoosCoolDown;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import util.boosChat;
public class BoosSignInteractListener implements Listener {
private final BoosCoolDown plugin;
public BoosSignInteractListener(BoosCoolDown instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onSignInteract(PlayerInteractEvent event) {
String msg;
if (event.isCancelled())
return;
if (event.hasBlock() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getClickedBlock().getType() == Material.SIGN_POST
|| event.getClickedBlock().getType() == Material.WALL_SIGN) {
Sign s = (Sign) event.getClickedBlock().getState();
String line1 = s.getLine(0);
String line2 = s.getLine(1);
String line3 = s.getLine(2);
String line4 = s.getLine(3);
Player player = event.getPlayer();
if (line1.equals("[boosCooldowns]")) {
if (line2.equals("player")
&& player
.hasPermission("booscooldowns.signs.player.use")) {
msg = line3;
if (line3.endsWith("+") || !line4.isEmpty()) {
msg = line3.substring(0, line3.length() - 1) + " "
+ line4;
}
event.getPlayer().chat(msg);
} else if (line2.equals("server")
&& player
.hasPermission("booscooldowns.signs.server.use")) {
msg = line3;
if (line3.endsWith("+") || !line4.isEmpty()) {
msg = line3.substring(0, line3.length() - 1) + " "
+ line4;
}
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(), msg);
} else {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCannotUseSignMessage());
}
}
}
}
}
}
package cz.boosik.boosCooldown.Listeners;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import cz.boosik.boosCooldown.BoosCoolDown;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import util.boosChat;
public class BoosSignInteractListener implements Listener {
private final BoosCoolDown plugin;
public BoosSignInteractListener(BoosCoolDown instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
private void onSignInteract(PlayerInteractEvent event) {
String msg;
if (event.isCancelled()) {
return;
}
if (event.hasBlock() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (event.getClickedBlock().getType() == Material.SIGN_POST
|| event.getClickedBlock().getType() == Material.WALL_SIGN) {
Sign s = (Sign) event.getClickedBlock().getState();
String line1 = s.getLine(0);
String line2 = s.getLine(1);
String line3 = s.getLine(2);
String line4 = s.getLine(3);
Player player = event.getPlayer();
if (line1.equals("[boosCooldowns]")) {
if (line2.equals("player")
&& player
.hasPermission("booscooldowns.signs.player.use")) {
msg = line3;
if (line3.endsWith("+") || !line4.isEmpty()) {
msg = line3.substring(0, line3.length() - 1) + " "
+ line4;
}
event.getPlayer().chat(msg);
} else if (line2.equals("server")
&& player
.hasPermission("booscooldowns.signs.server.use")) {
msg = line3;
if (line3.endsWith("+") || !line4.isEmpty()) {
msg = line3.substring(0, line3.length() - 1) + " "
+ line4;
}
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(), msg);
} else {
boosChat.sendMessageToPlayer(player,
BoosConfigManager.getCannotUseSignMessage());
}
}
}
}
}
}

View File

@ -1,9 +1,9 @@
package cz.boosik.boosCooldown.Managers;
import org.bukkit.entity.Player;
import java.util.Set;
import org.bukkit.entity.Player;
public class BoosAliasManager {
public static String checkCommandAlias(String originalCommand,

View File

@ -1,12 +1,5 @@
package cz.boosik.boosCooldown.Managers;
import cz.boosik.boosCooldown.BoosCoolDown;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import util.boosChat;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -14,6 +7,14 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import cz.boosik.boosCooldown.BoosCoolDown;
import util.boosChat;
public class BoosConfigManager {
private static YamlConfiguration conf;
@ -111,7 +112,8 @@ public class BoosConfigManager {
}
public static String getCancelWarmupByGameModeChangeMessage() {
return conf.getString("options.messages.warmup_cancelled_by_gamemode_change", "&6Warm-ups have been cancelled due to changing gamemode.&f");
return conf.getString("options.messages.warmup_cancelled_by_gamemode_change",
"&6Warm-ups have been cancelled due to changing gamemode.&f");
}
public static boolean getCancelWarmUpOnDamage() {
@ -237,30 +239,24 @@ public class BoosConfigManager {
return conf.getString("options.messages.interact_blocked_during_warmup", "&6You can't do this when command is warming-up!&f");
}
public static List<String> getItemCostLore(String regexCommand, Player player) {
return conf.getStringList("commands.groups." + getCommandGroup(player) + "." + regexCommand + ".itemcost.lore");
}
public static List<String> getItemCostEnchants(String regexCommand, Player player) {
return conf.getStringList("commands.groups." + getCommandGroup(player) + "." + regexCommand + ".itemcost.enchants");
}
public static String getItemCostName(String regexCommand, Player player) {
return conf.getString("commands.groups." + getCommandGroup(player) + "." + regexCommand + ".itemcost.name", "");
}
public static String getItemCostItem(String regexCommand, Player player) {
String item = "";
String temp;
String[] command;
String group = getCommandGroup(player);
temp = conf.getString("commands.groups." + group + "." + regexCommand + ".itemcost", "");
command = temp.split(",");
if (command.length == 2) {
item = command[0];
}
return item;
return conf.getString("commands.groups." + getCommandGroup(player) + "." + regexCommand + ".itemcost.item", "");
}
public static int getItemCostCount(String regexCommand, Player player) {
int count = 0;
String temp;
String[] command;
String group = getCommandGroup(player);
temp = conf.getString("commands.groups." + group + "." + regexCommand + ".itemcost", "");
command = temp.split(",");
if (command.length == 2) {
count = Integer.valueOf(command[1]);
}
return count;
return conf.getInt("commands.groups." + getCommandGroup(player) + "." + regexCommand + ".itemcost.count", 0);
}
public static int getLimit(String regexCommand, Player player) {
@ -486,7 +482,7 @@ public class BoosConfigManager {
}
public static Boolean getConfirmationsPlayer(Player player) {
return (Boolean)confusers.get("users." + player.getUniqueId() + ".confirmations", null);
return (Boolean) confusers.get("users." + player.getUniqueId() + ".confirmations", null);
}
public static boolean getAutoSave() {
@ -538,7 +534,8 @@ public class BoosConfigManager {
}
static String getLimitResetMessage() {
return conf.getString("options.messages.limit_reset", "&6Wait&e &seconds& &unit&&6 before your limit for command&e &command& &6is reset.&f");
return conf.getString("options.messages.limit_reset",
"&6Wait&e &seconds& &unit&&6 before your limit for command&e &command& &6is reset.&f");
}
static void clearSomething2(String co, String uuid, int hashedCommand) {

View File

@ -1,14 +1,15 @@
package cz.boosik.boosCooldown.Managers;
import org.bukkit.entity.Player;
import util.boosChat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.bukkit.entity.Player;
import util.boosChat;
public class BoosCoolDownManager {
static void cancelCooldown(Player player, String regexCommand) {
@ -17,9 +18,9 @@ public class BoosCoolDownManager {
"users." + player.getUniqueId() + ".cooldown." + pre2, null);
}
public static boolean isCoolingdown(Player player, String regexCommand, int time){
public static boolean isCoolingdown(Player player, String regexCommand, int time) {
Date lastTime = getTime(player, regexCommand);
if (lastTime == null){
if (lastTime == null) {
return false;
}
Calendar calcurrTime = Calendar.getInstance();
@ -27,7 +28,7 @@ public class BoosCoolDownManager {
Calendar callastTime = Calendar.getInstance();
callastTime.setTime(lastTime);
long secondsBetween = secondsBetween(callastTime, calcurrTime);
if ((secondsBetween > time) || secondsBetween == 0){
if ((secondsBetween > time) || secondsBetween == 0) {
return false;
}
return true;
@ -107,7 +108,11 @@ public class BoosCoolDownManager {
public static boolean coolDown(Player player, String regexCommand,
String originalCommand, int time) {
regexCommand = regexCommand.toLowerCase();
return time > 0 && !player.hasPermission("booscooldowns.nocooldown") && !player.hasPermission("booscooldowns.nocooldown." + originalCommand) && cd(player, regexCommand, originalCommand, time);
return time > 0 && !player.hasPermission("booscooldowns.nocooldown") && !player.hasPermission("booscooldowns.nocooldown." + originalCommand) && cd(
player,
regexCommand,
originalCommand,
time);
}
private static Date getCurrTime() {

View File

@ -0,0 +1,138 @@
package cz.boosik.boosCooldown.Managers;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.coloredcarrot.mcapi.json.JSON;
import com.coloredcarrot.mcapi.json.JSONColor;
import com.coloredcarrot.mcapi.json.JSONComponent;
import com.coloredcarrot.mcapi.json.JSONHoverAction;
import util.boosChat;
public class BoosItemCostManager {
private static boolean payItemForCommand(Player player,
String originalCommand, String item, int count, String name, List<String> lore, List<String> enchants) {
ItemStack itemStack = createItemStack(item, count, name, lore, enchants);
ItemStack itemStackSingle = createItemStack(item, 1, name, lore, enchants);
Inventory inventory = player.getInventory();
Boolean trans = false;
if (inventory.containsAtLeast(itemStackSingle, count)) {
inventory.removeItem(itemStack);
trans = true;
}
if (trans) {
String msg = String.format(
BoosConfigManager.getPaidItemsForCommandMessage(), "");
JSON json = getItemStackJson(1, item, count, name, lore, enchants);
msg = msg.replaceAll("&command&", originalCommand);
boosChat.sendMessageToPlayer(player, msg);
json.send(player);
return true;
} else {
return false;
}
}
public static void payItemForCommand(PlayerCommandPreprocessEvent event,
Player player, String regexCommand, String originalCommand,
String item, int count, String name, List<String> lore, List<String> enchants) {
if (count > 0) {
if (!player.hasPermission("booscooldowns.noitemcost")
&& !player.hasPermission("booscooldowns.noitemcost."
+ originalCommand)) {
if (!payItemForCommand(player, originalCommand,
item, count, name, lore, enchants)) {
BoosCoolDownManager.cancelCooldown(player, regexCommand);
event.setCancelled(true);
}
}
}
}
public static boolean has(Player player, String item, int count, String name, List<String> lore, List<String> enchants) {
if (item.equals("")) {
return true;
}
if (count <= 0) {
return true;
}
ItemStack itemStack = createItemStack(item, 1, name, lore, enchants);
Inventory inventory = player.getInventory();
return inventory.containsAtLeast(itemStack, count);
}
public static ItemStack createItemStack(String item, int count, String name, List<String> lore, List<String> enchants) {
ItemStack itemStack = new ItemStack(Material.getMaterial(item), count);
ItemMeta itemMeta = itemStack.getItemMeta();
if (name != null) {
itemMeta.setDisplayName(name);
}
if (!lore.isEmpty()) {
itemMeta.setLore(lore);
}
if (!enchants.isEmpty()) {
for (String enchantString : enchants) {
String[] enchantArray = enchantString.split(",");
Enchantment enchant = Enchantment.getByName(enchantArray[0]);
itemMeta.addEnchant(enchant, Integer.valueOf(enchantArray[1]), true);
}
}
itemStack.setItemMeta(itemMeta);
return itemStack;
}
public static JSON getItemStackJson(int indent, String item, int count, String name, List<String> lore, List<String> enchants) {
ItemStack itemStack = createItemStack(item, count, name, lore, enchants);
JSONColor itemColor;
if (itemStack.getItemMeta().hasEnchants()) {
itemColor = JSONColor.fromString("&b");
} else {
itemColor = JSONColor.fromString("&f");
}
itemColor = name != null && (name.startsWith("&") || name.startsWith("§")) ? JSONColor.fromString(name.substring(0, 2)) : itemColor;
String indentation = "";
for (int i = 0; i < indent; i++) {
indentation += " ";
}
JSONComponent comp1 = new JSONComponent(indentation);
JSONComponent comp2 = new JSONComponent(String.valueOf(count) + "x ");
comp2.setColor(JSONColor.YELLOW);
JSONComponent comp3 = new JSONComponent("[");
comp3.setColor(itemColor);
JSONComponent comp4 = new JSONComponent(name == null || name.equals("") ? toTitleCase(itemStack
.getType()
.toString()
.toLowerCase()) : name);
comp4.setColor(itemColor);
JSONComponent comp5 = new JSONComponent("]");
comp5.setColor(itemColor);
comp3.setHoverAction(new JSONHoverAction.ShowItemStack(itemStack));
comp4.setHoverAction(new JSONHoverAction.ShowItemStack(itemStack));
comp5.setHoverAction(new JSONHoverAction.ShowItemStack(itemStack));
return new JSON(comp1, comp2, comp3, comp4, comp5);
}
public static String toTitleCase(String givenString) {
if (givenString == null || "".equals(givenString)) {
return "";
}
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
}

View File

@ -1,15 +1,16 @@
package cz.boosik.boosCooldown.Managers;
import cz.boosik.boosCooldown.BoosCoolDown;
import org.bukkit.entity.Player;
import util.boosChat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import org.bukkit.entity.Player;
import cz.boosik.boosCooldown.BoosCoolDown;
import util.boosChat;
public class BoosLimitManager {
public static boolean blocked(Player player, String regexCommand,

View File

@ -1,10 +1,11 @@
package cz.boosik.boosCooldown.Managers;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import cz.boosik.boosCooldown.BoosCoolDown;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import util.boosChat;
public class BoosPriceManager {
@ -24,8 +25,8 @@ public class BoosPriceManager {
boosChat.sendMessageToPlayer(player, msg);
return true;
} else {
msg = String.format(BoosConfigManager.getPaidErrorMessage(),
r.errorMessage);
msg = String.format(BoosConfigManager.getPaidErrorMessage(),
r.errorMessage);
boosChat.sendMessageToPlayer(player, msg);
return false;
}

View File

@ -1,16 +1,17 @@
package cz.boosik.boosCooldown.Managers;
import cz.boosik.boosCooldown.BoosCoolDown;
import cz.boosik.boosCooldown.Runnables.BoosWarmUpTimer;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import util.boosChat;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import cz.boosik.boosCooldown.BoosCoolDown;
import cz.boosik.boosCooldown.Runnables.BoosWarmUpTimer;
import util.boosChat;
public class BoosWarmUpManager {
private static final ConcurrentHashMap<String, BoosWarmUpTimer> playercommands = new ConcurrentHashMap<>();

View File

@ -2,6 +2,7 @@ package cz.boosik.boosCooldown.Managers;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import util.boosChat;
public class BoosXpCostManager {

View File

@ -1,9 +1,10 @@
package cz.boosik.boosCooldown.Runnables;
import org.bukkit.Bukkit;
import cz.boosik.boosCooldown.BoosCoolDown;
import cz.boosik.boosCooldown.Managers.BoosConfigManager;
import cz.boosik.boosCooldown.Managers.BoosLimitManager;
import org.bukkit.Bukkit;
public class BoosGlobalLimitResetRunnable implements Runnable {

View File

@ -1,11 +1,12 @@
package cz.boosik.boosCooldown.Runnables;
import java.util.TimerTask;
import org.bukkit.entity.Player;
import cz.boosik.boosCooldown.BoosCoolDown;
import cz.boosik.boosCooldown.BoosCoolDownListener;
import cz.boosik.boosCooldown.Managers.BoosWarmUpManager;
import org.bukkit.entity.Player;
import java.util.TimerTask;
public class BoosWarmUpTimer extends TimerTask {

View File

@ -0,0 +1,560 @@
/*
* Copyright 2011-2013 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package org.mcstats;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import cz.boosik.boosCooldown.BoosCoolDown;
@SuppressWarnings("ALL")
public class MetricsLite {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private final static int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin;
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* Id of the scheduled task
*/
private volatile BukkitTask task = null;
public MetricsLite(Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org")
.copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
/**
* GZip compress a string of bytes
*
* @param input
* @return
*/
private static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
}
}
}
return baos.toByteArray();
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key,
String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return
*/
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text)
throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Start measuring statistics. This will immediately create an async
* repeating task as the plugin and send the initial data to the metrics
* backend, and then after that it will post in increments of PING_INTERVAL
* * 1200 ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler()
.runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide
// with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the
// server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it
// is the first time we are posting,
// it is not a interval ping, so it evaluates to
// FALSE
// Each time thereafter it will evaluate to
// TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the
* config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the
* config file and canceling the metrics task.
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data
* such as the GUID and opt-out status
*
* @return the File object for the config file
*/
File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(boolean isPing) throws IOException {
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if
// online
// mode is
// enabled
String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion();
int playersOnline = 0;
try {
playersOnline = Bukkit.getServer().getOnlinePlayers().size();
} catch (Exception e) {
BoosCoolDown
.getLog()
.warning(
"[boosCooldowns] This error was caused because you are using old CraftBukkit version. Please update to 1.7.10 (1.7.9-R0.3).");
}
// END server software specific section -- all code below does not use
// any code outside of this class / Java
// Construct the post data
StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as
// name, version, author, etc
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL
+ String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length",
Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
System.out.println("[Metrics] Prepared request for " + pluginName
+ " uncompressed=" + uncompressed.length + " compressed="
+ compressed.length);
}
// Write the data
OutputStream os = connection.getOutputStream();
os.write(compressed);
os.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String response = reader.readLine();
// close resources
os.close();
reader.close();
if (response == null || response.startsWith("ERR")
|| response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response
.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send
* POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (Exception e) {
return false;
}
}
}

View File

@ -0,0 +1,104 @@
package util;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@SuppressWarnings("ALL")
public class boosChat {
private static final Logger log = Logger.getLogger("Minecraft");
private static final List<String> Colors = new LinkedList<>();
private static Server server;
public boosChat(Server server) {
Colors.add("&black&");
Colors.add("&darkblue&");
Colors.add("&darkgreen&");
Colors.add("&darkaqua&");
Colors.add("&darkred&");
Colors.add("&purple&");
Colors.add("&gold&");
Colors.add("&gray&");
Colors.add("&darkgray&");
Colors.add("&blue&");
Colors.add("&green&");
Colors.add("&aqua&");
Colors.add("&red&");
Colors.add("&pink&");
Colors.add("&yellow&");
Colors.add("&white&");
Colors.add("&0");
Colors.add("&1");
Colors.add("&2");
Colors.add("&3");
Colors.add("&4");
Colors.add("&5");
Colors.add("&6");
Colors.add("&7");
Colors.add("&8");
Colors.add("&9");
Colors.add("&a");
Colors.add("&b");
Colors.add("&c");
Colors.add("&d");
Colors.add("&e");
Colors.add("&f");
boosChat.server = server;
}
public static void broadcastMessage(String message) {
message = boosChat.replaceColorCodes(message);
log.info("[bColoredChat] " + message);
server.broadcastMessage(message);
}
private static String replaceColorCodes(String line) {
line = replaceTags(line);
line = line.replaceAll("&", "§");
return line;
}
private static String replaceTags(String line) {
line = line.replaceAll("&black&", "&0");
line = line.replaceAll("&darkblue&", "&1");
line = line.replaceAll("&darkgreen&", "&2");
line = line.replaceAll("&darkaqua&", "&3");
line = line.replaceAll("&darkred&", "&4");
line = line.replaceAll("&purple&", "&5");
line = line.replaceAll("&gold&", "&6");
line = line.replaceAll("&gray&", "&7");
line = line.replaceAll("&darkgray&", "&8");
line = line.replaceAll("&blue&", "&9");
line = line.replaceAll("&green&", "&a");
line = line.replaceAll("&aqua&", "&b");
line = line.replaceAll("&red&", "&c");
line = line.replaceAll("&pink&", "&d");
line = line.replaceAll("&yellow&", "&e");
line = line.replaceAll("&white&", "&f");
return line;
}
public static void sendMessageToCommandSender(CommandSender sender,
String message) {
if (sender instanceof Player) {
boosChat.sendMessageToPlayer((Player) sender, message);
} else {
boosChat.sendMessageToServer(message);
}
}
public static void sendMessageToPlayer(Player player, String message) {
message = boosChat.replaceColorCodes(message);
player.sendMessage(message);
}
private static void sendMessageToServer(String message) {
message = boosChat.replaceColorCodes(message);
log.info(message);
}
}

View File

@ -0,0 +1,232 @@
options:
options:
#should warmups be enabled?
warmups_enabled: true
#should cooldowns be enabled?
cooldowns_enabled: true
#should prices be enabled?
prices_enabled: true
#should item costs be enabled?
item_cost_enabled: true
#should xp costs be enabled?
xp_cost_enabled: true
#should limits be enabled?
limits_enabled: true
#do not ever use this if you like your server
auto_save_enabled_CAN_CAUSE_BIG_LAGS: false
#if you have enabled the forbidden option above, this is how often in minutes will your server lag
save_interval_in_minutes: 15
#should warmups be canceled when player takes damage?
cancel_warmup_on_damage: false
#should warmups be canceled when player moves?
cancel_warmup_on_move: false
#should warmups be canceled when player toggles sneak?
cancel_warmup_on_sneak: false
#should warmups be canceled when player starts sprinting?
cancel_warmup_on_sprint: false
#should warmups be canceled when player changes gamemode?
cancel_warmup_on_gamemode_change: false
#should container access be disable during warmups?
block_interact_during_warmup: false
#should cooldowns be cleared on server restart?
clear_on_restart: false
#should limits (counts of how many times player used limited command) be cleared on server restart?
clear_uses_on_death: false
#should cooldowns be cleared on players death?
clear_cooldowns_on_death: false
#should cooldowns be started on players death?
start_cooldowns_on_death: false
#should command usages be logged to console? (not needed as spigot logs it already)
command_logging: false
#should commands signs be enabled?
command_signs: false
#should syntax blocker (blocks usage of commands with syntax /pluginname:command) be enabled?
syntax_blocker_enabled: true
#should command confirmations (when command has price, xp price or itemcost) be enabled?
command_confirmation: true
units:
#time unit for seconds that will be shown in messages
seconds: seconds
#time unit for minutes that will be shown in messages
minutes: minutes
#time unit for hours that will be shown in messages
hours: hours
messages:
warmup_cancelled_by_damage: '&6Warm-ups have been cancelled due to receiving damage.&f'
warmup_cancelled_by_move: '&6Warm-ups have been cancelled due to moving.&f'
warmup_cancelled_by_sprint: '&6Warm-ups have been cancelled due to sprinting.&f'
warmup_cancelled_by_sneak: '&6Warm-ups have been cancelled due to sneaking.&f'
warmup_cancelled_by_gamemode_change: '&6Warm-ups have been cancelled due to changing
gamemode.&f'
cooling_down: '&6Wait&e &seconds& &unit&&6 before you can use command&e &command&
&6again.&f'
warming_up: '&6Wait&e &seconds& &unit&&6 before command&e &command& &6has warmed
up.&f'
warmup_already_started: '&6Warm-Up process for&e &command& &6has already started.&f'
paid_error: '&6An error has occured:&e %s'
insufficient_funds: '&6You have insufficient funds!&e &command& &6costs &e%s &6but
you only have &e%s'
paid_for_command: '&6Price of&e &command& &6was&e %s &6and you now have&e %s'
paid_items_for_command: '&6Price of&e &command& &6was &e%s'
paid_xp_for_command: '&6Price of&e &command& &6was &e%s levels'
insufficient_items: '&6You have not enough items!&e &command& &6needs &e%s'
insufficient_xp: '&6You have not enough XP!&e &command& &6needs &e%s'
limit_achieved: '&6You cannot use this command anymore!&f'
limit_reset: '&6Wait&e &seconds& &unit&&6 before your limit for command&e &command&
&6is reset.&f'
limit_reset_now: '&6Reseting limits for command&e &command& &6now!&f'
limit_list: '&6Limit for command &e&command&&6 is &e&limit&&6. You can still use
it &e&times&&6 times.&f'
interact_blocked_during_warmup: '&6You can''t do this when command is warming-up!&f'
cannot_create_sign: '&6You are not allowed to create this kind of signs!&f'
cannot_use_sign: '&6You are not allowed to use this sign!&f'
invalid_command_syntax: '&6You are not allowed to use command syntax /<pluginname>:<command>!'
confirmation_message: '&6Would you like to use command&e &command& &6?'
confirmation_price_of_command: '&6its price is&e &price& &6and you now have &e&balance&'
confirmation_item_price_of_command: '&6its price is&e &itemprice& &itemname&'
confirmation_limit_of_command: '&6it is limited to&e &limit& &6uses and you can still use it&e &uses& &6times'
confirmation_xp_price_of_command: '&6its price is&e &xpprice& experience levels'
confirmation_confirm_command_execution: 'Yes'
confirmation_cancel_command_execution: 'No'
confirmation_command_cancelled: '&6Execution of command&e &command& &6was cancelled'
confirmation_toggle_disable: 'Confirmation messages are now disabled for you!'
confirmation_toggle_enable: 'Confirmation messages are now enabled for you!'
commands:
#plugin is disabled for OPs so keep that in mind while testing!
groups:
#this group will work for all players without any booscooldowns permission
default:
/permissionstest:
#permission required to use this command
permission: "nice.permission"
#message that is sent to players who does not have above permission and attepts to use this command
denied_message: '&cYou lack required permissions to use this command!'
/day_command:
#limited to 5 uses per player
limit: 5
#shared limit with /night_command, when player uses this command it will also reduce players limit for all shared_limit commands
shared_limit:
- /night_command
/night_command:
#limited to 5 uses but not shared, so when used it will only reduce players limit for itself
limit: 5
#this will only put cooldown on exactly /command parameter
/command parameter:
cooldown: 2 hours
#this will put cooldown on /commandwithparameters with parameters only eg.:
# /commandwithparameters home
# /commandwithparameters warp spawn hell
# this will not be affected: /commandwithparameters
/commandwithparameters *:
cooldown: 5 seconds
#this will put cooldown on /commandnewparams and all its parameters and continuations eg.:
# /commandnewparams
# /commandnewparams home
# /commandnewparams warp spawn hell
# /commandnewparamsprettylong
# /commandnewparamsprettylong and cool
/commandnewparams*:
cooldown: 5 hours
/anothercommand:
cooldown: 2 minute
/yetanothercommand:
#5 second delay between sending the command to chat and actually executing it
warmup: 5
#price of 10 money
price: 10.0
limit: 5
#potion effect and its strength that will affect player for the warmup time (5 seconds here) has to be one from this list: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/potion/PotionEffectType.html
potion: WEAKNESS,3
/test:
#message that is sent to player when he uses this command
message: You just used /test!
limit: 1
/shared_example:
cooldown: 6 hours
#same as shared_limit except for cooldown, will start cooldown on itself and all commands listed below shared_cooldown
shared_cooldown:
- /this_commands_cooldown_will_also_be_started
- /another_one
/this_commands_cooldown_will_also_be_started:
cooldown: 1 week
/another_one:
cooldown: 1 month
/per_time_interval_limit:
limit: 1
#limit will be automatically cleared after set time (you can set something like 5 uses per hour and so)
limit_reset_delay: 120
/original *:
cooldown: 5
warmup: 1
limit: 10
/testitemcommand:
#price in items required to use this command
itemcost:
#item type (material) has to be one from this list: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html
item: STONE
#number of items required to use command
count: 5
#name of required item
name: "Super Stone"
#lore of required item (any number of lines)
lore:
- "first line of lore"
- "second line of lore"
#enchants of required item and enchant level enchant name has to be one from this list: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/enchantments/Enchantment.html
enchants:
- ARROW_DAMAGE,1
- ARROW_FIRE,1
/testitemcommand2:
#item cost without enchants
itemcost:
item: STONE
count: 5
name: "Super"
lore:
- "1"
- "2"
/testitemcommand3:
#item cost without lore
itemcost:
item: STONE
count: 5
name: "Super"
enchants:
- DAMAGE_ARTHROPODS,5
/testitemcommand4:
#item cost without name
itemcost:
item: STONE
count: 5
lore:
- "1"
- "2"
enchants:
- DAMAGE_ARTHROPODS,5
/testitemcommand5:
#item cost without enchants, lore and name
itemcost:
item: STONE
count: 5
/testxpcommand:
#this command costs 5 experience levels to be used
xpcost: 5
#this group will only work for players that have booscooldowns.vip permission (player can only have one group at a time and no inheritance is possible atm
vip:
/command *:
warmup: 5
#players can use /newcommand and it will execute /originalcommand instead
#/ja * works for parameters and executes /me firstParameter secondParameter remainingParameters worldPlayerIsIn playerName
aliases:
/newcommand: /originalcommand
/ja *: /me $1 $2 $* $world $player
#this will clear limits of command for all players at the same time
#this delay can be started by /bcd startglobalreset
#delay is calculated from the time of command usage (using command on midnight with 1 day delay will reset limits every midnight)
#if the server is offline during limit reset time, it will reset limits as soon as the server starts again
#to cancel delays, delete command from config below and run the command /bcd startglobalreset
global:
/test:
limit_reset_delay: 1 hour
/original *:
limit_reset_delay: 360 minutes

View File

@ -1,6 +1,6 @@
name: boosCooldowns
main: cz.boosik.boosCooldown.BoosCoolDown
version: 3.9.8c-GIT
version: 3.11.0
authors: [LordBoos (boosik)]
softdepend: [Vault]
description: >

64
pom.xml
View File

@ -1,16 +1,25 @@
<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">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>
<groupId>cz.boosik</groupId>
<artifactId>boosCooldowns</artifactId>
<version>3.10.1-GIT</version>
<name>boosCooldowns</name>
<packaging>jar</packaging>
<version>${boosCooldowns.version}</version>
<modules>
<module>nms/NMS_hook_1_8_R1</module>
<module>nms/NMS_hook_1_8_R2</module>
<module>nms/NMS_hook_1_8_R3</module>
<module>nms/NMS_hook_1_9_R1</module>
<module>nms/NMS</module>
<module>plugin</module>
<module>jar</module>
</modules>
<packaging>pom</packaging>
<url>http://maven.apache.org</url>
<properties>
<boosCooldowns.version>3.11.0</boosCooldowns.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<minecraft.version>1.9</minecraft.version>
<minecraft.version>1.9.2</minecraft.version>
<bukkit.version>R0.1</bukkit.version>
<bukkit.packet>v1_9_R1</bukkit.packet>
</properties>
@ -39,44 +48,9 @@
<id>spigot-repo</id>
<url>http://repo.md-5.net/content/repositories/snapshots/</url>
</repository>
<repository>
<id>elmakers-spigot-repo</id>
<url>http://maven.elmakers.com/repository/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>${minecraft.version}-${bukkit.version}-SNAPSHOT</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>LATEST</version>
</dependency>
</dependencies>
<build>
<finalName>boosCooldowns</finalName>
<sourceDirectory>${basedir}/src/main/java/</sourceDirectory>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,62 +0,0 @@
package cz.boosik.boosCooldown.Managers;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import util.boosChat;
public class BoosItemCostManager {
private static boolean payItemForCommand(Player player,
String originalCommand, String item, int count) {
Material material = Material.getMaterial(item);
Inventory inventory = player.getInventory();
Boolean trans = false;
if (inventory.contains(material, count)) {
ItemStack itemstack = new ItemStack(material, count);
inventory.removeItem(itemstack);
trans = true;
}
if (trans) {
String msg = String.format(
BoosConfigManager.getPaidItemsForCommandMessage(), count
+ " " + item);
msg = msg.replaceAll("&command&", originalCommand);
boosChat.sendMessageToPlayer(player, msg);
return true;
} else {
return false;
}
}
public static void payItemForCommand(PlayerCommandPreprocessEvent event,
Player player, String regexCommand, String originalCommand,
String item, int count) {
if (count > 0) {
if (!player.hasPermission("booscooldowns.noitemcost")
&& !player.hasPermission("booscooldowns.noitemcost."
+ originalCommand)) {
if (!payItemForCommand(player, originalCommand,
item, count)) {
BoosCoolDownManager.cancelCooldown(player, regexCommand);
event.setCancelled(true);
}
}
}
}
public static boolean has(Player player, String item, int count) {
if (item.equals("")) {
return true;
}
if (count <= 0) {
return true;
}
Material material = Material.getMaterial(item);
Inventory inventory = player.getInventory();
return inventory.contains(material, count);
}
}

View File

@ -1,560 +0,0 @@
/*
* Copyright 2011-2013 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package org.mcstats;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import cz.boosik.boosCooldown.BoosCoolDown;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
@SuppressWarnings("ALL")
public class MetricsLite {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private final static int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin;
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* Id of the scheduled task
*/
private volatile BukkitTask task = null;
public MetricsLite(Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org")
.copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
/**
* Start measuring statistics. This will immediately create an async
* repeating task as the plugin and send the initial data to the metrics
* backend, and then after that it will post in increments of PING_INTERVAL
* * 1200 ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler()
.runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide
// with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the
// server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it
// is the first time we are posting,
// it is not a interval ping, so it evaluates to
// FALSE
// Each time thereafter it will evaluate to
// TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the
* config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the
* config file and canceling the metrics task.
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data
* such as the GUID and opt-out status
*
* @return the File object for the config file
*/
File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(boolean isPing) throws IOException {
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if
// online
// mode is
// enabled
String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion();
int playersOnline = 0;
try {
playersOnline = Bukkit.getServer().getOnlinePlayers().size();
} catch (Exception e) {
BoosCoolDown
.getLog()
.warning(
"[boosCooldowns] This error was caused because you are using old CraftBukkit version. Please update to 1.7.10 (1.7.9-R0.3).");
}
// END server software specific section -- all code below does not use
// any code outside of this class / Java
// Construct the post data
StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as
// name, version, author, etc
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL
+ String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length",
Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
System.out.println("[Metrics] Prepared request for " + pluginName
+ " uncompressed=" + uncompressed.length + " compressed="
+ compressed.length);
}
// Write the data
OutputStream os = connection.getOutputStream();
os.write(compressed);
os.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String response = reader.readLine();
// close resources
os.close();
reader.close();
if (response == null || response.startsWith("ERR")
|| response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response
.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
}
}
/**
* GZip compress a string of bytes
*
* @param input
* @return
*/
private static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null)
try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send
* POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (Exception e) {
return false;
}
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key,
String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return
*/
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text
* the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text)
throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
}

View File

@ -1,106 +0,0 @@
package util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
@SuppressWarnings("ALL")
public class boosChat {
private static final Logger log = Logger.getLogger("Minecraft");
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private static final List<String> Colors = new LinkedList<>();
private static Server server;
@SuppressWarnings("UnusedDeclaration")
public static void broadcastMessage(String message) {
message = boosChat.replaceColorCodes(message);
log.info("[bColoredChat] " + message);
server.broadcastMessage(message);
}
private static String replaceColorCodes(String line) {
line = replaceTags(line);
line = line.replaceAll("&", "§");
return line;
}
private static String replaceTags(String line) {
line = line.replaceAll("&black&", "&0");
line = line.replaceAll("&darkblue&", "&1");
line = line.replaceAll("&darkgreen&", "&2");
line = line.replaceAll("&darkaqua&", "&3");
line = line.replaceAll("&darkred&", "&4");
line = line.replaceAll("&purple&", "&5");
line = line.replaceAll("&gold&", "&6");
line = line.replaceAll("&gray&", "&7");
line = line.replaceAll("&darkgray&", "&8");
line = line.replaceAll("&blue&", "&9");
line = line.replaceAll("&green&", "&a");
line = line.replaceAll("&aqua&", "&b");
line = line.replaceAll("&red&", "&c");
line = line.replaceAll("&pink&", "&d");
line = line.replaceAll("&yellow&", "&e");
line = line.replaceAll("&white&", "&f");
return line;
}
public static void sendMessageToCommandSender(CommandSender sender,
String message) {
if (sender instanceof Player) {
boosChat.sendMessageToPlayer((Player) sender, message);
} else {
boosChat.sendMessageToServer(message);
}
}
public static void sendMessageToPlayer(Player player, String message) {
message = boosChat.replaceColorCodes(message);
player.sendMessage(message);
}
private static void sendMessageToServer(String message) {
message = boosChat.replaceColorCodes(message);
log.info(message);
}
public boosChat(Server server) {
Colors.add("&black&");
Colors.add("&darkblue&");
Colors.add("&darkgreen&");
Colors.add("&darkaqua&");
Colors.add("&darkred&");
Colors.add("&purple&");
Colors.add("&gold&");
Colors.add("&gray&");
Colors.add("&darkgray&");
Colors.add("&blue&");
Colors.add("&green&");
Colors.add("&aqua&");
Colors.add("&red&");
Colors.add("&pink&");
Colors.add("&yellow&");
Colors.add("&white&");
Colors.add("&0");
Colors.add("&1");
Colors.add("&2");
Colors.add("&3");
Colors.add("&4");
Colors.add("&5");
Colors.add("&6");
Colors.add("&7");
Colors.add("&8");
Colors.add("&9");
Colors.add("&a");
Colors.add("&b");
Colors.add("&c");
Colors.add("&d");
Colors.add("&e");
Colors.add("&f");
boosChat.server = server;
}
}

View File

@ -1,127 +0,0 @@
options:
options:
warmups_enabled: true
cooldowns_enabled: true
prices_enabled: true
item_cost_enabled: true
xp_cost_enabled: true
limits_enabled: true
auto_save_enabled_CAN_CAUSE_BIG_LAGS: false
save_interval_in_minutes: 15
cancel_warmup_on_damage: false
cancel_warmup_on_move: false
cancel_warmup_on_sneak: false
cancel_warmup_on_sprint: false
cancel_warmup_on_gamemode_change: false
block_interact_during_warmup: false
clear_on_restart: false
clear_uses_on_death: false
clear_cooldowns_on_death: false
start_cooldowns_on_death: false
command_logging: false
command_signs: false
syntax_blocker_enabled: true
command_confirmation: true
units:
seconds: seconds
minutes: minutes
hours: hours
messages:
warmup_cancelled_by_damage: '&6Warm-ups have been cancelled due to receiving damage.&f'
warmup_cancelled_by_move: '&6Warm-ups have been cancelled due to moving.&f'
warmup_cancelled_by_sprint: '&6Warm-ups have been cancelled due to sprinting.&f'
warmup_cancelled_by_sneak: '&6Warm-ups have been cancelled due to sneaking.&f'
warmup_cancelled_by_gamemode_change: '&6Warm-ups have been cancelled due to changing
gamemode.&f'
cooling_down: '&6Wait&e &seconds& &unit&&6 before you can use command&e &command&
&6again.&f'
warming_up: '&6Wait&e &seconds& &unit&&6 before command&e &command& &6has warmed
up.&f'
warmup_already_started: '&6Warm-Up process for&e &command& &6has already started.&f'
paid_error: '&6An error has occured:&e %s'
insufficient_funds: '&6You have insufficient funds!&e &command& &6costs &e%s &6but
you only have &e%s'
paid_for_command: '&6Price of&e &command& &6was&e %s &6and you now have&e %s'
paid_items_for_command: '&6Price of&e &command& &6was &e%s'
paid_xp_for_command: '&6Price of&e &command& &6was &e%s levels'
insufficient_items: '&6You have not enough items!&e &command& &6needs &e%s'
insufficient_xp: '&6You have not enough XP!&e &command& &6needs &e%s'
limit_achieved: '&6You cannot use this command anymore!&f'
limit_reset: '&6Wait&e &seconds& &unit&&6 before your limit for command&e &command&
&6is reset.&f'
limit_reset_now: '&6Reseting limits for command&e &command& &6now!&f'
limit_list: '&6Limit for command &e&command&&6 is &e&limit&&6. You can still use
it &e&times&&6 times.&f'
interact_blocked_during_warmup: '&6You can''t do this when command is warming-up!&f'
cannot_create_sign: '&6You are not allowed to create this kind of signs!&f'
cannot_use_sign: '&6You are not allowed to use this sign!&f'
invalid_command_syntax: '&6You are not allowed to use command syntax /<pluginname>:<command>!'
confirmation_message: '&6Would you like to use command&e &command& &6?'
confirmation_price_of_command: '&6its price is&e &price& &6and you now have &e&balance&'
confirmation_item_price_of_command: '&6its price is&e &itemprice& &itemname&'
confirmation_limit_of_command: '&6it is limited to&e &limit& &6uses and you can still use it&e &uses& &6times'
confirmation_xp_price_of_command: '&6its price is&e &xpprice& experience levels'
confirmation_confirm_command_execution: 'Yes'
confirmation_cancel_command_execution: 'No'
confirmation_command_cancelled: '&6Execution of command&e &command& &6was cancelled'
confirmation_toggle_disable: 'Confirmation messages are now disabled for you!'
confirmation_toggle_enable: 'Confirmation messages are now enabled for you!'
commands:
groups:
default:
/permissionstest:
permission: "nice.permission"
denied_message: '&cYou lack required permissions to use this command!'
/day_command:
limit: 5
shared_limit:
- /night_command
/night_command:
limit: 5
shared_limit:
- /day_command
/command parameter:
cooldown: 2 hours
/commandwithparameters *:
cooldown: 5 seconds
/anothercommand:
cooldown: 2 minute
/yetanothercommand:
warmup: 5
price: 10.0
limit: 5
potion: WEAKNESS,3
/test:
message: You just used /test!
limit: 1
/shared_example:
cooldown: 6 hours
shared_cooldown:
- /this_commands_cooldown_will_also_be_started
- /another_one
/this_commands_cooldown_will_also_be_started:
cooldown: 1 week
/another_one:
cooldown: 1 month
/per_time_interval_limit:
limit: 1
limit_reset_delay: 120
/original *:
cooldown: 5
warmup: 1
limit: 10
/testitemcommand:
itemcost: STONE,5
/testxpcommand:
xpcost: 5
vip:
/command *:
warmup: 5
aliases:
/newcommand: /originalcommand
/ja *: /me $1 $2 $* $world $player
global:
/test:
limit_reset_delay: 1 hour
/original *:
limit_reset_delay: 360 minutes