, SubListener>> listeners = new HashMap<>();
68 |
69 | /**
70 | * Gets a listener by its string name. Returns null if the listener is
71 | * disabled or not registered.
72 | *
73 | * @since 0.0.1
74 | * @version 0.1.0
75 | *
76 | * @param The {@link SubListener} type
77 | * @param listener An instance of the class type to retrieve
78 | * @return The listener class, null if disabled or not registered
79 | * @throws IllegalArgumentException If the listener isn't registered
80 | */
81 | public static > S getListener(Class listener) {
82 | Validate.isTrue(ListenerManager.isRegistered(listener), "Class is not registered with listener manager");
83 | return (S) ListenerManager.listeners.get(listener);
84 | }
85 |
86 | /**
87 | * Returns the {@link Plugin} relevant to the passed {@link SubListener}
88 | * class
89 | *
90 | * @since 0.1.0
91 | * @version 0.1.0
92 | *
93 | * @param The {@link Plugin} type
94 | * @param The {@link SubListener} type
95 | * @param listener The {@link SubListener} class that was registered
96 | * @return The {@link Plugin} that registered the {@link SubListener}
97 | * @throws IllegalArgumentException If the listener isn't registered
98 | */
99 | public static
> P getRegisteringPlugin(Class listener) {
100 | return ListenerManager.getListener(listener).getPlugin();
101 | }
102 |
103 | /**
104 | * Returns whether or not a listener is registered under the relevant
105 | * listener key
106 | *
107 | * @since 0.0.1
108 | * @version 0.1.0
109 | *
110 | * @param The {@link SubListener} class to get
111 | * @param listener The listener class to look for
112 | * @return {@code true} if registered, {@code false} otherwise
113 | */
114 | public static > boolean isRegistered(Class listener) {
115 | return ListenerManager.listeners.containsKey(listener);
116 | }
117 |
118 | /**
119 | * Returns {@code true} if the passed {@link Listener} has another Listener
120 | * of the same class type already registered for bukkit. This should not be
121 | * used with any listeners that are from an anonymous class, as this will
122 | * return {@code true} for any other anonymous classes as well
123 | *
124 | * @since 0.1.0
125 | * @version 0.1.0
126 | *
127 | * @param p The {@link Plugin} that registers this {@link Listener}
128 | * @param l The {@link Listener} to check
129 | * @return {@code true} if registered to bukkit
130 | */
131 | public static boolean isRegisteredToBukkit(Plugin p, Listener l) {
132 | if (l.getClass().isAnonymousClass()) {
133 | StackTraceElement t = Reflections.getCaller();
134 | Logging.simple().here().print(Level.WARNING, "Passed an anonymous class from %s:%d", t.getClass().getName(), t.getLineNumber());
135 | }
136 | return HandlerList.getRegisteredListeners(p).stream().anyMatch(r -> r.getListener().getClass() == l.getClass());
137 | }
138 |
139 | /**
140 | * Registers a listener through Bukkit and {@link ListenerManager}
141 | *
142 | * @since 0.0.1
143 | * @version 0.1.0
144 | *
145 | * @param The {@link SubListener} class to register
146 | * @param listener The listener to register
147 | * @throws IllegalArgumentException Attempted to register a Listener twice
148 | * @return The listener that was registered
149 | */
150 | public static > S registerListener(S listener) {
151 | Validate.isTrue(!ListenerManager.isRegistered(listener.getClass()),
152 | "Listener Map already contains key: " + listener.getClass().getName());
153 | ListenerManager.listeners.put(listener.getClass(), listener);
154 | if (!ListenerManager.isRegisteredToBukkit(listener.getPlugin(), listener)) {
155 | listener.getPlugin().getServer().getPluginManager().registerEvents(listener, listener.getPlugin());
156 | }
157 | return listener;
158 | }
159 |
160 | /**
161 | * Calls {@link ListenerManager#registerListener(SubListener)} for every
162 | * passed listener. Any exception thrown will be re-thrown after all
163 | * listeners are registered
164 | *
165 | * @since 0.0.1
166 | * @version 0.1.0
167 | *
168 | * @param The {@link SubListener} class to register
169 | * @param listeners The listeners to register
170 | * @throws IllegalArgumentException Attempted to register a Listener twice
171 | */
172 | public static > void registerListeners(T... listeners) {
173 | IllegalArgumentException ex = null;
174 | for (T listener : listeners) {
175 | try {
176 | ListenerManager.registerListener(listener);
177 | } catch (IllegalArgumentException e) {
178 | if (ex != null) {
179 | ex = e;
180 | }
181 | }
182 | }
183 | if (ex != null) {
184 | throw ex;
185 | }
186 | }
187 |
188 | /**
189 | * Unregisters a specific {@link SubListener} from both CodelanxLib and
190 | * Bukkit
191 | *
192 | * @since 0.1.0
193 | * @version 0.1.0
194 | *
195 | * @param listener The {@link SubListener} class to unregister
196 | */
197 | public static void unregisterListener(Class extends SubListener>> listener) {
198 | if (ListenerManager.isRegistered(listener)) {
199 | HandlerList.unregisterAll(ListenerManager.listeners.remove(listener));
200 | }
201 | }
202 |
203 | /**
204 | * Unregisters all the listeners attached to this {@link ListenerManager}.
205 | * Can only be called from {@link CodelanxLib}
206 | *
207 | * @since 0.0.1
208 | * @version 0.1.0
209 | *
210 | * @throws IllegalInvocationException Only {@link CodelanxLib} can use
211 | */
212 | public static void release() {
213 | Exceptions.illegalInvocation(Reflections.accessedFrom(CodelanxLib.class),
214 | "ListenerManager#release may only be called by CodelanxLib");
215 | ListenerManager.listeners.values().forEach((l) -> {
216 | l.onDisable();
217 | HandlerList.unregisterAll(l);
218 | });
219 | ListenerManager.listeners.clear();
220 | }
221 |
222 | /**
223 | * Allows registering an anonymous listener for any bukkit listeners using
224 | * Java 8's function API, useful for listening to events in one-liner solutions
225 | *
226 | * @since 0.2.0
227 | * @version 0.2.0
228 | *
229 | * @param clazz The {@link Event} fired within Bukkit to listen to
230 | * @param event A {@link Consumer} of the event, called when the event is fired
231 | * @param The type of the {@link Event}
232 | */
233 | public static void listen(Class clazz, Consumer event) {
234 | ListenerManager.registerListener(new SubListener(ReflectBukkit.getCallingPlugin()) {
235 |
236 | @EventHandler
237 | public void handle(T bukkitEvent) {
238 | event.accept(bukkitEvent);
239 | }
240 | });
241 | }
242 |
243 | }
244 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/listener/SubListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.listener;
21 |
22 | import org.bukkit.event.Listener;
23 | import org.bukkit.plugin.Plugin;
24 |
25 | /**
26 | * Handles events that are called by Bukkit's event system. On an implementation
27 | * level, this is relatively the same as Bukkit's {@link Listener} class (and
28 | * even implements said interface), however it also provides methods for simpler
29 | * registration as well as a simple constructor to ensure a plugin instance is
30 | * available
31 | *
32 | * @since 0.0.1
33 | * @author 1Rogue
34 | * @version 0.1.0
35 | *
36 | * @param The specific {@link Plugin} to use
37 | */
38 | public abstract class SubListener implements Listener {
39 |
40 | /**
41 | * The stored {@link Plugin} reference relevant to this {@link SubListener}
42 | *
43 | * @since 0.0.1
44 | * @version 0.0.1
45 | */
46 | protected final T plugin;
47 |
48 | /**
49 | * Stores the {@link Plugin} reference
50 | *
51 | * @since 0.0.1
52 | * @version 0.1.0
53 | *
54 | * @param plugin The {@link Plugin} relevant to this {@link SubListener}
55 | */
56 | public SubListener(T plugin) {
57 | this.plugin = plugin;
58 | }
59 |
60 | /**
61 | * Called when the plugin is being disabled. This is a convenience method to
62 | * allow simple cleanup of any resources
63 | *
64 | * @since 0.1.0
65 | * @version 0.1.0
66 | */
67 | public void onDisable() {}
68 |
69 | /**
70 | * Returns the {@link Plugin} used for this {@link SubListener}
71 | *
72 | * @since 0.1.0
73 | * @version 0.1.0
74 | *
75 | * @return The {@link Plugin} that registered this {@link SubListener}
76 | */
77 | public T getPlugin() {
78 | return this.plugin;
79 | }
80 |
81 | /**
82 | * Registers the listener to the {@link ListenerManager}. If the listener
83 | * class is already registered, this method will do nothing.
84 | *
85 | * @since 0.1.0
86 | * @version 0.1.0
87 | */
88 | public final void register() {
89 | if (!ListenerManager.isRegistered(this.getClass())) {
90 | ListenerManager.registerListener(this);
91 | }
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/permission/Permissions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.permission;
21 |
22 | import org.apache.commons.lang.Validate;
23 | import org.bukkit.Bukkit;
24 | import org.bukkit.permissions.Permissible;
25 | import org.bukkit.permissions.Permission;
26 | import org.bukkit.plugin.PluginManager;
27 |
28 | /**
29 | * Represents a single permission value for use with checking whether or not a
30 | * {@link org.bukkit.permissions.Permissible Permissible} has a specific
31 | * permission or not. Meant for use on enum types
32 | *
33 | * @since 0.1.0
34 | * @author 1Rogue
35 | * @version 0.1.0
36 | */
37 | public interface Permissions {
38 |
39 | /**
40 | * Returns the base permission node for the plugin. e.g. "commons".
41 | *
42 | * @since 0.1.0
43 | * @version 0.1.0
44 | *
45 | * @return The base permission node to prefix all permissions
46 | */
47 | public String getBase();
48 |
49 | /**
50 | * Returns the raw node for the specified enum constant without prefixing
51 | *
52 | * @since 0.1.0
53 | * @version 0.1.0
54 | *
55 | * @return The permission suffix supplied by the enum
56 | */
57 | public String getNode();
58 |
59 | /**
60 | * Builds the full permission string
61 | *
62 | * @since 0.1.0
63 | * @version 0.1.0
64 | *
65 | * @return The full permission string
66 | */
67 | default public String build() {
68 | String median = ".";
69 | if (this.getBase().endsWith(median)) {
70 | median = "";
71 | }
72 | return this.getBase().toLowerCase() + median + this.getNode().toLowerCase();
73 | }
74 |
75 | /**
76 | * Determines whether or not the {@link Permissible} has this permission
77 | *
78 | * @since 0.1.0
79 | * @version 0.1.0
80 | *
81 | * @param p The {@link Permissible} to check permissions for
82 | * @return {@code true} if the {@link Permissible} has the permissions
83 | */
84 | default public boolean has(Permissible p) {
85 | Validate.notNull(p, "Player cannot be null");
86 | //Register permission to conform to Bukkit API
87 | String fullPerm = this.build();
88 | PluginManager pm = Bukkit.getServer().getPluginManager();
89 | if (pm.getPermission(fullPerm) == null) {
90 | pm.addPermission(new Permission(fullPerm));
91 | }
92 | //end register
93 | return p.hasPermission(fullPerm);
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/serialize/SInventory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.serialize;
21 |
22 | import org.bukkit.configuration.serialization.ConfigurationSerializable;
23 | import org.bukkit.configuration.serialization.SerializableAs;
24 | import org.bukkit.inventory.ItemStack;
25 |
26 | import java.util.ArrayList;
27 | import java.util.Arrays;
28 | import java.util.Collection;
29 | import java.util.Collections;
30 | import java.util.HashMap;
31 | import java.util.List;
32 | import java.util.Map;
33 | import java.util.stream.Collectors;
34 |
35 | /**
36 | * Represents an Inventory which is ready to be serialized
37 | *
38 | * @since 0.0.1
39 | * @author 1Rogue
40 | * @version 0.0.1
41 | */
42 | @SerializableAs("Inventory")
43 | public class SInventory implements ConfigurationSerializable {
44 |
45 | /**
46 | * Represents a collection of the relevant inventory items
47 | *
48 | * @since 0.0.1
49 | * @version 0.0.1
50 | */
51 | protected final List items = new ArrayList<>();
52 |
53 | /**
54 | * Copies the passed {@link ItemStack} objects
55 | *
56 | * @since 0.0.1
57 | * @version 0.0.1
58 | *
59 | * @param contents The {@link ItemStack}s to copy
60 | */
61 | public SInventory(ItemStack... contents) {
62 | this.items.addAll(Arrays.asList(contents).stream()
63 | .map(i -> i.clone()).collect(Collectors.toList()));
64 | }
65 |
66 | /**
67 | * {@link ConfigurationSerializable} constructor. Should not be used by
68 | * anything other than Bukkit.
69 | *
70 | * @since 0.0.1
71 | * @version 0.0.1
72 | *
73 | * @param config A serialized {@link Map} of this object
74 | */
75 | @SuppressWarnings("unchecked")
76 | public SInventory(Map config) {
77 | this.items.addAll((Collection extends ItemStack>) config.get("items"));
78 | }
79 |
80 | /**
81 | * Returns a copy of this instance's stored {@link ItemStack ItemStacks}
82 | *
83 | * @since 0.0.1
84 | * @version 0.0.1
85 | *
86 | * @return A copy of the relevant {@link ItemStack ItemStacks}
87 | */
88 | public List getContents() {
89 | return Collections.unmodifiableList(this.items.stream().map(i -> i.clone())
90 | .collect(Collectors.toList()));
91 | }
92 |
93 | /**
94 | * Returns a copy of this instance's stored {@link ItemStack ItemStacks}
95 | *
96 | * @since 0.0.1
97 | * @version 0.0.1
98 | *
99 | * @return A copy of the relevant {@link ItemStack ItemStacks}
100 | */
101 | public ItemStack[] getContentsAsArray() {
102 | return this.getContents().toArray(new ItemStack[this.items.size()]);
103 | }
104 |
105 | /**
106 | * {@inheritDoc}
107 | *
108 | * @since 0.0.1
109 | * @version 0.0.1
110 | *
111 | * @return {@inheritDoc}
112 | */
113 | @Override
114 | public Map serialize() {
115 | Map back = new HashMap<>();
116 | back.put("items", this.items);
117 | return back;
118 | }
119 |
120 | /**
121 | * Creates a new {@link SInventory} object and returns it. Should only be
122 | * used by Bukkit
123 | *
124 | * @since 0.0.1
125 | * @version 0.0.1
126 | *
127 | * @param config A serialized {@link Map} of this object
128 | * @return A new {@link SInventory} object
129 | */
130 | public static SInventory valueOf(Map config) {
131 | return new SInventory(config);
132 | }
133 |
134 | /**
135 | * Creates a new {@link SInventory} object and returns it. Should only be
136 | * used by Bukkit
137 | *
138 | * @since 0.0.1
139 | * @version 0.0.1
140 | *
141 | * @param config A serialized {@link Map} of this object
142 | * @return A new {@link SInventory} object
143 | */
144 | public static SInventory deserialize(Map config) {
145 | return new SInventory(config);
146 | }
147 |
148 | }
149 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/serialize/SLocation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.serialize;
21 |
22 | import org.bukkit.Bukkit;
23 | import org.bukkit.Location;
24 | import org.bukkit.World;
25 | import org.bukkit.configuration.serialization.ConfigurationSerializable;
26 | import org.bukkit.configuration.serialization.SerializableAs;
27 | import org.bukkit.util.Vector;
28 |
29 | import java.util.HashMap;
30 | import java.util.Map;
31 | import java.util.UUID;
32 |
33 | /**
34 | * Represents a {@link ConfigurationSerializable} {@link Location} with a lazily
35 | * initialized world
36 | *
37 | * @since 0.0.1
38 | * @author 1Rogue
39 | * @version 0.0.1
40 | */
41 | @SerializableAs("Location")
42 | public class SLocation implements ConfigurationSerializable {
43 |
44 | private final Vector loc;
45 | private final float yaw;
46 | private final float pitch;
47 | private final UUID uuid;
48 | private World world;
49 |
50 | static {
51 |
52 | }
53 |
54 | /**
55 | * Creates a new {@link SLocation} object from the passed {@link Location}
56 | *
57 | * @since 0.0.1
58 | * @version 0.0.1
59 | *
60 | * @param loc The {@link Location} to serialize
61 | */
62 | public SLocation(Location loc) {
63 | this.loc = loc.toVector();
64 | this.yaw = loc.getYaw();
65 | this.pitch = loc.getPitch();
66 | this.uuid = loc.getWorld().getUID();
67 | }
68 |
69 | /**
70 | * Allows constructing an {@link SLocation} from serialized parts
71 | *
72 | * @since 0.1.0
73 | * @version 0.1.0
74 | *
75 | * @param loc The relevant {@link Vector}
76 | * @param worldUUID The {@link UUID} of the world for this {@link SLocation}
77 | * @param pitch The pitch
78 | * @param yaw The yaw
79 | */
80 | public SLocation(Vector loc, UUID worldUUID, float pitch, float yaw) {
81 | this.loc = loc;
82 | this.uuid = worldUUID;
83 | this.pitch = pitch;
84 | this.yaw = yaw;
85 | }
86 |
87 | /**
88 | * {@link ConfigurationSerializable} constructor. Should not be used by
89 | * anything other than Bukkit.
90 | *
91 | * @since 0.0.1
92 | * @version 0.0.1
93 | *
94 | * @param config A serialized {@link Map} of this object
95 | */
96 | public SLocation(Map config) {
97 | this.loc = (Vector) config.get("location");
98 | this.uuid = UUID.fromString((String) config.get("world"));
99 | this.pitch = config.containsKey("pitch") ? ((Number) config.get("pitch")).floatValue() : 0F;
100 | this.yaw = config.containsKey("yaw") ? ((Number) config.get("yaw")).floatValue() : 0F;
101 | }
102 |
103 | /**
104 | * {@inheritDoc}
105 | *
106 | * @since 0.0.1
107 | * @version 0.0.1
108 | *
109 | * @return {@inheritDoc}
110 | */
111 | @Override
112 | public Map serialize() {
113 | Map back = new HashMap<>();
114 | back.put("location", this.loc);
115 | back.put("world", this.uuid.toString());
116 | back.put("pitch", this.pitch);
117 | back.put("yaw", this.yaw);
118 | return back;
119 | }
120 |
121 | /**
122 | * Creates a new {@link SLocation} object and returns it. Should only be
123 | * used by Bukkit
124 | *
125 | * @since 0.0.1
126 | * @version 0.0.1
127 | *
128 | * @param config A serialized {@link Map} of this object
129 | * @return A new {@link SLocation} object
130 | */
131 | public static SLocation valueOf(Map config) {
132 | return new SLocation(config);
133 | }
134 |
135 | /**
136 | * Creates a new {@link SLocation} object and returns it. Should only be
137 | * used by Bukkit
138 | *
139 | * @since 0.0.1
140 | * @version 0.0.1
141 | *
142 | * @param config A serialized {@link Map} of this object
143 | * @return A new {@link SLocation} object
144 | */
145 | public static SLocation deserialize(Map config) {
146 | return new SLocation(config);
147 | }
148 |
149 | /**
150 | * Retrieves the {@link World} object relevant to this instance. This is
151 | * lazily-initialized, so until this method is called the class will not
152 | * attempt to retrieve the {@link World} value
153 | *
154 | * @since 0.0.1
155 | * @version 0.0.1
156 | *
157 | * @return The relevant {@link World} object, or {@code null} if not found
158 | */
159 | public World getWorld() {
160 | if (this.world == null) {
161 | this.world = Bukkit.getWorld(this.uuid);
162 | }
163 | return this.world;
164 | }
165 |
166 | /**
167 | * Returns the relevant {@link Vector} object to this instance
168 | *
169 | * @since 0.0.1
170 | * @version 0.0.1
171 | *
172 | * @return The relevant {@link Vector} object
173 | */
174 | public Vector getVector() {
175 | return this.loc;
176 | }
177 |
178 | /**
179 | * Converts this instance into a {@link Location} object. This method will
180 | * fail if called before Bukkit has loaded any worlds
181 | *
182 | * @since 0.0.1
183 | * @version 0.0.1
184 | *
185 | * @return This instance in the context of a {@link Location} object
186 | */
187 | public Location toLocation() {
188 | return this.getVector().toLocation(this.getWorld(), this.yaw, this.pitch);
189 | }
190 |
191 | }
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/serialize/SPlayerInventory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.serialize;
21 |
22 | import org.apache.commons.lang3.Validate;
23 | import org.bukkit.configuration.serialization.ConfigurationSerializable;
24 | import org.bukkit.configuration.serialization.SerializableAs;
25 | import org.bukkit.inventory.ItemStack;
26 | import org.bukkit.inventory.PlayerInventory;
27 |
28 | import java.util.HashMap;
29 | import java.util.Map;
30 |
31 | /**
32 | * Represents a {@link PlayerInventory} that is capable of being serialized
33 | *
34 | * @since 0.0.1
35 | * @author 1Rogue
36 | * @version 0.0.1
37 | */
38 | @SerializableAs("PlayerInventory")
39 | public class SPlayerInventory implements ConfigurationSerializable {
40 |
41 | /** The {@link ItemStack} stored on the player's head */
42 | protected final ItemStack helmet;
43 | /** The {@link ItemStack} stored on the player's torso */
44 | protected final ItemStack chest;
45 | /** The {@link ItemStack} stored on the player's legs */
46 | protected final ItemStack legs;
47 | /** The {@link ItemStack} stored on the player's feet */
48 | protected final ItemStack boots;
49 | /** The general contents of the player's inventory */
50 | protected final SInventory inv;
51 |
52 | /**
53 | * Copies the contents of the passed {@link PlayerInventory}
54 | *
55 | * @since 0.0.1
56 | * @version 0.0.1
57 | *
58 | * @param inv The {@link PlayerInventory} to copy
59 | */
60 | public SPlayerInventory(PlayerInventory inv) {
61 | Validate.notNull(inv, "PlayerInventory cannot be null");
62 | this.helmet = inv.getHelmet();
63 | this.chest = inv.getChestplate();
64 | this.legs = inv.getLeggings();
65 | this.boots = inv.getBoots();
66 | this.inv = new SInventory(inv.getContents());
67 | }
68 |
69 | /**
70 | * {@link ConfigurationSerializable} constructor. Should not be used by
71 | * anything other than Bukkit.
72 | *
73 | * @since 0.0.1
74 | * @version 0.0.1
75 | *
76 | * @param config A serialized {@link Map} of this object
77 | */
78 | public SPlayerInventory(Map config) {
79 | if (config.isEmpty()) {
80 | this.helmet = this.chest = this.legs = this.boots = null;
81 | this.inv = null;
82 | } else {
83 | this.helmet = (ItemStack) config.get("helmet");
84 | this.chest = (ItemStack) config.get("chest");
85 | this.legs = (ItemStack) config.get("legs");
86 | this.boots = (ItemStack) config.get("boots");
87 | this.inv = (SInventory) config.get("contents");
88 | }
89 | }
90 |
91 | /**
92 | * Returns the item in the helmet slot of the {@link PlayerInventory}
93 | *
94 | * @since 0.1.0
95 | * @version 0.1.0
96 | *
97 | * @return The helmet in the {@link PlayerInventory}
98 | */
99 | public ItemStack getHelmet() {
100 | return this.helmet;
101 | }
102 |
103 | /**
104 | * Returns the item in the torso slot of the {@link PlayerInventory}
105 | *
106 | * @since 0.1.0
107 | * @version 0.1.0
108 | *
109 | * @return The torso in the {@link PlayerInventory}
110 | */
111 | public ItemStack getChestplate() {
112 | return this.chest;
113 | }
114 |
115 | /**
116 | * Returns the item in the pants slot of the {@link PlayerInventory}
117 | *
118 | * @since 0.1.0
119 | * @version 0.1.0
120 | *
121 | * @return The pants in the {@link PlayerInventory}
122 | */
123 | public ItemStack getLeggings() {
124 | return this.legs;
125 | }
126 |
127 | /**
128 | * Returns the item in the boots slot of the {@link PlayerInventory}
129 | *
130 | * @since 0.1.0
131 | * @version 0.1.0
132 | *
133 | * @return The boots in the {@link PlayerInventory}
134 | */
135 | public ItemStack getBoots() {
136 | return this.boots;
137 | }
138 |
139 | /**
140 | * Returns the underlying {@link SInventory} object that stores normal
141 | * inventory items
142 | *
143 | * @since 0.0.1
144 | * @version 0.0.1
145 | *
146 | * @return The underlying {@link SInventory} object
147 | */
148 | public SInventory getInventory() {
149 | return this.inv;
150 | }
151 |
152 | /**
153 | * Sets the current contents of this class into a passed
154 | * {@link PlayerInventory}
155 | *
156 | * @since 0.0.1
157 | * @version 0.0.1
158 | *
159 | * @param inv The {@link PlayerInventory} to store into
160 | */
161 | public void set(PlayerInventory inv) {
162 | inv.setContents(this.getInventory().getContentsAsArray());
163 | inv.setHelmet(this.getHelmet());
164 | inv.setChestplate(this.getChestplate());
165 | inv.setLeggings(this.getLeggings());
166 | inv.setBoots(this.getBoots());
167 | }
168 |
169 | /**
170 | * {@inheritDoc}
171 | *
172 | * @since 0.0.1
173 | * @version 0.0.1
174 | *
175 | * @return {@inheritDoc}
176 | */
177 | @Override
178 | public Map serialize() {
179 | Map back = new HashMap<>();
180 | back.put("helmet", this.helmet);
181 | back.put("chest", this.chest);
182 | back.put("legs", this.legs);
183 | back.put("boots", this.boots);
184 | back.put("contents", this.inv);
185 | return back;
186 | }
187 |
188 | /**
189 | * Creates a new {@link SPlayerInventory} object and returns it. Should only
190 | * be used by Bukkit
191 | *
192 | * @since 0.0.1
193 | * @version 0.0.1
194 | *
195 | * @param config A serialized {@link Map} of this object
196 | * @return A new {@link SPlayerInventory} object
197 | */
198 | public static SPlayerInventory valueOf(Map config) {
199 | return new SPlayerInventory(config);
200 | }
201 |
202 | /**
203 | * Creates a new {@link SPlayerInventory} object and returns it. Should only
204 | * be used by Bukkit
205 | *
206 | * @since 0.0.1
207 | * @version 0.0.1
208 | *
209 | * @param config A serialized {@link Map} of this object
210 | * @return A new {@link SPlayerInventory} object
211 | */
212 | public static SPlayerInventory deserialize(Map config) {
213 | return new SPlayerInventory(config);
214 | }
215 |
216 | }
217 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/serialize/SerializationFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.serialize;
21 |
22 | import org.bukkit.configuration.serialization.ConfigurationSerializable;
23 | import org.bukkit.configuration.serialization.ConfigurationSerialization;
24 |
25 | /**
26 | * Façade for registering {@link ConfigurationSerializable} classes to Bukkit
27 | *
28 | * @since 0.0.1
29 | * @author 1Rogue
30 | * @version 0.1.0
31 | */
32 | public class SerializationFactory {
33 |
34 | /**
35 | * Registers a single {@link ConfigurationSerializable} class to Bukkit
36 | *
37 | * @since 0.0.1
38 | * @version 0.1.0
39 | *
40 | * @param clazz The class to register
41 | */
42 | public static void registerClass(Class extends ConfigurationSerializable> clazz) {
43 | ConfigurationSerialization.registerClass(clazz);
44 | }
45 |
46 | /**
47 | * Registers multiple {@link ConfigurationSerializable} class to Bukkit
48 | *
49 | * @since 0.0.1
50 | * @version 0.1.0
51 | *
52 | * @param clazz The classes to register
53 | */
54 | public static void registerClasses(Class extends ConfigurationSerializable>... clazz) {
55 | for (Class extends ConfigurationSerializable> c : clazz) {
56 | SerializationFactory.registerClass(c);
57 | }
58 | }
59 |
60 | /**
61 | * Registers multiple {@link ConfigurationSerializable} class to Bukkit
62 | *
63 | * @since 0.1.0
64 | * @version 0.1.0
65 | *
66 | * @param clazz The classes to register
67 | */
68 | public static void registerClasses(Iterable extends Class extends ConfigurationSerializable>> clazz) {
69 | clazz.forEach(SerializationFactory::registerClass);
70 | }
71 |
72 | /**
73 | * Returns the native {@link ConfigurationSerializable} classes that are
74 | * provided by CodelanxLib
75 | *
76 | * @since 0.0.1
77 | * @version 0.0.1
78 | *
79 | * @return The native serializable types
80 | */
81 | @SuppressWarnings("rawtypes")
82 | public static Class[] getNativeSerializables() {
83 | return new Class[] {
84 | SInventory.class,
85 | SPlayerInventory.class,
86 | SLocation.class
87 | };
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/BScheduler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import com.codelanx.codelanxlib.CodelanxLib;
23 | import com.codelanx.commons.util.Scheduler;
24 | import org.bukkit.Bukkit;
25 |
26 | import java.util.concurrent.ScheduledFuture;
27 |
28 | public class BScheduler {
29 |
30 | /**
31 | * Runs a task after a specified delay on Bukkit's main thread
32 | *
33 | * @since 0.1.0
34 | * @version 0.1.0
35 | *
36 | * @param r The {@link Runnable} to execute
37 | * @param delay Time (in seconds) to wait before execution
38 | * @return The scheduled task that will execute the provided runnable
39 | */
40 | public static ScheduledFuture> runSyncTask(Runnable r, long delay) {
41 | //TODO: hook bukkit's scheduler directly for this operation
42 | return Scheduler.runAsyncTask(() -> {
43 | Bukkit.getServer().getScheduler().callSyncMethod(CodelanxLib.get(), () -> {
44 | r.run();
45 | return null;
46 | });
47 | }, delay);
48 | }
49 |
50 | /**
51 | * Runs a task after a specified time on Bukkit's main thread, and repeats
52 | * it in intervals as specified by the {@code delay} parameter
53 | *
54 | * @since 0.1.0
55 | * @version 0.1.0
56 | *
57 | * @param r The {@link Runnable} to execute
58 | * @param startAfter Time (in seconds) to wait before executing at all
59 | * @param delay Time (in seconds) to wait in between executions
60 | * @return The scheduled task that will execute the provided runnable
61 | */
62 | public static ScheduledFuture> runSyncTaskRepeat(Runnable r, long startAfter, long delay) {
63 | return Scheduler.runAsyncTaskRepeat(() -> {
64 | Bukkit.getServer().getScheduler().callSyncMethod(CodelanxLib.get(), () -> {
65 | r.run();
66 | return null;
67 | });
68 | }, startAfter, delay);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/BlockData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import org.apache.commons.lang.Validate;
23 | import org.bukkit.Material;
24 | import org.bukkit.block.Block;
25 | import org.bukkit.inventory.ItemStack;
26 | import org.bukkit.material.MaterialData;
27 |
28 | import java.util.Objects;
29 |
30 | /**
31 | * Allows for representing material and it's data counterpart as a single string
32 | *
33 | * @since 0.2.0
34 | * @author 1Rogue
35 | * @version 0.3.1
36 | */
37 | public class BlockData implements Comparable {
38 |
39 | private final Material mat;
40 | private final byte data;
41 |
42 | /**
43 | * Creates a {@link BlockData} instance
44 | *
45 | * @since 0.2.0
46 | * @version 0.2.0
47 | *
48 | * @param mat The {@link Material} value
49 | * @param data A {@code byte} representing an internal data value, set to
50 | * negative to match all data values
51 | */
52 | public BlockData(Material mat, Number data) {
53 | this.mat = mat;
54 | this.data = data.byteValue();
55 | }
56 |
57 | public BlockData(Block b) {
58 | this(b.getType(), b.getData());
59 | }
60 |
61 | public BlockData(ItemStack stack) {
62 | this(stack.getType(), stack.getData().getData());
63 | }
64 |
65 | public BlockData(MaterialData data) {
66 | this(data.getItemType(), data.getData());
67 | }
68 |
69 | public Material getMaterial() {
70 | return this.mat;
71 | }
72 |
73 | public byte getData() {
74 | return this.data;
75 | }
76 |
77 | /**
78 | * Converts this {@link BlockData} to an {@link ItemStack}, which can then
79 | * be assigned to a block
80 | *
81 | * @since 0.2.0
82 | * @version 0.2.0
83 | *
84 | * @return This {@link BlockData} in {@link ItemStack} form
85 | */
86 | public ItemStack toItemStack() {
87 | ItemStack back = new ItemStack(this.mat);
88 | if (this.data > 0) {
89 | back.getData().setData(this.data);
90 | }
91 | return back;
92 | }
93 |
94 | public MaterialData toMaterialData() {
95 | return new MaterialData(this.mat, this.data > 0 ? this.data : 0);
96 | }
97 |
98 | public void toBlock(Block toChange) {
99 | toChange.setType(this.mat);
100 | toChange.setData(this.data > 0 ? this.data : 0);
101 | }
102 |
103 | public boolean matches(ItemStack stack) {
104 | return this.matches(stack.getData());
105 | }
106 |
107 | public boolean matches(Block b) {
108 | return this.mat == b.getType()
109 | && (this.data < 0 || b.getData() == this.data);
110 | }
111 |
112 | public boolean matches(MaterialData data) {
113 | return this.mat == data.getItemType()
114 | && (this.data < 0 || data.getData() == this.data);
115 | }
116 |
117 | @Override
118 | public String toString() {
119 | return this.mat.toString() + (this.data != 0 ? ":" + (this.data < 0 ? "*" : this.data) : "");
120 | }
121 |
122 | /**
123 | * Converts a {@link BlockData} string back into an object instance
124 | *
125 | * @since 0.2.0
126 | * @version 0.2.0
127 | *
128 | * @param in The string to parse
129 | * @return The relevant {@link BlockData}
130 | */
131 | public static BlockData fromString(String in) {
132 | String[] raw = in.split(":");
133 | byte data = 0;
134 | Material mat;
135 | switch (raw.length) {
136 | case 2:
137 | if (raw[1].equals("*")) {
138 | data = -1;
139 | } else {
140 | data = Byte.valueOf(raw[1]);
141 | }
142 | case 1:
143 | mat = Material.matchMaterial(raw[0].toUpperCase());
144 | Validate.notNull(mat);
145 | break;
146 | default:
147 | throw new IllegalArgumentException("Malformed string passed to BlockData#fromString: '" + in + "'");
148 | }
149 | return new BlockData(mat, data);
150 | }
151 |
152 | @Override
153 | public int hashCode() {
154 | int hash = 3;
155 | hash = 41 * hash + Objects.hashCode(this.mat);
156 | hash = 41 * hash + this.data;
157 | return hash;
158 | }
159 |
160 | @Override
161 | public boolean equals(Object obj) {
162 | if (obj == null) {
163 | return false;
164 | }
165 | if (getClass() != obj.getClass()) {
166 | return false;
167 | }
168 | final BlockData other = (BlockData) obj;
169 | if (this.mat != other.mat) {
170 | return false;
171 | }
172 | return this.data == other.data || this.data < 0 || other.data < 0; //TODO: remove comparison exception?
173 | }
174 |
175 | @Override
176 | public int compareTo(BlockData o) {
177 | if (this.mat.ordinal() != o.mat.ordinal()) {
178 | return this.mat.ordinal() - o.mat.ordinal();
179 | } else {
180 | if (this.data < 0 || o.data < 0) {
181 | return 0;
182 | }
183 | return this.data - o.data;
184 | }
185 | }
186 |
187 | }
188 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/Blocks.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import org.bukkit.Material;
23 | import org.bukkit.block.Sign;
24 |
25 | /**
26 | * Utility class for working with any {@link org.bukkit.block.Block Block}
27 | * objects and their derivatives
28 | *
29 | * @since 0.1.0
30 | * @author 1Rogue
31 | * @version 0.1.0
32 | */
33 | public final class Blocks {
34 |
35 | private Blocks() {
36 | }
37 |
38 | /**
39 | * Forcibly sends an update of sign text to any players within a close
40 | * enough range of the sign to render its text
41 | *
42 | * @since 0.1.0
43 | * @version 0.1.0
44 | *
45 | * @param s The {@link Sign} to update
46 | */
47 | public static void updatePlayersInRange(Sign s) {
48 | //Seems to be that entities within ~60 block radius are not sent/updated
49 | Players.getPlayersInRange(65, s.getLocation()).keySet().forEach(p -> {
50 | p.sendSignChange(s.getLocation(), s.getLines());
51 | });
52 | }
53 |
54 | /**
55 | * Returns whether or not a {@link Material} will harm a
56 | * {@link org.bukkit.entity.Player Player} who comes into contact with it
57 | *
58 | * @since 0.1.0
59 | * @version 0.1.0
60 | *
61 | * @param mat The {@link Material} to compare
62 | * @return {@code true} if the material will harm the player
63 | */
64 | public static boolean isHarmful(Material mat) {
65 | switch(mat) {
66 | case LAVA:
67 | case CACTUS:
68 | case FIRE:
69 | case STATIONARY_LAVA:
70 | return true;
71 | default:
72 | return false;
73 | }
74 | }
75 |
76 | /**
77 | * Determines if a material will be liquid when placed
78 | *
79 | * @since 0.1.0
80 | * @version 0.1.0
81 | *
82 | * @param mat The {@link Material} to check
83 | * @return {@code true} if lava or water (non-contained of any kind)
84 | */
85 | public static boolean isLiquid(Material mat) {
86 | switch(mat) {
87 | case LAVA:
88 | case STATIONARY_LAVA:
89 | case WATER:
90 | case STATIONARY_WATER:
91 | return true;
92 | default:
93 | return false;
94 | }
95 | }
96 |
97 | /**
98 | * Determines if a block would be dangerous if above a player's head with
99 | * nothing but air inbetween, assuming no movement on part of the player
100 | *
101 | * @since 0.1.0
102 | * @version 0.1.0
103 | *
104 | * @param mat The {@link Material} to check
105 | * @return {@code true} if a player could be harmed
106 | */
107 | public static boolean isDangerousFromAbove(Material mat) {
108 | switch(mat) {
109 | case LAVA:
110 | case STATIONARY_LAVA:
111 | case SAND:
112 | case GRAVEL:
113 | case ANVIL:
114 | return true;
115 | default:
116 | return false;
117 | }
118 | }
119 |
120 | }
121 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/NMS.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import org.bukkit.potion.PotionEffectType;
23 |
24 | /**
25 | * Represents utility methods for either dealing with or fixing issues with
26 | * minecraft's internal server implementation
27 | *
28 | * @since 0.1.0
29 | * @author 1Rogue
30 | * @version 0.1.0
31 | */
32 | public final class NMS {
33 |
34 | private NMS() {
35 |
36 | }
37 |
38 | /**
39 | * This method returns a duration that is constant-time based upon the given
40 | * {@link PotionEffectType}. Due to NMS internals with "MobEffectType",
41 | * some effects are abstractly divided by 2, to which this method undoes
42 | * that division for the relevant effects. Note this is a hardcoded method
43 | * which is up-to-date for Minecraft 1.8.*
44 | *
45 | * @param type The {@link PotionEffectType} to check
46 | * @param duration The duration for the effect
47 | * @return The same duration provided, multiplied by 2 for "flagged" effects
48 | */
49 | public int fixPotionEffectDuration(PotionEffectType type, int duration) {
50 | if (type == PotionEffectType.SLOW
51 | || type == PotionEffectType.SLOW_DIGGING
52 | || type == PotionEffectType.HARM
53 | || type == PotionEffectType.CONFUSION
54 | || type == PotionEffectType.BLINDNESS
55 | || type == PotionEffectType.HUNGER
56 | || type == PotionEffectType.WEAKNESS
57 | || type == PotionEffectType.POISON
58 | || type == PotionEffectType.WITHER) {
59 | return duration << 1;
60 | }
61 | return duration;
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/Paginator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import com.codelanx.codelanxlib.config.Lang;
23 | import com.codelanx.codelanxlib.internal.InternalLang;
24 | import org.bukkit.ChatColor;
25 |
26 | import java.util.ArrayList;
27 | import java.util.Arrays;
28 | import java.util.Collections;
29 | import java.util.List;
30 |
31 | /**
32 | * Wraps text in formatted bars with a title, and allows for paging through
33 | * text content
34 | *
35 | * @since 0.1.0
36 | * @author 1Rogue
37 | * @version 0.1.0
38 | */
39 | public class Paginator {
40 |
41 | private final String BAR;
42 | private final List pages = new ArrayList<>();
43 |
44 | /**
45 | * Constructor. Splits the {@code wholeText} parameter by a newline
46 | * character ({@code \n}) and forwards it to
47 | * {@link Paginator#Paginator(String, int, List)}
48 | *
49 | * @since 0.1.0
50 | * @version 0.1.0
51 | *
52 | * @see Paginator#Paginator(String, int, List)
53 | * @param title The title for the pages
54 | * @param itemsPerPage The number of items from the content parameter to
55 | * display on a page
56 | * @param wholeText A string to be split by the newline character {@code \n}
57 | */
58 | public Paginator(String title, int itemsPerPage, String wholeText) {
59 | this(title, itemsPerPage, wholeText.split("\n"));
60 | }
61 |
62 | /**
63 | * Constructor. Converts the passed {@code itr} parameter into a
64 | * {@link List} and forwards it to
65 | * {@link Paginator#Paginator(String, int, List)}
66 | *
67 | * @since 0.1.0
68 | * @version 0.1.0
69 | *
70 | * @see Paginator#Paginator(String, int, List)
71 | * @param title The title for the pages
72 | * @param itemsPerPage The number of items from the content parameter to
73 | * display on a page
74 | * @param itr An iterable collection of strings
75 | */
76 | public Paginator(String title, int itemsPerPage, String... itr) {
77 | this(title, itemsPerPage, Arrays.asList(itr));
78 | }
79 |
80 | /**
81 | * Constructor. Takes a {@link List} of strings and creates formatted
82 | * pages which can be output to a
83 | * {@link org.bukkit.command.CommandSender CommandSender}. These pages
84 | * should be considered immutable as they are only rendered once and then
85 | * subsequently stored.
86 | *
87 | * @since 0.1.0
88 | * @version 0.1.0
89 | *
90 | * @param title The title for the pages
91 | * @param itemsPerPage The number of items from the content parameter to
92 | * display on a page
93 | * @param content A {@link List} of strings to display
94 | */
95 | public Paginator(String title, int itemsPerPage, List content) {
96 | String s = InternalLang.PAGINATOR_BARCHAR.formatAndColor();
97 | if (s.isEmpty()) {
98 | this.BAR = "------------------------------"
99 | + "------------------------------";
100 | } else {
101 | char[] barr = new char[60];
102 | char c = s.toCharArray()[0];
103 | for (int i = barr.length - 1; i >= 0; i--) {
104 | barr[i] = c;
105 | }
106 | this.BAR = new String(barr);
107 | }
108 | //divide into pages
109 | int pageCount = content.size() / itemsPerPage + ((content.size() % itemsPerPage) == 0 ? 0 : 1);
110 | for (int i = 0; i < pageCount; i++) {
111 | StringBuilder sb = new StringBuilder();
112 | sb.append(this.formatTitle(title,
113 | InternalLang.PAGINATOR_BARCOLOR.formatAndColor(),
114 | InternalLang.PAGINATOR_TITLECOLOR.formatAndColor()));
115 | sb.append('\n');
116 | sb.append(InternalLang.PAGINATOR_PAGEFORMAT.formatAndColor(i + 1, pageCount));
117 | sb.append('\n');
118 | int stop = (i + 1) * itemsPerPage;
119 | if (stop > content.size()) {
120 | stop = content.size();
121 | }
122 | for (int w = i * itemsPerPage; w < stop; w++) {
123 | sb.append(content.get(w)).append('\n');
124 | }
125 | sb.append(this.formatFooter(InternalLang.PAGINATOR_BARCOLOR.formatAndColor()));
126 | sb.append('\n');
127 | this.pages.add(sb.toString());
128 | }
129 | }
130 |
131 | /**
132 | * Returns the appropriately formatted page for this {@link Paginator}
133 | *
134 | * @since 0.1.0
135 | * @version 0.1.0
136 | *
137 | * @param page The page to retrieve
138 | * @return The page in the form of a string
139 | */
140 | public String getPage(int page) {
141 | page--;
142 | if (page < 0 || page > this.pages.size()) {
143 | throw new IndexOutOfBoundsException("Page " + ++page + " does not exist");
144 | }
145 | return this.pages.get(page);
146 | }
147 |
148 | /**
149 | * Formats the title-bar for displaying help information
150 | *
151 | * @since 0.1.0
152 | * @version 0.1.0
153 | *
154 | * @param title The title to use
155 | * @param barcolor The color of the bar (ref: {@link ChatColor})
156 | * @param titlecolor The color of the title (ref: {@link ChatColor})
157 | * @return A formatted header
158 | */
159 | private String formatTitle(String title, String barcolor, String titlecolor) {
160 | String line = barcolor + this.BAR;
161 | int pivot = line.length() / 2;
162 | String center = InternalLang.PAGINATOR_TITLECONTAINER.formatAndColor(barcolor, titlecolor, title);
163 | return Lang.color(line.substring(0, pivot - center.length() / 2)
164 | + center
165 | + line.substring(0, pivot - center.length() / 2));
166 | }
167 |
168 | /**
169 | * Formats the footer-bar of the help information.
170 | *
171 | * @since 0.1.0
172 | * @version 0.1.0
173 | *
174 | * @param barcolor The color of the footer-bar
175 | * @return A formatted footer
176 | */
177 | private String formatFooter(String barcolor) {
178 | String back = barcolor + this.BAR;
179 | return Lang.color(back.substring(0, back.length() - 11));
180 | }
181 |
182 | /**
183 | * Returns the number of pages in this instance
184 | *
185 | * @since 0.1.0
186 | * @version 0.1.0
187 | *
188 | * @return The number of pages
189 | */
190 | public int size() {
191 | return this.pages.size();
192 | }
193 |
194 | /**
195 | * Returns a copy of all the pages in this instance
196 | *
197 | * @since 0.1.0
198 | * @version 0.1.0
199 | *
200 | * @return A copy of the pages
201 | */
202 | public List getPages() {
203 | return Collections.unmodifiableList(this.pages);
204 | }
205 |
206 | }
207 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/Players.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import com.codelanx.codelanxlib.util.auth.UUIDFetcher;
23 | import org.bukkit.Bukkit;
24 | import org.bukkit.Location;
25 | import org.bukkit.Material;
26 | import org.bukkit.OfflinePlayer;
27 | import org.bukkit.entity.Player;
28 | import org.json.simple.parser.ParseException;
29 |
30 | import java.io.IOException;
31 | import java.util.HashMap;
32 | import java.util.Map;
33 | import java.util.UUID;
34 | import java.util.function.BiPredicate;
35 |
36 | /**
37 | * Represents utility functions to simplify or clarify common operations
38 | * with Bukkit's {@link Player} object
39 | *
40 | * @since 0.0.1
41 | * @author 1Rogue
42 | * @version 0.1.0
43 | */
44 | public final class Players {
45 |
46 | private Players() {
47 | }
48 |
49 | /**
50 | * Gets any players within range of a specific location
51 | *
52 | * @since 0.0.1
53 | * @version 0.0.1
54 | *
55 | * @param range The range in which to look for players
56 | * @param origin The {@link Location} representing the center of the circle
57 | * @return Any players within the radius range of the origin, mapped to
58 | * the distance away they are
59 | */
60 | public static Map getPlayersInRange(int range, Location origin) {
61 | Map back = new HashMap<>();
62 | int frange = range * range;
63 | origin.getWorld().getPlayers().forEach((p) -> {
64 | double d = p.getLocation().distanceSquared(origin);
65 | if (d <= frange) {
66 | back.put(p, d);
67 | }
68 | });
69 | return back;
70 | }
71 |
72 | /**
73 | * Gets any players within range of a specific player, exclusive of the
74 | * player themselves.
75 | *
76 | * @since 0.0.1
77 | * @version 0.0.1
78 | *
79 | * @param range The range in which to look for players
80 | * @param origin The {@link Player} representing the center of the circle
81 | * @return Any players within the radius range of the origin, mapped to
82 | * the distance away they are
83 | */
84 | public static Map getPlayersInRange(int range, Player origin) {
85 | Map back = Players.getPlayersInRange(range, origin.getLocation());
86 | back.remove(origin);
87 | return back;
88 | }
89 |
90 | /**
91 | * Returns the closest {@link Player} adjacent to another {@link Player}
92 | *
93 | * @since 0.1.0
94 | * @version 0.1.0
95 | *
96 | * @param p The {@link Player} at the origin to search around
97 | * @return The closest {@link Player}, or {@code null} if no one else is in
98 | * the world
99 | */
100 | public static Player getClosestPlayer(Player p) {
101 | Location loc = p.getLocation();
102 | return p.getWorld().getPlayers().stream()
103 | .filter((o) -> !p.equals(o))
104 | .min((p1, p2) -> {
105 | return Double.compare(p1.getLocation().distanceSquared(loc), p2.getLocation().distanceSquared(loc));
106 | })
107 | .orElse(null);
108 | }
109 |
110 | /**
111 | * Returns the closest {@link Player} to a specific {@link Location}
112 | *
113 | * @since 0.1.0
114 | * @version 0.1.0
115 | *
116 | * @param loc The {@link Location} representing the origin to search from
117 | * @return The closest {@link Player}, or {@code null} if no one is in the
118 | * world
119 | */
120 | public static Player getClosestPlayer(Location loc) {
121 | return loc.getWorld().getPlayers().stream().min((o1, o2) -> {
122 | return Double.compare(o1.getLocation().distanceSquared(loc), o2.getLocation().distanceSquared(loc));
123 | }).orElse(null);
124 | }
125 |
126 | /**
127 | * Determines whether or not a location is harmful if a player was to be
128 | * located there in the current instant of time (such as a teleport)
129 | *
130 | * @since 0.1.0
131 | * @version 0.1.0
132 | *
133 | * @param in The {@link Location} to check
134 | * @return {@code true} if the location is safe
135 | */
136 | public static boolean isSafeLocation(final Location in) {
137 | Location l = in.clone();
138 | boolean hole = false;
139 | BiPredicate fallDmg = (i, m) -> i > 3 && m.isBlock();
140 | int count = 0;
141 | while (l.getBlockY() > 0) {
142 | l.add(0, -1, 0);
143 | count++;
144 | Material type = l.getBlock().getType();
145 | if (fallDmg.test(count, type)) {
146 | return false;
147 | }
148 | if (Blocks.isHarmful(type)) {
149 | return false;
150 | }
151 | if (type != Material.AIR && (type.isBlock() || type == Material.WATER || type == Material.STATIONARY_WATER)) {
152 | break;
153 | }
154 | }
155 | l = in.clone();
156 | for (int i = 0; i < 2; i++) {
157 | Material type = l.getBlock().getType();
158 | if (Blocks.isHarmful(type) || type.isBlock() || Blocks.isLiquid(type)) {
159 | return false;
160 | }
161 | l.add(0, 1, 0);
162 | }
163 | while (l.getBlockY() < 255) {
164 | Material type = l.getBlock().getType();
165 | if (Blocks.isDangerousFromAbove(type)) {
166 | return false;
167 | } else if (type.isBlock()) {
168 | break;
169 | }
170 | l.add(0, 1, 0);
171 | }
172 | return true;
173 | }
174 |
175 | /**
176 | * Gets the most correct UUID for the {@link Player} in the least expensive
177 | * way possible. Note however, if there is no UUID information about the
178 | * player on the server (e.g., they never played before), it will send a
179 | * blocking web request to Mojang's servers
180 | *
181 | * @since 0.1.0
182 | * @version 0.1.0
183 | *
184 | * @param name The name of the {@link Player}
185 | * @return The {@link UUID} for that player
186 | */
187 | public static UUID getUUID(String name) {
188 | if (Bukkit.getServer().getOnlineMode()) {
189 | OfflinePlayer op = Bukkit.getOfflinePlayer(name);
190 | if (op.hasPlayedBefore() || op.isOnline()) {
191 | return op.getUniqueId();
192 | }
193 | }
194 | try {
195 | return UUIDFetcher.getUUIDOf(name);
196 | } catch (IOException | ParseException | InterruptedException ex) {
197 | throw new IllegalArgumentException("Cannot determine UUID of player '" + name + "'", ex);
198 | }
199 | }
200 |
201 | /**
202 | * Returns whether or not a player by the specified {@code name} parameter
203 | * has played on this server before, or is currently online, thus resulting
204 | * in having a correct {@link UUID}
205 | *
206 | * @since 0.1.0
207 | * @version 0.1.0
208 | *
209 | * @param name The player name to look for
210 | * @return {@code true} if the UUID will be correct
211 | */
212 | public static boolean hasCorrectOfflineUUID(String name) {
213 | OfflinePlayer op = Bukkit.getOfflinePlayer(name);
214 | return op.hasPlayedBefore() || op.isOnline();
215 | }
216 |
217 | }
218 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/Protections.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import com.codelanx.codelanxlib.CodelanxLib;
23 | import com.codelanx.codelanxlib.internal.InternalPerms;
24 | import org.bukkit.Bukkit;
25 | import org.bukkit.Location;
26 | import org.bukkit.Material;
27 | import org.bukkit.block.Block;
28 | import org.bukkit.block.BlockFace;
29 | import org.bukkit.entity.Player;
30 | import org.bukkit.event.EventHandler;
31 | import org.bukkit.event.Listener;
32 | import org.bukkit.event.block.BlockBreakEvent;
33 | import org.bukkit.event.block.BlockBurnEvent;
34 | import org.bukkit.event.block.BlockPistonExtendEvent;
35 | import org.bukkit.event.block.BlockPistonRetractEvent;
36 | import org.bukkit.event.block.BlockPlaceEvent;
37 | import org.bukkit.event.entity.EntityChangeBlockEvent;
38 | import org.bukkit.event.entity.EntityExplodeEvent;
39 | import org.bukkit.plugin.java.JavaPlugin;
40 |
41 | import java.util.LinkedHashSet;
42 | import java.util.Set;
43 |
44 | /**
45 | * Adds protection to specific locations. This should not be used for large
46 | * areas, but rather indiscriminate points. Large-area protection will be added
47 | * later. Note that this will not protect from plugins dynamically modifying
48 | * the block themselves, such as WorldEdit
49 | *
50 | * @since 0.1.0
51 | * @author 1Rogue
52 | * @version 0.1.0
53 | */
54 | public final class Protections {
55 |
56 | private static final Set protect = new LinkedHashSet<>();
57 | private static boolean listenerRegistered = false;
58 |
59 | private Protections() {
60 |
61 | }
62 |
63 | /**
64 | * Protects a single {@link Location} from being altered
65 | *
66 | * @since 0.1.0
67 | * @version 0.1.0
68 | *
69 | * @param loc The {@link Location} to protect
70 | */
71 | public static void protect(Location loc) {
72 | if (!Protections.listenerRegistered) {
73 | Bukkit.getServer().getPluginManager().registerEvents(new ProtectionListener(), JavaPlugin.getPlugin(CodelanxLib.class));
74 | Protections.listenerRegistered = true;
75 | }
76 | Protections.protect.add(loc);
77 | }
78 |
79 | /**
80 | * Removes protection from a single {@link Location}. Does nothing if the
81 | * location was not protected in the first place.
82 | *
83 | * @since 0.1.0
84 | * @version 0.1.0
85 | *
86 | * @param loc The {@link Location} to unprotect
87 | */
88 | public static void unprotect(Location loc) {
89 | Protections.protect.remove(loc);
90 | }
91 |
92 | /**
93 | * Returns {@code true} if the passed {@link Location} is protected
94 | *
95 | * @since 0.1.0
96 | * @version 0.1.0
97 | *
98 | * @param loc The {@link Location} to check
99 | * @return {@code true} if protected
100 | */
101 | public static boolean isProtected(Location loc) {
102 | return Protections.protect.contains(loc);
103 | }
104 |
105 | /**
106 | * Provides total protection for blocks cached in {@link Protections}
107 | *
108 | * @since 0.1.0
109 | * @author 1Rogue
110 | * @version 0.1.0
111 | */
112 | public static class ProtectionListener implements Listener {
113 |
114 | private boolean doCancel(Location loc, Player p, boolean cancelled) {
115 | if (Protections.isProtected(loc)) {
116 | if (p == null) {
117 | return true;
118 | }
119 | return !InternalPerms.PROTECTION_OVERRIDE.has(p) ? true : cancelled;
120 | }
121 | return cancelled;
122 | }
123 |
124 | /**
125 | * Prevents pistons from pushing protected blocks
126 | *
127 | * @since 0.1.0
128 | * @version 0.1.0
129 | *
130 | * @param event The relevant {@link BlockPistonExtendEvent}
131 | */
132 | @EventHandler
133 | public void onPistonExtend(BlockPistonExtendEvent event) {
134 | if (!this.handlePiston(event.getBlock(), event.getDirection(), 12)) {
135 | event.setCancelled(true);
136 | }
137 | }
138 |
139 | /**
140 | * Prevents sticky pistons from pulling protected blocks
141 | *
142 | * @since 0.1.0
143 | * @version 0.1.0
144 | *
145 | * @param event The relevant {@link BlockPistonRetractEvent}
146 | */
147 | @EventHandler
148 | public void onPistonRetract(BlockPistonRetractEvent event) {
149 | if (event.isSticky()) {
150 | if (!this.handlePiston(event.getBlock(), event.getDirection(), 1)) {
151 | event.setCancelled(true);
152 | }
153 | }
154 | }
155 |
156 | /**
157 | * Determines if a protected block will be affected by a piston
158 | * movement in a specific direction
159 | *
160 | * @since 0.1.0
161 | * @version 0.1.0
162 | *
163 | * @param b The starting piston block
164 | * @param dir The {@link BlockFace} direction to search in
165 | * @param amount The amount of blocks to check
166 | * @return {@code true} if no protected blocks will be affected
167 | */
168 | private boolean handlePiston(Block b, BlockFace dir, int amount) {
169 | for (int i = amount; i > 0; i--) {
170 | b = b.getRelative(dir);
171 | if (b == null || b.getType() == Material.AIR) {
172 | return true;
173 | }
174 | if (Protections.isProtected(b.getLocation())) {
175 | return false;
176 | }
177 | }
178 | return true;
179 | }
180 |
181 | /**
182 | * Prevents protected blocks from being broken
183 | *
184 | * @since 0.1.0
185 | * @version 0.1.0
186 | *
187 | * @param event The relevant {@link BlockBreakEvent}
188 | */
189 | @EventHandler
190 | public void onBlockBreak(BlockBreakEvent event) {
191 | event.setCancelled(this.doCancel(event.getBlock().getLocation(),
192 | event.getPlayer(), event.isCancelled()));
193 | }
194 |
195 | /**
196 | * Prevents blocks from being burned
197 | *
198 | * @since 0.1.0
199 | * @version 0.1.0
200 | *
201 | * @param event The relevant {@link BlockBurnEvent}
202 | */
203 | @EventHandler
204 | public void onBurn(BlockBurnEvent event) {
205 | event.setCancelled(this.doCancel(event.getBlock().getLocation(),
206 | null, event.isCancelled()));
207 | }
208 |
209 | /**
210 | * Prevents blocks from being turned into entities (e.g. falling sand)
211 | *
212 | * @since 0.1.0
213 | * @version 0.1.0
214 | *
215 | * @param event The relevant {@link EntityChangeBlockEvent}
216 | */
217 | @EventHandler
218 | public void onEntityBlock(EntityChangeBlockEvent event) {
219 | event.setCancelled(this.doCancel(event.getBlock().getLocation(),
220 | null, event.isCancelled()));
221 | }
222 |
223 | /**
224 | * Prevents people from placing a block in the protected location
225 | *
226 | * @since 0.1.0
227 | * @version 0.1.0
228 | *
229 | * @param event The relevant {@link BlockPlaceEvent}
230 | */
231 | @EventHandler
232 | public void onPlace(BlockPlaceEvent event) {
233 | event.setCancelled(this.doCancel(event.getBlock().getLocation(),
234 | event.getPlayer(), event.isCancelled()));
235 | }
236 |
237 | /**
238 | * Prevents the block from exploding
239 | *
240 | * @since 0.1.0
241 | * @version 0.1.0
242 | *
243 | * @param event The relevant {@link EntityExplodeEvent}
244 | */
245 | @EventHandler
246 | public void onExplode(EntityExplodeEvent event) {
247 | event.blockList().removeIf(b -> Protections.isProtected(b.getLocation()));
248 | }
249 |
250 | }
251 |
252 | }
253 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/ReflectBukkit.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import com.codelanx.commons.logging.Debugger;
23 | import com.codelanx.commons.util.Reflections;
24 | import com.codelanx.commons.util.exception.Exceptions;
25 | import org.bukkit.Bukkit;
26 | import org.bukkit.World;
27 | import org.bukkit.plugin.java.JavaPlugin;
28 |
29 | import java.io.BufferedReader;
30 | import java.io.File;
31 | import java.io.FileInputStream;
32 | import java.io.IOException;
33 | import java.io.InputStream;
34 | import java.io.InputStreamReader;
35 | import java.util.zip.ZipEntry;
36 | import java.util.zip.ZipFile;
37 | import java.util.zip.ZipInputStream;
38 |
39 | /**
40 | * Created by Rogue on 11/17/2015.
41 | */
42 | public class ReflectBukkit { //blergh, save me from this classname
43 |
44 | /**
45 | * Gets the default {@link World} loaded by Bukkit
46 | *
47 | * @since 0.1.0
48 | * @version 0.1.0
49 | *
50 | * @return Bukkit's default {@link World} object
51 | */
52 | public static World getDefaultWorld() {
53 | Exceptions.illegalState(!Bukkit.getServer().getWorlds().isEmpty(), "No worlds loaded");
54 | return Bukkit.getServer().getWorlds().get(0);
55 | }
56 |
57 |
58 | /**
59 | * Returns the {@link JavaPlugin} that immediately called the method in the
60 | * current context. Useful for finding out which plugins accessed static API
61 | * methods. This method is equivalent to calling
62 | * {@code Reflections.getCallingPlugin(0)}
63 | *
64 | * @since 0.1.0
65 | * @version 0.1.0
66 | *
67 | * @see ReflectBukkit#getCallingPlugin(int)
68 | * @return The relevant {@link JavaPlugin}
69 | * @throws UnsupportedOperationException If not called from a
70 | * {@link JavaPlugin} class (either through an alternative ClassLoader,
71 | * executing code directly, or some voodoo magic)
72 | */
73 | public static JavaPlugin getCallingPlugin() {
74 | return ReflectBukkit.getCallingPlugin(1);
75 | }
76 |
77 |
78 | /**
79 | * Façade method for determining if Bukkit is the invoker of the method
80 | *
81 | * @since 0.1.0
82 | * @version 0.1.0
83 | *
84 | * @return {@code true} if Bukkit is the direct invoker of the method
85 | */
86 | public static boolean accessedFromBukkit() {
87 | return Reflections.getCaller(1).getClassName().startsWith("org.bukkit.");
88 | }
89 |
90 | /**
91 | * Returns the {@link JavaPlugin} that immediately called the method in the
92 | * current context. Useful for finding out which plugins accessed static API
93 | * methods
94 | *
95 | * @since 0.1.0
96 | * @version 0.1.0
97 | *
98 | * @param offset The number of additional methods to look back
99 | * @return The relevant {@link JavaPlugin}
100 | * @throws UnsupportedOperationException If not called from a
101 | * {@link JavaPlugin} class (either through an alternative ClassLoader,
102 | * executing code directly, or some voodoo magic)
103 | */
104 | public static JavaPlugin getCallingPlugin(int offset) {
105 | try {
106 | Class> cl = Class.forName(Reflections.getCaller(1 + offset).getClassName());
107 | JavaPlugin back = JavaPlugin.getProvidingPlugin(cl);
108 | if (back == null) {
109 | throw new UnsupportedOperationException("Must be called from a class loaded from a plugin");
110 | }
111 | return back;
112 | } catch (ClassNotFoundException ex) {
113 | //Potentially dangerous (Stackoverflow)
114 | Debugger.error(ex, "Error reflecting for plugin class");
115 | throw new IllegalStateException("Could not load from called class (Classloader issue?)", ex);
116 | }
117 | }
118 |
119 | /**
120 | * Checks whether or not there is a plugin on the server with the name of
121 | * the passed {@code name} paramater. This method achieves this by scanning
122 | * the plugins folder and reading the {@code plugin.yml} files of any
123 | * respective jarfiles in the directory.
124 | *
125 | * @since 0.1.0
126 | * @version 0.2.0
127 | *
128 | * @param name The name of the plugin as specified in the {@code plugin.yml}
129 | * @return The {@link File} for the plugin jarfile, or {@code null} if not
130 | * found
131 | */
132 | public static File findPluginJarfile(String name) {
133 | File plugins = new File("plugins");
134 | Exceptions.illegalState(plugins.isDirectory(), "'plugins' isn't a directory! (wat)");
135 | for (File f : plugins.listFiles((File pathname) -> {
136 | return pathname.getPath().endsWith(".jar");
137 | })) {
138 | try (InputStream is = new FileInputStream(f); ZipInputStream zi = new ZipInputStream(is)) {
139 | ZipEntry ent = null;
140 | while ((ent = zi.getNextEntry()) != null) {
141 | if (ent.getName().equalsIgnoreCase("plugin.yml")) {
142 | break;
143 | }
144 | }
145 | if (ent == null) {
146 | continue; //no plugin.yml found
147 | }
148 | ZipFile z = new ZipFile(f);
149 | try (InputStream fis = z.getInputStream(ent);
150 | InputStreamReader fisr = new InputStreamReader(fis);
151 | BufferedReader scan = new BufferedReader(fisr)) {
152 | String in;
153 | while ((in = scan.readLine()) != null) {
154 | if (in.startsWith("name: ")) {
155 | if (in.substring(6).equalsIgnoreCase(name)) {
156 | return f;
157 | }
158 | }
159 | }
160 | }
161 | } catch (IOException ex) {
162 | Debugger.error(ex, "Error reading plugin jarfiles");
163 | }
164 | }
165 | return null;
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/RuntimeCommandSender.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util;
21 |
22 | import org.bukkit.Server;
23 | import org.bukkit.command.CommandSender;
24 | import org.bukkit.permissions.Permission;
25 | import org.bukkit.permissions.PermissionAttachment;
26 | import org.bukkit.permissions.PermissionAttachmentInfo;
27 | import org.bukkit.plugin.Plugin;
28 |
29 | import java.util.Set;
30 | import java.util.logging.Logger;
31 |
32 | /**
33 | * Represents a {@link CommandSender} which outputs to a {@link Logger}. This is
34 | * specifically made with the intention of unit testing without running a Bukkit
35 | * environment
36 | *
37 | * @since 0.1.0
38 | * @author 1Rogue
39 | * @version 0.1.0
40 | */
41 | public class RuntimeCommandSender implements CommandSender {
42 |
43 | private static final Logger LOG = Logger.getLogger(RuntimeCommandSender.class.getName());
44 |
45 | @Override
46 | public void sendMessage(String message) {
47 | LOG.info(message);
48 | }
49 |
50 | @Override
51 | public void sendMessage(String[] messages) {
52 | for (String s : messages) {
53 | LOG.info(s);
54 | }
55 | }
56 |
57 | @Override
58 | public Server getServer() {
59 | throw new UnsupportedOperationException(this.getClass().getSimpleName() + " is not attached to any server instance");
60 | }
61 |
62 | @Override
63 | public String getName() {
64 | return "RUNTIME";
65 | }
66 |
67 | @Override
68 | public boolean isPermissionSet(String name) {
69 | return true;
70 | }
71 |
72 | @Override
73 | public boolean isPermissionSet(Permission perm) {
74 | return true;
75 | }
76 |
77 | @Override
78 | public boolean hasPermission(String name) {
79 | return true;
80 | }
81 |
82 | @Override
83 | public boolean hasPermission(Permission perm) {
84 | return true;
85 | }
86 |
87 | @Override
88 | public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) {
89 | throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot have permission attachments");
90 | }
91 |
92 | @Override
93 | public PermissionAttachment addAttachment(Plugin plugin) {
94 | throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot have permission attachments");
95 | }
96 |
97 | @Override
98 | public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) {
99 | throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot have permission attachments");
100 | }
101 |
102 | @Override
103 | public PermissionAttachment addAttachment(Plugin plugin, int ticks) {
104 | throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot have permission attachments");
105 | }
106 |
107 | @Override
108 | public void removeAttachment(PermissionAttachment attachment) {}
109 |
110 | @Override
111 | public void recalculatePermissions() {}
112 |
113 | @Override
114 | public Set getEffectivePermissions() {
115 | throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot have permission attachments");
116 | }
117 |
118 | @Override
119 | public boolean isOp() {
120 | return true;
121 | }
122 |
123 | @Override
124 | public void setOp(boolean value) {}
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/src/main/java/com/codelanx/codelanxlib/util/auth/UserInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Codelanx, All Rights Reserved
3 | *
4 | * This work is licensed under a Creative Commons
5 | * Attribution-NonCommercial-NoDerivs 3.0 Unported License.
6 | *
7 | * This program is protected software: You are free to distrubute your
8 | * own use of this software under the terms of the Creative Commons BY-NC-ND
9 | * license as published by Creative Commons in the year 2015 or as published
10 | * by a later date. You may not provide the source files or provide a means
11 | * of running the software outside of those licensed to use it.
12 | *
13 | * This program is distributed in the hope that it will be useful,
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 | *
17 | * You should have received a copy of the Creative Commons BY-NC-ND license
18 | * long with this program. If not, see .
19 | */
20 | package com.codelanx.codelanxlib.util.auth;
21 |
22 | import java.util.UUID;
23 |
24 | /**
25 | * Represents information about a player
26 | *
27 | * @since 0.1.0
28 | * @author 1Rogue
29 | * @version 0.1.0
30 | */
31 | public class UserInfo {
32 |
33 | private final String name;
34 | private final UUID uuid;
35 |
36 | /**
37 | * Stores the passed fields
38 | *
39 | * @since 0.1.0
40 | * @version 0.1.0
41 | *
42 | * @param name The player name
43 | * @param uuid The player {@link UUID}
44 | */
45 | public UserInfo(String name, UUID uuid) {
46 | this.name = name;
47 | this.uuid = uuid;
48 | }
49 |
50 | /**
51 | * Returns the name of this player
52 | *
53 | * @since 0.1.0
54 | * @version 0.1.0
55 | *
56 | * @return The player name
57 | */
58 | public String getName() {
59 | return this.name;
60 | }
61 |
62 | /**
63 | * Returns the {@link UUID} of this player
64 | *
65 | * @since 0.1.0
66 | * @version 0.1.0
67 | *
68 | * @return The player {@link UUID}
69 | */
70 | public UUID getUUID() {
71 | return this.uuid;
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/resources/plugin.yml:
--------------------------------------------------------------------------------
1 | name: ${project.name}
2 | version: ${project.version}
3 | description: ${project.description}
4 | load: STARTUP
5 | author: 1Rogue
6 | website: ${website}
7 | main: ${project.groupId}.${project.artifactId}.${project.name}
8 | loadbefore: [Vault]
9 | softdepend: [Vault]
10 | prefix: ${prefix}
--------------------------------------------------------------------------------