/
Static.java
1583 lines (1477 loc) · 49.4 KB
/
Static.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.laytonsmith.core;
import com.laytonsmith.PureUtilities.Common.DateUtils;
import com.laytonsmith.PureUtilities.Common.StreamUtils;
import com.laytonsmith.PureUtilities.SimpleVersion;
import com.laytonsmith.PureUtilities.TermColors;
import com.laytonsmith.PureUtilities.XMLDocument;
import com.laytonsmith.abstraction.MCCommandSender;
import com.laytonsmith.abstraction.MCConsoleCommandSender;
import com.laytonsmith.abstraction.MCEntity;
import com.laytonsmith.abstraction.MCItemStack;
import com.laytonsmith.abstraction.MCLivingEntity;
import com.laytonsmith.abstraction.MCMetadatable;
import com.laytonsmith.abstraction.MCOfflinePlayer;
import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.abstraction.MCPlugin;
import com.laytonsmith.abstraction.MCServer;
import com.laytonsmith.abstraction.MCVehicle;
import com.laytonsmith.abstraction.MCWorld;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.abstraction.blocks.MCBlock;
import com.laytonsmith.annotations.typeof;
import com.laytonsmith.commandhelper.CommandHelperPlugin;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CBoolean;
import com.laytonsmith.core.constructs.CByteArray;
import com.laytonsmith.core.constructs.CClassType;
import com.laytonsmith.core.constructs.CDouble;
import com.laytonsmith.core.constructs.CInt;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CNumber;
import com.laytonsmith.core.constructs.CPrimitive;
import com.laytonsmith.core.constructs.CResource;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.NativeTypeList;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.constructs.Variable;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CRE.CREBadEntityException;
import com.laytonsmith.core.exceptions.CRE.CRECastException;
import com.laytonsmith.core.exceptions.CRE.CREFormatException;
import com.laytonsmith.core.exceptions.CRE.CREIOException;
import com.laytonsmith.core.exceptions.CRE.CREIllegalArgumentException;
import com.laytonsmith.core.exceptions.CRE.CREInvalidPluginException;
import com.laytonsmith.core.exceptions.CRE.CREInvalidWorldException;
import com.laytonsmith.core.exceptions.CRE.CRELengthException;
import com.laytonsmith.core.exceptions.CRE.CRENullPointerException;
import com.laytonsmith.core.exceptions.CRE.CREPlayerOfflineException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.functions.Function;
import com.laytonsmith.core.profiler.Profiler;
import com.laytonsmith.core.taskmanager.TaskManager;
import com.laytonsmith.persistence.DataSourceException;
import com.laytonsmith.persistence.PersistenceNetwork;
import com.laytonsmith.persistence.io.ConnectionMixinFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class contains several static methods to get various objects that really
* should be static in the first place, but aren't. For the most part, when any
* code is running, these things will have been initialized, but in the event
* they aren't, each function will throw a NotInitializedYetException, which is
* a RuntimeException, so you don't have to check for exceptions whenever you
* use them. The Exception is caught on a higher level though, so it shouldn't
* bubble up too far.
*
*/
public final class Static {
private Static() {
}
private static final Logger logger = Logger.getLogger("CommandHelper");
private static Map<String, String> hostCache = new HashMap<String, String>();
private static final String consoleName = "~console";
private static final String blockPrefix = "#"; // Chosen over @ because that does special things when used by the block
/**
* In case the API being used doesn't support permission groups, a permission node in the format
* <code>String permission = groupPrefix + groupName;</code>
* can be assigned to players to declare their permission group.
*
* Third party APIs may provide better access.
*/
public static final String groupPrefix = "group.";
/**
* The label representing unrestricted access.
*/
public static final String GLOBAL_PERMISSION = "*";
/**
* Returns a CArray object from a given construct, throwing a common error
* message if not.
*
* @param construct
* @param t
* @return
*/
public static CArray getArray(Construct construct, Target t) {
return ArgumentValidation.getArray(construct, t);
}
/**
* Works like the other get* methods, but works in a more generic way for
* other types of Constructs. It also assumes that the class specified is
* tagged with a typeof annotation, thereby preventing the need for the
* expectedClassName like the deprecated version uses.
*
* @param <T> The type expected.
* @param construct The generic object
* @param t Code target
* @param clazz The type expected.
* @return The properly cast object.
*/
public static <T extends Construct> T getObject(Construct construct, Target t, Class<T> clazz) {
return ArgumentValidation.getObject(construct, t, clazz);
}
/**
* Returns a CNumber construct (CInt or CDouble) from any java number.
* @param number The java number to convert.
* @param t The code target.
* @return A construct equivalent to the given java number, whose the type is the better to represent it.
*/
public static CNumber getNumber(Number number, Target t) {
long longValue = number.longValue();
double doubleValue = number.doubleValue();
return longValue == doubleValue ? new CInt(longValue, t) : new CDouble(doubleValue, t);
}
/**
* This function pulls a numerical equivalent from any given construct. It
* throws a ConfigRuntimeException if it cannot be converted, for instance
* the string "s" cannot be cast to a number. The number returned will
* always be a double.
*
* @param c
* @return
*/
public static double getNumber(Construct c, Target t) {
return ArgumentValidation.getNumber(c, t);
}
/**
* Alias to getNumber
*
* @param c
* @return
*/
public static double getDouble(Construct c, Target t) {
return ArgumentValidation.getDouble(c, t);
}
public static float getDouble32(Construct c, Target t) {
return ArgumentValidation.getDouble32(c, t);
}
/**
* Returns an integer from any given construct.
*
* @param c
* @return
*/
public static long getInt(Construct c, Target t) {
return ArgumentValidation.getInt(c, t);
}
/**
* Returns a 32 bit int from the construct. Since the backing value is
* actually a long, if the number contained in the construct is not the same
* after truncating, an exception is thrown (fail fast). When needing an int
* from a construct, this method is much preferred over silently truncating.
*
* @param c
* @param t
* @return
*/
public static int getInt32(Construct c, Target t) {
return ArgumentValidation.getInt32(c, t);
}
/**
* Returns a 16 bit int from the construct (a short). Since the backing
* value is actually a long, if the number contained in the construct is not
* the same after truncating, an exception is thrown (fail fast). When
* needing an short from a construct, this method is much preferred over
* silently truncating.
*
* @param c
* @param t
* @return
*/
public static short getInt16(Construct c, Target t) {
return ArgumentValidation.getInt16(c, t);
}
/**
* Returns an 8 bit int from the construct (a byte). Since the backing value
* is actually a long, if the number contained in the construct is not the
* same after truncating, an exception is thrown (fail fast). When needing a
* byte from a construct, this method is much preferred over silently
* truncating.
*
* @param c
* @param t
* @return
*/
public static byte getInt8(Construct c, Target t) {
return ArgumentValidation.getInt8(c, t);
}
/**
* Returns a boolean from any given construct. Depending on the type of the
* construct being converted, it follows the following rules: If it is an
* integer or a double, it is false if 0, true otherwise. If it is a string,
* if it is empty, it is false, otherwise it is true.
*
* @param c
* @return
*/
public static boolean getBoolean(Construct c) {
return ArgumentValidation.getBoolean(c, Target.UNKNOWN);
}
/**
* Returns a primitive from any given construct.
* @param c
* @param t
* @return
*/
public static CPrimitive getPrimitive(Construct c, Target t){
return ArgumentValidation.getObject(c, t, CPrimitive.class);
}
/**
* Returns a CByteArray from any given construct.
* @param c
* @param t
* @return
*/
public static CByteArray getByteArray(Construct c, Target t) {
return ArgumentValidation.getByteArray(c, t);
}
/**
* Returns true if any of the constructs are a CDouble, false otherwise.
*
* @param c
* @return
*/
public static boolean anyDoubles(Construct... c) {
return ArgumentValidation.anyDoubles(c);
}
/**
* Return true if any of the constructs are CStrings, false otherwise.
*
* @param c
* @return
*/
public static boolean anyStrings(Construct... c) {
return ArgumentValidation.anyStrings(c);
}
/**
* Returns true if any of the constructs are CBooleans, false otherwise.
*
* @param c
* @return
*/
public static boolean anyBooleans(Construct... c) {
return ArgumentValidation.anyBooleans(c);
}
/**
* Returns true if any of the constructs are null.
* @param c
* @return
*/
public static boolean anyNulls(Construct... c){
return ArgumentValidation.anyNulls(c);
}
/**
* Returns the logger for the plugin
*
* @return
*/
public static Logger getLogger() {
return logger;
}
/**
* Returns the server for this plugin
*
* @return
* @throws NotInitializedYetException
*/
public static MCServer getServer() throws NotInitializedYetException {
MCServer s = com.laytonsmith.commandhelper.CommandHelperPlugin.myServer;
if (s == null) {
throw new NotInitializedYetException("The server has not been initialized yet");
}
return s;
}
/**
* Gets the reference to the AliasCore for this plugin
*
* @return
* @throws NotInitializedYetException
*/
public static AliasCore getAliasCore() throws NotInitializedYetException {
AliasCore ac = com.laytonsmith.commandhelper.CommandHelperPlugin.getCore();
if (ac == null) {
throw new NotInitializedYetException("The core has not been initialized yet");
}
return ac;
}
/**
* Gets the current version of the plugin
*
* @return
* @throws NotInitializedYetException
*/
public static SimpleVersion getVersion() throws NotInitializedYetException {
SimpleVersion v = com.laytonsmith.commandhelper.CommandHelperPlugin.version;
if (v == null) {
throw new NotInitializedYetException("The plugin has not been initialized yet");
}
return v;
}
private static String debugLogFileCurrent = null;
private static FileWriter debugLogFileHandle = null;
/**
* Returns a file that is most likely ready to write to. The timestamp
* variables have already been replaced, and parent directories are all
* created.
*
* @return
*/
public static FileWriter debugLogFile(File root) throws IOException {
String currentFileName = root.getPath() + "/" + DateUtils.ParseCalendarNotation(Prefs.DebugLogFile());
if (!currentFileName.equals(debugLogFileCurrent)) {
if (debugLogFileHandle != null) {
//We're done with the old one, close it.
debugLogFileHandle.close();
}
debugLogFileCurrent = currentFileName;
new File(debugLogFileCurrent).getParentFile().mkdirs();
if (!new File(debugLogFileCurrent).exists()) {
new File(debugLogFileCurrent).createNewFile();
}
debugLogFileHandle = new FileWriter(currentFileName);
}
return debugLogFileHandle;
}
private static String standardLogFileCurrent = null;
private static FileWriter standardLogFileHandle = null;
public static FileWriter standardLogFile(File root) throws IOException {
String currentFileName = root.getPath() + DateUtils.ParseCalendarNotation(Prefs.StandardLogFile());
if (!currentFileName.equals(standardLogFileCurrent)) {
if (standardLogFileHandle != null) {
//We're done with the old one, close it.
standardLogFileHandle.close();
}
standardLogFileCurrent = currentFileName;
new File(standardLogFileCurrent).getParentFile().mkdirs();
standardLogFileHandle = new FileWriter(currentFileName);
}
return standardLogFileHandle;
}
private static String profilingLogFileCurrent = null;
private static FileWriter profilingLogFileHandle = null;
public static FileWriter profilingLogFile(File root) throws IOException {
String currentFileName = root.getPath() + DateUtils.ParseCalendarNotation(Prefs.ProfilingFile());
if (!currentFileName.equals(profilingLogFileCurrent)) {
if (profilingLogFileHandle != null) {
//We're done with the old one, close it.
profilingLogFileHandle.close();
}
profilingLogFileCurrent = currentFileName;
new File(profilingLogFileCurrent).getParentFile().mkdirs();
profilingLogFileHandle = new FileWriter(currentFileName);
}
return profilingLogFileHandle;
}
public static void checkPlugin(String name, Target t) throws ConfigRuntimeException {
if (Static.getServer().getPluginManager().getPlugin(name) == null) {
throw new CREInvalidPluginException("Needed plugin " + name + " not found!", t);
}
}
/**
* Regex patterns
*/
private static final Pattern INVALID_HEX = Pattern.compile("0x[a-fA-F0-9]*[^a-fA-F0-9]+[a-fA-F0-9]*");
private static final Pattern VALID_HEX = Pattern.compile("0x[a-fA-F0-9]+");
private static final Pattern INVALID_BINARY = Pattern.compile("\"0b[0-1]*[^0-1]+[0-1]*\"");
private static final Pattern VALID_BINARY = Pattern.compile("0b[0-1]+");
private static final Pattern INVALID_OCTAL = Pattern.compile("0o[0-7]*[^0-7]+[0-7]*");
private static final Pattern VALID_OCTAL = Pattern.compile("0o[0-7]+");
/**
* Given a string input, creates and returns a Construct of the appropriate
* type. This takes into account that null, true, and false are keywords.
*
* @param val
* @param t
* @return
* @throws ConfigRuntimeException If the value is a hex or binary value, but
* has invalid characters in it.
*/
public static Construct resolveConstruct(String val, Target t) throws ConfigRuntimeException {
if (val == null) {
return new CString("", t);
}
if(val.equals("true")){
return CBoolean.TRUE;
}
if(val.equals("false")){
return CBoolean.FALSE;
}
if(val.equals("null")){
return CNull.NULL;
}
if(val.equals("void")){
return CVoid.TYPE;
}
if (INVALID_HEX.matcher(val).matches()) {
throw new CREFormatException("Hex numbers must only contain digits 0-9, and the letters A-F, but \"" + val + "\" was found.", t);
}
if (VALID_HEX.matcher(val).matches()) {
//Hex number
return new CInt(Long.parseLong(val.substring(2), 16), t);
}
if (INVALID_BINARY.matcher(val).matches()) {
throw new CREFormatException("Binary numbers must only contain digits 0 and 1, but \"" + val + "\" was found.", t);
}
if (VALID_BINARY.matcher(val).matches()) {
//Binary number
return new CInt(Long.parseLong(val.substring(2), 2), t);
}
if (INVALID_OCTAL.matcher(val).matches()){
throw new CREFormatException("Octal numbers must only contain digits 0-7, but \"" + val + "\" was found.", t);
}
if (VALID_OCTAL.matcher(val).matches()){
return new CInt(Long.parseLong(val.substring(2), 8), t);
}
try {
return new CInt(Long.parseLong(val), t);
} catch (NumberFormatException e) {
try {
if (!(val.contains(" ") || val.contains("\t"))) {
//Interesting behavior in Double.parseDouble causes it to "trim" strings first, then
//try to parse them, which is not desireable in our case. So, if the value contains
//any characters other than [\-0-9\.], we want to make it a string instead
return new CDouble(Double.parseDouble(val), t);
}
} catch (NumberFormatException g) {
// Not a double either
}
}
// TODO: Once compiler environments are added, we would need to check to see if the value here is a custom
// type. However, as it stands, since we only support the native types, we will just hardcode the check here.
if(NativeTypeList.getNativeTypeList().contains(val)){
return CClassType.get(val);
} else {
return new CString(val, t);
}
}
public static Construct resolveDollarVar(Construct variable, List<Variable> vars) {
if (variable == null) {
return CNull.NULL;
}
if (variable.getCType() == Construct.ConstructType.VARIABLE) {
for (Variable var : vars) {
if (var.getVariableName().equals(((Variable) variable).getVariableName())) {
return new CString(var.val(), var.getTarget());
}
}
return new CString(((Variable) variable).getDefault(), variable.getTarget());
} else {
return variable;
}
}
/**
* This function sends a message to the player. If the player is not online,
* a CRE is thrown.
*
* @param m
* @param msg
*/
public static void SendMessage(final MCCommandSender m, String msg, final Target t) {
if (m != null && !(m instanceof MCConsoleCommandSender)) {
if (m instanceof MCPlayer) {
MCPlayer p = (MCPlayer) m;
if (!p.isOnline()) {
throw new CREPlayerOfflineException("The player " + p.getName() + " is not online", t);
}
}
m.sendMessage(msg);
} else {
msg = Static.MCToANSIColors(msg);
if (msg.contains("\033")) {
//We have terminal colors, we need to reset them at the end
msg += TermColors.reset();
}
StreamUtils.GetSystemOut().println(msg);
}
}
/**
* Works like
* {@link #SendMessage(com.laytonsmith.abstraction.MCCommandSender, java.lang.String, com.laytonsmith.core.constructs.Target)}
* except it doesn't require a target, and ignores the message if the
* command sender is offline.
*
* @param m
* @param msg
*/
public static void SendMessage(final MCCommandSender m, String msg) {
try {
SendMessage(m, msg, Target.UNKNOWN);
} catch (ConfigRuntimeException e) {
//Ignored
}
}
/**
* Returns the name set aside to identify console via string<br>
* This is done here so that if it ever changes, it will update in all
* functions/docs
*
* @return
*/
public static String getConsoleName() {
return consoleName;
}
/**
* Returns the string set aside to prefix block names to distinguish them
* from players
*
* @return
*/
public static String getBlockPrefix() {
return blockPrefix;
}
/**
* Returns an item stack from the given item notation. Defaulting to the
* specified qty, this will throw an exception if the notation is invalid.
*
* @param functionName
* @param notation
* @param qty
* @throws ConfigRuntimeException FormatException if the notation is
* invalid.
* @return
*/
public static MCItemStack ParseItemNotation(String functionName, String notation, int qty, Target t) {
int type = 0;
short data = 0;
MCItemStack is;
String[] sData = notation.split(":");
try {
type = Integer.parseInt(sData[0]);
if (sData.length > 1) {
data = (short) Integer.parseInt(sData[1]);
}
} catch (NumberFormatException e) {
throw new CREFormatException("Item value passed to " + functionName + " is invalid: " + notation, t);
}
is = StaticLayer.GetItemStack(type, qty);
is.setDurability(data);
//is.setData(new MaterialData(type, data));
return is;
}
/**
* Works in reverse from the other ParseItemNotation
*
* @param is
* @return
*/
public static String ParseItemNotation(MCItemStack is) {
if (is == null) {
return "0";
}
String append = null;
if (is.getDurability() != 0) {
append = Short.toString(is.getDurability());
} else if (is.getData() != null) {
append = Integer.toString(is.getData().getData());
}
return is.getTypeId() + (append == null ? "" : ":" + append);
}
public static String ParseItemNotation(MCBlock b) {
if (b == null || b.isNull()) {
return "0";
}
return b.getTypeId() + (b.getData() == 0 ? "" : ":" + Byte.toString(b.getData()));
}
private static Map<String, MCCommandSender> injectedPlayers = new HashMap<String, MCCommandSender>();
private static final Pattern DASHLESS_PATTERN = Pattern.compile("^([A-Fa-f0-9]{8})([A-Fa-f0-9]{4})([A-Fa-f0-9]{4})([A-Fa-f0-9]{4})([A-Fa-f0-9]{12})$");
/**
* Based on https://github.com/sk89q/SquirrelID
*
* @param subject
* @param t
* @return
*/
public static UUID GetUUID(String subject, Target t) {
try {
if (subject.length() == 36) {
return UUID.fromString(subject);
}
if (subject.length() == 32) {
Matcher matcher = DASHLESS_PATTERN.matcher(subject);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid UUID format.");
}
return UUID.fromString(matcher.replaceAll("$1-$2-$3-$4-$5"));
} else {
throw new CRELengthException("A UUID is expected to be 32 or 36 characters,"
+ " but the given string was " + subject.length() + " characters.", t);
}
} catch (IllegalArgumentException iae) {
throw new CREIllegalArgumentException("A UUID length string was given, but was not a valid UUID.", t);
}
}
public static UUID GetUUID(Construct subject, Target t) {
return GetUUID(subject.val(), t);
}
public static MCOfflinePlayer GetUser(Construct search, Target t) {
return GetUser(search.val(), t);
}
/**
* Provides a user object containing info that doesn't require an online player.
* If provided a string between 1 and 16 characters, the lookup will be name-based.
* If provided a string that is 32 or 36 characters, the lookup will be uuid-based.
*
* @param search The text to be searched, can be between 1 and 16 characters, or 32 or 36 characters
* @param t
* @return
*/
public static MCOfflinePlayer GetUser(String search, Target t) {
MCOfflinePlayer ofp;
if (search.length() > 0 && search.length() <= 16) {
ofp = getServer().getOfflinePlayer(search);
} else {
try {
ofp = getServer().getOfflinePlayer(GetUUID(search, t));
} catch (ConfigRuntimeException cre) {
if (cre instanceof CRELengthException) {
throw new CRELengthException("The given string was the wrong size to identify a player."
+ " A player name is expected to be between 1 and 16 characters. " + cre.getMessage(), t);
} else {
throw cre;
}
}
}
return ofp;
}
/**
* Returns the player specified by name. Injected players also are returned in this list.
* If provided a string between 1 and 16 characters, the lookup will be name-based.
* If provided a string that is 32 or 36 characters, the lookup will be uuid-based.
*
* @param player
* @param t
* @return
* @throws ConfigRuntimeException
*/
public static MCPlayer GetPlayer(String player, Target t) throws ConfigRuntimeException {
MCCommandSender m;
if (player == null) {
throw new CREPlayerOfflineException("No player was specified!", t);
}
if (player.length() > 0 && player.length() <= 16) {
m = GetCommandSender(player, t);
} else {
try {
m = getServer().getPlayer(GetUUID(player, t));
} catch (ConfigRuntimeException cre) {
if (cre instanceof CRELengthException) {
throw new CRELengthException("The given string was the wrong size to identify a player."
+ " A player name is expected to be between 1 and 16 characters. " + cre.getMessage(), t);
} else {
throw cre;
}
}
}
if (m == null) {
throw new CREPlayerOfflineException("The specified player (" + player + ") is not online", t);
}
if (!(m instanceof MCPlayer)) {
throw new CREPlayerOfflineException("Expecting a player name, but \"" + player + "\" was found.", t);
}
MCPlayer p = (MCPlayer) m;
if (!p.isOnline()) {
throw new CREPlayerOfflineException("The specified player (" + player + ") is not online", t);
}
return p;
}
/**
* Returns the specified command sender. Players are supported, as is the
* special ~console user. The special ~console user will always return a
* user.
*
* @param player
* @param t
* @return
* @throws ConfigRuntimeException
*/
public static MCCommandSender GetCommandSender(String player, Target t) throws ConfigRuntimeException {
MCCommandSender m = null;
if (injectedPlayers.containsKey(player)) {
m = injectedPlayers.get(player);
} else {
if (consoleName.equals(player)) {
m = Static.getServer().getConsole();
} else {
try {
m = Static.getServer().getPlayer(player);
} catch (Exception e) {
//Apparently the server can occasionally throw exceptions here, so instead of rethrowing
//a NPE or whatever, we'll assume that the player just isn't online, and
//throw a CRE instead.
}
}
}
if (m == null || (m instanceof MCPlayer && (!((MCPlayer) m).isOnline() && !injectedPlayers.containsKey(player)))) {
throw new CREPlayerOfflineException("The specified player (" + player + ") is not online", t);
}
return m;
}
public static MCPlayer GetPlayer(Construct player, Target t) throws ConfigRuntimeException {
return GetPlayer(player.val(), t);
}
/**
* If the sender is a player, it is returned, otherwise a
* ConfigRuntimeException is thrown.
*
* @param environment
* @param t
* @return
*/
public static MCPlayer getPlayer(Environment environment, Target t) {
MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
if (player != null) {
return player;
} else {
throw new CREPlayerOfflineException("The passed arguments induce that the function must be run by a player.", t);
}
}
public static boolean isNull(Construct construct) {
return construct instanceof CNull;
}
public static int Normalize(int i, int min, int max) {
return java.lang.Math.min(max, java.lang.Math.max(min, i));
}
public static MCEntity getEntity(Construct id, Target t) {
return getEntityByUuid(GetUUID(id.val(), t), t);
}
public static MCLivingEntity getLivingEntity(Construct id, Target t) {
return getLivingByUUID(GetUUID(id.val(), t), t);
}
/**
* Returns the entity with the specified unique id. If it doesn't exist, a
* ConfigRuntimeException is thrown.
*
* @param id
* @return
*/
public static MCEntity getEntityByUuid(UUID id, Target t) {
for (MCWorld w : getServer().getWorlds()) {
for (MCEntity e : w.getEntities()) {
if (e.getUniqueId().compareTo(id) == 0) {
return StaticLayer.GetCorrectEntity(e);
}
}
}
throw new CREBadEntityException("That entity (UUID " + id + ") does not exist.", t);
}
/**
* Returns the living entity with the specified unique id. If it doesn't exist or
* isn't living, a ConfigRuntimeException is thrown.
*
* @param id
* @return
*/
public static MCLivingEntity getLivingByUUID(UUID id, Target t) {
for (MCWorld w : Static.getServer().getWorlds()) {
for (MCLivingEntity e : w.getLivingEntities()) {
if (e.getUniqueId().compareTo(id) == 0) {
try {
return (MCLivingEntity) StaticLayer.GetCorrectEntity(e);
} catch (ClassCastException cce) {
throw new CREBadEntityException("The entity found was misinterpreted by the converter, this is"
+ " a developer mistake, please file a ticket.", t);
}
}
}
}
throw new CREBadEntityException("That entity (" + id + ") does not exist or is not alive.", t);
}
/**
* Returns all vehicles from all maps.
*
* @return
*/
public static List<MCVehicle> getVehicles() {
List<MCVehicle> vehicles = new ArrayList<MCVehicle>();
for (MCWorld w : Static.getServer().getWorlds()) {
for (MCEntity e : w.getEntities()) {
MCEntity entity = StaticLayer.GetCorrectEntity(e);
if (entity instanceof MCVehicle) {
vehicles.add((MCVehicle) entity);
}
}
}
return vehicles;
}
/**
* Returns the world with the specified name. If it does not exist, a
* ConfigRuntimeException is thrown.
*
* @param name
* @param t
* @return
*/
public static MCWorld getWorld(String name, Target t) {
MCWorld world = getServer().getWorld(name);
if (world != null) {
return world;
} else {
throw new CREInvalidWorldException("Unknown world:" + name + ".", t);
}
}
/**
* Returns the world with the specified name. If it does not exist, a
* ConfigRuntimeException is thrown.
*
* @param name
* @param t
* @return
*/
public static MCWorld getWorld(Construct name, Target t) {
return getWorld(name.val(), t);
}
/**
* Returns the plugin with the specified name. If it does not exist, a
* ConfigRuntimeException is thrown.
*
* @param name
* @param t
* @return
*/
public static MCPlugin getPlugin(String name, Target t) {
MCPlugin plugin = getServer().getPluginManager().getPlugin(name);
if (plugin != null) {
return plugin;
} else {
throw new CREInvalidPluginException("Unknown plugin:" + name + ".", t);
}
}
public static MCPlugin getPlugin(Construct name, Target t) {
return getPlugin(name.val(), t);
}
/**
* Returns the metadatable object designated by the given construct. If the
* construct is invalid or if the object does not exist, a
* ConfigRuntimeException is thrown.
*
* @param construct
* @param t
* @return
*/
public static MCMetadatable getMetadatable(Construct construct, Target t) {
if (construct instanceof CInt) {
return Static.getEntity(construct, t);
} else if (construct instanceof CArray) {
return ObjectGenerator.GetGenerator().location(construct, null, t).getBlock();
} else if (construct instanceof CString) {
switch (construct.val().length()) {
case 32:
case 36:
return Static.getEntity(construct, t);
default:
return Static.getWorld(construct, t);
}
} else {
throw new CRECastException("An array or a string was expected, but " + construct.val()
+ " was found.", t);
}
}
public static String strJoin(Collection c, String inner) {
StringBuilder b = new StringBuilder();
Object[] o = c.toArray();
for (int i = 0; i < o.length; i++) {
if (i != 0) {
b.append(inner);
}
b.append(o[i]);
}
return b.toString();
}
public static String strJoin(Object[] o, String inner) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < o.length; i++) {
if (i != 0) {
b.append(inner);
}
b.append(o[i]);
}
return b.toString();
}
/**
* Returns the system based line seperator character
*
* @return
*/
public static String LF() {
return System.getProperty("line.separator");
}
public static void LogDebug(File root, String message) throws IOException {
LogDebug(root, message, LogLevel.OFF);
}
/**
* Equivalent to LogDebug(root, message, level, true);