/
ScriptQueue.java
564 lines (434 loc) · 16.1 KB
/
ScriptQueue.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
package net.aufdemrand.denizen.scripts.queues;
import net.aufdemrand.denizen.objects.Duration;
import net.aufdemrand.denizen.objects.dObject;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.Debuggable;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.Bukkit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* ScriptQueues hold/control ScriptEntries while being sent
* to the CommandExecuter
*
* @version 1.0
* @author Jeremy Schroeder
*/
public abstract class ScriptQueue implements Debuggable {
protected static long total_queues = 0;
/**
* Returns the number of queues created in the current instance
* as well as the number of currently active queues.
*
* @return stats
*/
public static String _getStats() {
return "Total number of queues created: "
+ total_queues
+ ", currently active queues: "
+ _queues.size() + ".";
}
/**
* Gets an existing queue. Cast to the correct QueueType to
* access further methods.
*
* @param id the id of the queue
* @return a ScriptQueue instance, or null
*/
public static ScriptQueue _getExistingQueue(String id) {
if (!_queueExists(id)) return null;
else return _queues.get(id.toUpperCase());
}
/**
* Gets a random UUID for use in creating a 'nameless' queue.
*
* @return String value of a random UUID
*/
public static String _getNextId() {
return UUID.randomUUID().toString();
}
/**
* Checks the type of an existing queue with the type given.
*
* @param queue id of the queue
* @param type class of the queue type
* @return true if they match, false if the queue
* doesn't exist or does not match
*/
public static boolean _matchesType(String queue, Class type) {
return (_queueExists(queue.toUpperCase())) && _queues.get(queue.toUpperCase()).getClass() == type;
}
// Contains all currently active queues, keyed by a String id.
protected static Map<String, ScriptQueue> _queues =
new ConcurrentHashMap<String, ScriptQueue>(8, 0.9f, 1);
/**
* Returns a collection of all active queues.
*
* @return a collection of ScriptQueues
*/
public static Collection<ScriptQueue> _getQueues() {
return _queues.values();
}
/**
* Checks if a queue exists with the given id.
*
* @param id the String ID of the queue to check.
* @return true if it exists.
*/
public static boolean _queueExists(String id) {
return _queues.containsKey(id.toUpperCase());
}
/////////////////////
// Public instance fields
/////////////////////
// Name of the queue -- this identifies
// the ScriptQueue when using _getQueue()
public String id;
// Whether the queue was cleared
public boolean was_cleared = false;
/////////////////////
// Private instance fields and constructors
/////////////////////
// List of ScriptEntries in the queue
private List<ScriptEntry>
script_entries = new ArrayList<ScriptEntry>();
// The last script entry that was executed
// in this queue.
private ScriptEntry lastEntryExecuted = null;
// If this number is larger than Java's
// getCurrentTimeMillis(), the queue will
// delay execution of the next ScriptEntry
private long delay_time = 0;
// ScriptQueues can have a definitions,
// keyed by a String Id. Denizen's
// 'Definitions' system uses this map.
// This information is fetched by using
// %definition_name%
private Map<String, String>
definitions = new ConcurrentHashMap<String, String>(8, 0.9f, 1);
// ScriptQueues can also have a list of context, added
// by events/actions/etc. This is kind of like the context
// inside scriptEntries, but within the scope of the entire
// queue.
// To access this context, use <c.context_name> or <context.context_name>
private Map<String, dObject>
context = new ConcurrentHashMap<String, dObject>();
// Held script entries can be recalled later in the script
// and their scriptEntry context can be recalled. Good for
// commands that contain unique items/objects that it's
// created.
private Map<String, ScriptEntry>
held_entries = new ConcurrentHashMap<String, ScriptEntry>();
/**
* Creates a ScriptQueue instance. Users of
* the API should instead use the static members
* of classes that extend ScriptQueue.
*
* @param id the name of the ScriptQueue
*/
protected ScriptQueue(String id) {
// Remember the 'id'
this.id = id.toUpperCase();
// Save the instance to the _queues static map
_queues.put(id.toUpperCase(), this);
// Increment the stats
total_queues++;
}
/////////////////////
// Public instance setters and getters
/////////////////////
/**
* Gets a boolean indicating whether the queue
* was cleared.
*
* @return whether the queue has been cleared.
*/
public boolean getWasCleared() {
return was_cleared;
}
/**
* Gets a held script entry. Held script entries might
* contains some script entry context that might need
* to be fetched!
*
*/
public ScriptEntry getHeldScriptEntry(String id) {
return held_entries.get(id.toLowerCase());
}
/**
* Provides a way to hold a script entry for retrieval later in the
* script. Keyed by an id, which is turned to lowercase making
* it case insensitive.
*
* @param id intended name of the entry
* @param entry the ScriptEntry instance
* @return the ScriptQueue, just in case you need to do more with it
*/
public ScriptQueue holdScriptEntry(String id, ScriptEntry entry) {
// to lowercase to avoid case sensitivity.
held_entries.put(id.toLowerCase(), entry);
return this;
}
/**
* Gets a context from the queue. Script writers can
* use the <c.context_name> or <context.context_name> tags
* to fetch this data.
*
* @param id The name of the definitions
* @return The value of the definitions, or null
*/
public dObject getContext(String id) {
return context.get(id.toLowerCase());
}
/**
* Checks for a piece of context.
*
* @param id The name of the context
* @return true if the context exists.
*/
public boolean hasContext(String id) {
return context.containsKey(id.toLowerCase());
}
/**
* Adds a new piece of context to the queue. This is usually
* done within events or actions, or wherever script creation has
* some information to pass along, other than a player and npc.
*
* @param id the name of the context
* @param value the value of the context
*/
public void addContext(String id, dObject value) {
context.put(id.toLowerCase(), value);
}
/**
* Returns a Map of all the current context
* stored in the queue, keyed by 'id'
*
* @return all current context, empty if none.
*/
public Map<String, dObject> getAllContext() {
return context;
}
/**
* Gets a definition from the queue. Denizen's
* CommandExecuter will fetch this information
* by using the %definition_name% format, similar
* to 'replaceable tags'
*
* @param definition The name of the definitions
* @return The value of the definitions, or null
*/
public String getDefinition(String definition) {
return definitions.get(definition.toLowerCase());
}
/**
* Checks for a piece of definitions.
*
* @param definition The name of the definitions
* @return true if the definition exists.
*/
public boolean hasDefinition(String definition) {
return definitions.containsKey(definition.toLowerCase());
}
/**
* Adds a new piece of definitions to the queue. This
* can be done with dScript as well by using the
* 'define' command.
*
* @param definition the name of the definitions
* @param value the value of the definition
*/
public void addDefinition(String definition, String value) {
definitions.put(definition.toLowerCase(), value);
}
/**
* Returns a Map of all the current definitions
* stored in the queue, keyed by 'definition id'
*
* @return all current definitions, empty if none.
*/
public Map<String, String> getAllDefinitions() {
return definitions;
}
/**
* The last entry that was executed. Note: any
* replaceable tags/etc. are already replaced
* in this ScriptEntry.
*
* @return
*/
public ScriptEntry getLastEntryExecuted() {
return lastEntryExecuted;
}
/**
* Clears the script queue.
*
* Use the 'queue clear' command in dScript to
* access this method.
*/
public void clear() {
was_cleared = true;
script_entries.clear();
}
/**
* Will delay the start of the queue until Java's
* System.currentTimeMillis() is less than the
* delayTime.
*
* @param delayTime the time to start the queue, in
* System.currentTimeMillis() format.
*/
public void delayUntil(long delayTime) {
this.delay_time = delayTime;
}
///////////////////
// Public 'functional' methods
//////////////////
/**
* Starts the script queue.
*
*/
protected abstract void onStart();
protected boolean is_started;
public void start() {
if (is_started) return;
// Set as started, and check for a valid delay_time.
is_started = true;
boolean is_delayed = false;
if (delay_time > System.currentTimeMillis())
is_delayed = true;
// If it's delayed, schedule it for later
if (is_delayed) {
Bukkit.getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(),
new Runnable() {
@Override
public void run() { onStart(); /* Start the engine */ }
// Take the delay time, find out how many milliseconds away
// it is, turn it into seconds, then divide by 20 for ticks.
},
(delay_time - System.currentTimeMillis()) / 1000 * 20);
} else
// If it's not, start the engine now!
onStart();
if (is_delayed) {
dB.echoDebug(this, "Delaying " + getClass().getSimpleName() + " '" + id + "'" + " for '"
+ new Duration((delay_time - System.currentTimeMillis()) / 1000 * 20).identify() + "'.");
} else
dB.echoDebug(this, "Starting " + getClass().getSimpleName() + " '" + id + "'");
}
/**
* Stops the script_queue and breaks it down.
*
*/
protected abstract void onStop();
protected boolean is_stopping = false;
public void stop() {
// If this is the first time this has been called, check the
// ScriptContainer event 'on queue completes' which may have
// a few more script entries to run.
if (!is_stopping) {
is_stopping = true;
// Get the entries
List<ScriptEntry> entries =
(lastEntryExecuted != null && lastEntryExecuted.getScript() != null ?
lastEntryExecuted.getScript().getContainer()
.getEntries(lastEntryExecuted.getPlayer(),
lastEntryExecuted.getNPC(), "on queue completes") : new ArrayList<ScriptEntry>());
// Add the 'finishing' entries back into the queue (if not empty)
if (!entries.isEmpty()) {
script_entries.addAll(entries);
dB.echoDebug(this, "Finishing up queue " + id + "...");
} else /* if empty, just stop the queue like normal */ {
_queues.remove(id);
dB.echoDebug(this, "Completing queue " + id + "...");
is_started = false;
onStop();
}
}
// Else, just complete the queue.
// 1) Remove the id from active queue list
// 2) Cancel the corresponding task_id
else {
_queues.remove(id);
dB.echoDebug(this, "Completing queue " + id + "...");
is_started = false;
onStop();
}
}
////////////////////
// Internal methods and fields
////////////////////
/**
* Sets the last entry executed by the ScriptEngine.
*
* @param entry the ScriptEntry last executed.
*/
public void setLastEntryExecuted(ScriptEntry entry) {
lastEntryExecuted = entry;
}
protected abstract boolean shouldRevolve();
protected void revolve() {
// If entries queued up are empty, deconstruct the queue.
if (script_entries.isEmpty()) {
stop();
return;
}
if (!shouldRevolve()) return;
// Criteria met for a successful 'revolution' of this queue,
// so send the next script entry to the ScriptEngine.
DenizenAPI.getCurrentInstance().getScriptEngine().revolve(this);
if (script_entries.isEmpty()) {
stop();
}
}
public ScriptEntry getNext() {
if (!script_entries.isEmpty()) {
ScriptEntry entry = script_entries.get(0);
script_entries.remove(0);
return entry;
}
else return null;
}
public ScriptQueue addEntries(List<ScriptEntry> entries) {
script_entries.addAll(entries);
return this;
}
public boolean hasInjectedItems = false;
public ScriptQueue injectEntries(List<ScriptEntry> entries, int position) {
if (position > script_entries.size() || position < 0) position = 1;
if (script_entries.size() == 0) position = 0;
script_entries.addAll(position, entries);
hasInjectedItems = true;
return this;
}
public boolean removeEntry(int position) {
if (script_entries.size() < position) return false;
script_entries.remove(position);
return true;
}
public ScriptEntry getEntry(int position) {
if (script_entries.size() < position) return null;
return script_entries.get(position);
}
public ScriptQueue injectEntry(ScriptEntry entry, int position) {
if (position > script_entries.size() || position < 0) position = 1;
if (script_entries.size() == 0) position = 0;
script_entries.add(position, entry);
hasInjectedItems = true;
return this;
}
public int getQueueSize() {
return script_entries.size();
}
@Override
public boolean shouldDebug() throws Exception {
return (lastEntryExecuted != null ? lastEntryExecuted.shouldDebug()
: script_entries.get(0).shouldDebug());
}
@Override
public boolean shouldFilter(String criteria) throws Exception {
return (lastEntryExecuted != null ? lastEntryExecuted.getScript().getName().equalsIgnoreCase(criteria.replace("s@", ""))
: script_entries.get(0).getScript().getName().equalsIgnoreCase(criteria.replace("s@", "")));
}
}