/
aH.java
632 lines (501 loc) · 20.6 KB
/
aH.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.scripts.ScriptRegistry;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.ChatColor;
import org.bukkit.entity.EntityType;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The dScript Argument Helper will aid you in parsing and formatting arguments from a
* dScript argument string (such as those found in a ScriptEntry.getArguments() method).
*
* @author aufdemrand
*
*/
public class aH {
public enum PrimitiveType { Float, Double, Integer, Boolean, String, Word, Percentage }
final static Pattern floatPrimitive =
Pattern.compile("^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?$");
final static Pattern doublePrimitive =
Pattern.compile("(-)?(?:(?:\\d+)|)(?:(?:\\.\\d+)|)");
final static Pattern percentagePrimitive =
Pattern.compile("(?:(?:\\d+)|)(?:(?:\\.\\d+)|)(%|)");
final static Pattern integerPrimitive =
Pattern.compile("(-)?\\d+");
final static Pattern booleanPrimitive =
Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
final static Pattern wordPrimitive =
Pattern.compile("\\w+");
public static class Argument {
public String raw_value;
String prefix = null;
String value;
boolean has_prefix = false;
// Construction
public Argument(String string) {
raw_value = string;
string = string.trim();
int first_colon = string.indexOf(":");
int first_space = string.indexOf(" ");
if ((first_space > -1 && first_space < first_colon) || first_colon == -1) value = string;
else {
has_prefix = true;
prefix = string.split(":", 2)[0];
value = string.split(":", 2)[1];
}
// dB.log("Constructed Argument: " + prefix + ":" + value);
}
public static Argument valueOf(String string) {
return new Argument(string);
}
public boolean hasPrefix() {
return has_prefix;
}
public Argument getPrefix() {
if (prefix == null)
return null;
return valueOf(prefix);
}
public boolean startsWith(String string) {
return value.startsWith(string);
}
public boolean matches(String values) {
for (String value : values.split(","))
if (value.trim().equalsIgnoreCase(this.value))
return true;
return false;
}
public void replaceValue(String string) {
value = string;
}
public String getValue() {
return value;
}
public String getPrefixAndValue() {
if (has_prefix)
return prefix + ":" + value;
else
return value;
}
public boolean matchesEnum(Enum[] values) {
for (Enum value : values)
if (value.name().replace("_", "").equalsIgnoreCase(this.value.replace("_", "")))
return true;
return false;
}
public boolean matchesPrefix(String values) {
for (String value : values.split(","))
if (value.trim().equalsIgnoreCase((prefix != null ? prefix : this.value)))
return true;
return false;
}
public boolean matchesPrimitive(PrimitiveType argumentType) {
if (value == null) return false;
switch (argumentType) {
case Word:
return wordPrimitive.matcher(value).matches();
case Integer:
return integerPrimitive.matcher(value).matches();
case Double:
return doublePrimitive.matcher(value).matches();
case Float:
return floatPrimitive.matcher(value).matches();
case Boolean:
return booleanPrimitive.matcher(value).matches();
case Percentage:
return percentagePrimitive.matcher(value).matches();
case String:
return true;
}
return false;
}
public boolean matchesArgumentType(Class<? extends dObject> dClass) {
try {
return (Boolean) dClass.getMethod("matches", String.class).invoke(null, value);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// Check if this argument matches a dList of a certain dObject
public boolean matchesArgumentList(Class<? extends dObject> dClass) {
dList list = new dList(this.getValue());
if (list.filter(dClass) != null) {
return true;
}
return false;
}
public Element asElement() {
return new Element(prefix, value);
}
public <T extends dObject> T asType(Class<? extends dObject> clazz) {
// dB.log("Calling asType: " + prefix + ":" + value + " " + clazz.getCanonicalName());
dObject arg = null;
try {
arg = (dObject) clazz.getMethod("valueOf", String.class)
.invoke(null, value);
// dB.log("Created: " + clazz.cast(arg).debug());
if (arg != null) {
return (T) clazz.cast(arg).setPrefix(prefix);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
}
/**
* Turns a list of string arguments (separated by buildArgs) into Argument
* Objects for easy matching and dObject creation throughout Denizen.
*
* @param args a list of string arguments
* @return a list of Arguments
*/
public static List<Argument> interpret(List<String> args) {
List<Argument> arg_list = new ArrayList<Argument>();
for (String string : args)
arg_list.add(new Argument(string.trim()));
return arg_list;
}
/**
* Builds an arguments array, recognizing items in quotes as a single item, but
* otherwise splitting on a space.
*
* @param stringArgs the line of arguments that need split
* @return an array of arguments
*
*/
public static String[] buildArgs(String stringArgs) {
final Pattern regex =
Pattern.compile("[^\\s\"'¨]+|\"([^\"]*)\"|'([^']*)'|¨([^¨]*)¨");
if (stringArgs == null) return null;
java.util.List<String> matchList = new ArrayList<String>();
Matcher regexMatcher = regex.matcher(stringArgs);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null)
matchList.add(regexMatcher.group(1));
else if (regexMatcher.group(2) != null)
matchList.add(regexMatcher.group(2));
else
matchList.add(regexMatcher.group());
}
if (dB.showScriptBuilder)
dB.echoDebug(ChatColor.GRAY + "Args: " + Arrays.toString(matchList.toArray()));
return matchList.toArray(new String[matchList.size()]);
}
/**
* To be used with the dBuggers' .report to provide debug output for
* objects that don't extend dObject.
*
* @param prefix name/type/simple description of the object being reported
* @param value object being reported will report the value of toString()
*
* @return color coded debug report
*/
public static String debugObj(String prefix, Object value) {
return "<G>" + prefix + "='<Y>" + (value != null ? value.toString() : "null") + "<G>' ";
}
/**
* To be used with the dBuggers' .report to provide debug output for
* objects that may have some kind of id or type also associated with
* the object.
*
* @param prefix name/type/simple description of the object being reported
* @param id additional id/type of the object
* @param value object being reported will report the value of toString()
*
* @return color coded debug report
*/
public static String debugUniqueObj(String prefix, String id, Object value) {
return "<G>" + prefix + "='<A>" + id + "<Y>(" + (value != null ? value.toString() : "null") + ")<G>' ";
}
public enum ArgumentType {
LivingEntity, Item, Boolean, Custom, Double, Float,
Integer, String, Word, Location, Script, Duration
}
/**
* <p>Used to determine if a argument string matches a non-valued custom argument.
* If a dScript valued argument (such as TARGET:NAME) is passed, this method
* will always return false. Also supports multiple argument names, separated by a
* comma (,) character. This method will trim() each name specified.</p>
*
* <b>Example use of '<tt>aH.matchesArg("NOW, LATER", arg)</tt>':</b>
* <ol>
* <tt>arg = "NOW"</tt> will return true.<br>
* <tt>arg = "NEVER"</tt> will return false.<br>
* <tt>arg = "LATER:8PM"</tt> will return false.<br>
* <tt>arg = "LATER"</tt> will return true.
* </ol>
*
* @param names the valid argument names to match
* @param string_arg the dScript argument string
* @return true if matched, false if not
*
*/
public static boolean matchesArg(String names, String string_arg) {
String[] parts = names.split(",");
if (parts.length == 1) {
if (string_arg.toUpperCase().equals(names.toUpperCase())) return true;
} else {
for (String string : parts)
if (string_arg.split(":")[0].equalsIgnoreCase(string.trim())) return true;
}
return false;
}
/**
* <p>Used to match a custom argument with a value. In practice, the standard
* arguments should be used whenever possible to keep things consistent across
* the entire 'dScript experience'. Should you need to use custom arguments,
* however, this method provides some support. After all, while using standard
* arguments is nice, you should never reach. Arguments should make as much
* sense to the user/script writer as possible.</p>
*
* <b>Small code example:</b>
* <ol>
* <tt>0 if (aH.matchesValueArg("HARDNESS", arg, ArgumentType.Word))</tt><br>
* <tt>1 try { </tt><br>
* <tt>2 hardness = Hardness.valueOf(aH.getStringFrom(arg).toUpperCase());</tt><br>
* <tt>3 } catch (Exception e) { </tt><br>
* <tt>4 dB.echoError("Invalid HARDNESS!") </tt><br>
* <tt>5 }</tt><br>
* </ol>
*
* <p>Note: Like {@link #matchesArg(String, String)}, matchesValueArg(String)
* supports multiple argument names, separated by a comma (,) character. This method
* will trim() each name specified.</p>
*
* <p>Also requires a specified ArgumentType, which will filter the type of value
* to match to. If anything should be excepted as the value, or you plan
* on parsing the value yourself, use ArgumentType.Custom, otherwise use an
* an appropriate ArgumentType. See: {@link ArgumentType}.</p>
*
* <b>Example use of '<tt>aH.matchesValueArg("TIME", arg, ArgumentType.Integer)</tt>':</b>
* <ol>
* <tt>arg = "TIME:60"</tt> will return true.<br>
* <tt>arg = "90"</tt> will return false.<br>
* <tt>arg = "TIME:8 o'clock"</tt> will return false.<br>
* <tt>arg = "TIME:0"</tt> will return true.
* </ol>
*
* @param names the desired name variations of the argument
* @param string_arg the dScript argument string
* @param type a valid ArgumentType, used for matching values
* @return true if matched, false otherwise
*
*/
@Deprecated
public static boolean matchesValueArg(String names, String string_arg, ArgumentType type) {
if (string_arg == null) return false;
int firstColonIndex = string_arg.indexOf(':');
if (firstColonIndex == -1) return false;
String[] commaParts = names.split(",");
if (commaParts.length == 1) {
if (!string_arg.substring(0,firstColonIndex).equalsIgnoreCase(names))
return false;
}
else {
boolean matched = false;
for (String string : commaParts)
if (string_arg.substring(0,firstColonIndex).equalsIgnoreCase(string.trim()))
matched = true;
if (!matched) return false;
}
string_arg = string_arg.split(":", 2)[1];
switch (type) {
case Word:
return wordPrimitive.matcher(string_arg).matches();
case Integer:
return integerPrimitive.matcher(string_arg).matches();
case Double:
return doublePrimitive.matcher(string_arg).matches();
case Float:
return floatPrimitive.matcher(string_arg).matches();
case Boolean:
return booleanPrimitive.matcher(string_arg).matches();
case Location:
return dLocation.matches(string_arg);
case Script:
// return dScript.matches(string_arg);
return true;
case Item:
return dItem.matches(string_arg);
case LivingEntity:
return dEntity.matches(string_arg);
case Duration:
return Duration.matches(string_arg);
case String:
return true;
case Custom:
return true;
}
dB.echoError("While parsing '" + string_arg + "', Denizen has run into a problem. While the " +
"prefix is correct, the value is not valid. Check documentation for valid value." +
"Perhaps a replaceable tag has failed to fill in a value?");
return false;
}
public static boolean getBooleanFrom(String arg) {
return Boolean.valueOf(getStringFrom(arg));
}
public static double getDoubleFrom(String arg) {
try {
return Double.valueOf(getStringFrom(arg));
} catch (NumberFormatException e) {
return 0D;
}
}
@Deprecated
public static EntityType getEntityTypeFrom(String arg) {
for (EntityType validEntity : EntityType.values())
if (getStringFrom(arg).equalsIgnoreCase(validEntity.name()))
return validEntity;
// No match
return null;
}
@Deprecated
public static dEntity getEntityFrom(String arg) {
arg = arg.toLowerCase().replace("entity:", "");
return dEntity.valueOf(arg);
}
public static float getFloatFrom(String arg) {
try {
return Float.valueOf(getStringFrom(arg));
} catch (NumberFormatException e) {
return 0f;
}
}
public static int getIntegerFrom(String arg) {
try {
return Integer.valueOf(getStringFrom(arg));
} catch (NumberFormatException e) {
return 0;
}
}
@Deprecated
public static dItem getItemFrom(String arg) {
arg = arg.toLowerCase().replace("item:", "");
dItem stack = dItem.valueOf(arg);
return stack;
}
@Deprecated
public static dList getListFrom(String arg) {
return dList.valueOf(aH.getStringFrom(arg));
}
@Deprecated
public static dLocation getLocationFrom(String arg) {
arg = arg.toLowerCase().replace("location:", "");
return dLocation.valueOf(arg);
}
@Deprecated
public static dScript getScriptFrom(String arg) {
arg = arg.toLowerCase().replace("script:", "");
return dScript.valueOf(arg);
}
@Deprecated
public static dPlayer getPlayerFrom(String arg) {
return dPlayer.valueOf(aH.getStringFrom(arg));
}
@Deprecated
public static dNPC getNPCFrom(String arg) {
return dNPC.valueOf(aH.getStringFrom(arg));
}
public static String getStringFrom(String arg) {
String[] parts = arg.split(":", 2);
return parts.length >=2 ? parts[1] : arg;
}
@Deprecated
public static Duration getDurationFrom(String arg) {
arg = arg.toLowerCase().replace("duration:", "").replace("delay:", "");
return Duration.valueOf(arg);
}
public static boolean matchesDouble(String arg) {
return doublePrimitive.matcher(arg).matches();
}
@Deprecated
public static boolean matchesDuration(String arg) {
arg = arg.toLowerCase().replace("duration:", "").replace("delay:", "");
return Duration.matches(arg);
}
public static boolean matchesEntityType(String arg) {
arg = arg.toLowerCase().replace("entity:", "");
// Check against valid EntityTypes using Bukkit's EntityType enum
for (EntityType validEntity : EntityType.values())
if (arg.equalsIgnoreCase(validEntity.name()))
return true;
return false;
}
public static boolean matchesInteger(String arg) {
return integerPrimitive.matcher(arg).matches();
}
@Deprecated
public static boolean matchesItem(String arg) {
if (arg.length() > 5 && arg.toUpperCase().startsWith("ITEM:"))
return true;
// TODO: Other matches____ do some actual checks.
return false;
}
@Deprecated
public static boolean matchesContext(String arg) {
if (arg.toUpperCase().startsWith("CONTEXT:") ||
arg.toUpperCase().startsWith("DEFINE:")) return true;
// TODO: Other matches____ do some actual checks, should this?.
return false;
}
@Deprecated
public static Map<String, String> getContextFrom(String arg) {
Map<String, String> context = new HashMap<String, String>();
int x = 1;
for (String ctxt : aH.getListFrom(arg)) {
context.put(String.valueOf(x), ctxt.trim());
x++;
}
return context;
}
@Deprecated
public static boolean matchesLocation(String arg) {
if (arg.length() > 8 && arg.toUpperCase().startsWith("LOCATION:"))
return true;
return false;
}
@Deprecated
public static boolean matchesQuantity(String arg) {
if (arg.length() > 4 && arg.toUpperCase().startsWith("QTY:"))
return true;
return false;
}
@Deprecated
public static boolean matchesQueue(String arg) {
if (arg.length() > 6 && arg.toUpperCase().startsWith("QUEUE:"))
return true;
return false;
}
@Deprecated
public static boolean matchesScript(String arg) {
Matcher m = matchesScriptPtrn.matcher(arg);
if (m.matches()) {
if (ScriptRegistry.containsScript(m.group(1)))
return true;
else {
dB.echoError("While parsing '" + arg + "', Denizen has run into a problem. This " +
"argument's format is correct, but Denizen couldn't locate a script " +
"named '" + m.group(1) + "'. Is it spelled correctly?");
}
}
return false;
}
@Deprecated
public static boolean matchesState(String arg) {
final Pattern m = Pattern.compile("(state|toggle):(true|false|toggle)");
if (m.matcher(arg).matches()) return true;
else if (arg.toUpperCase().startsWith("(state|toggle):"))
dB.echoError("While parsing '" + arg + "', Denizen has run into a problem. While the prefix is " +
"correct, the value is not valid. 'STATE' requires a value of TRUE, FALSE, or TOGGLE. ");
return false;
}
final static Pattern matchesScriptPtrn = Pattern.compile("script:(.+)", Pattern.CASE_INSENSITIVE);
}