/
RestAction.java
1573 lines (1516 loc) · 64.5 KB
/
RestAction.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
/*
* Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.api.requests;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.exceptions.ContextException;
import net.dv8tion.jda.api.exceptions.RateLimitedException;
import net.dv8tion.jda.api.utils.Result;
import net.dv8tion.jda.api.utils.concurrent.DelayedCompletableFuture;
import net.dv8tion.jda.internal.requests.RestActionImpl;
import net.dv8tion.jda.internal.requests.restaction.operator.*;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.ContextRunnable;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* A class representing a terminal between the user and the discord API.
* <br>This is used to offer users the ability to decide how JDA should limit a Request.
*
* <p>Methods that return an instance of RestAction require an additional step
* to complete the execution. Thus the user needs to append a follow-up method.
*
* <p>A default RestAction is issued with the following operations:
* <ul>
* <li>{@link #queue()}, {@link #queue(Consumer)}, {@link #queue(Consumer, Consumer)}
* <br>The fastest and most simplistic way to execute a RestAction is to queue it.
* <br>This method has two optional callback functions, one with the generic type and another with a failure exception.</li>
*
* <li>{@link #submit()}, {@link #submit(boolean)}
* <br>Provides a Future representing the pending request.
* <br>An optional parameter of type boolean can be passed to disable automated rate limit handling. (not recommended)</li>
*
* <li>{@link #complete()}, {@link #complete(boolean)}
* <br>Blocking execution building up on {@link #submit()}.
* <br>This will simply block the thread and return the Request result, or throw an exception.
* <br>An optional parameter of type boolean can be passed to disable automated rate limit handling. (not recommended)</li>
* </ul>
*
* The most efficient way to use a RestAction is by using the asynchronous {@link #queue()} operations.
* <br>These allow users to provide success and failure callbacks which will be called at a convenient time.
*
* <p><b>Planning Execution</b><br>
* To <u>schedule</u> a RestAction we provide both {@link #queue()} and {@link #complete()} versions that
* will be executed by a {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} after a
* specified delay:
* <ul>
* <li>{@link #queueAfter(long, TimeUnit)}
* <br>Schedules a call to {@link #queue()} with default callback {@link java.util.function.Consumer Consumers} to be executed after the specified {@code delay}.
* <br>The {@link java.util.concurrent.TimeUnit TimeUnit} is used to convert the provided long into a delay time.
* <br>Example: {@code queueAfter(1, TimeUnit.SECONDS);}
* <br>will call {@link #queue()} <b>1 second</b> later.</li>
*
* <li>{@link #submitAfter(long, TimeUnit)}
* <br>This returns a {@link java.util.concurrent.ScheduledFuture ScheduledFuture} which
* can be joined into the current Thread using {@link java.util.concurrent.ScheduledFuture#get()}
* <br>The blocking call to {@code submitAfter(delay, unit).get()} will return
* the value processed by a call to {@link #complete()}</li>
*
* <li>{@link #completeAfter(long, TimeUnit)}
* <br>This operation simply sleeps for the given delay and will call {@link #complete()}
* once finished sleeping.</li>
* </ul>
*
* <p>All of those operations provide overloads for optional parameters such as a custom
* {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} instead of using the default
* global JDA executor. Specifically {@link #queueAfter(long, TimeUnit)} has overloads
* to provide a success and/or failure callback due to the returned {@link java.util.concurrent.ScheduledFuture ScheduledFuture}
* not being able to provide the response values of the {@link #queue()} callbacks.
*
* <p><b>Using RestActions</b><br>
* The most common way to use a RestAction is not using the returned value.
* <br>For instance sending messages usually means you will not require to view the message once
* it was sent. Thus we can simply use the <b>asynchronous</b> {@link #queue()} operation which will
* be executed on a rate limit worker thread in the background, without blocking your current thread:
* <pre><code>
* {@link net.dv8tion.jda.api.entities.channel.middleman.MessageChannel MessageChannel} channel = event.getChannel();
* {@literal RestAction<Message>} action = channel.sendMessage("Hello World");
* action.{@link #queue() queue()}; // Execute the rest action asynchronously
* </code></pre>
*
* <p>Sometimes it is important to access the response value, possibly to modify it later.
* <br>Now we have two options to actually access the response value, either using an asynchronous
* callback {@link java.util.function.Consumer Consumer} or the (not recommended) {@link #complete()} which will block
* the current thread until the response has been processed and joins with the current thread.
*
* <p><b>Example Queue: (recommended)</b><br>
* <pre><code>
* {@link net.dv8tion.jda.api.entities.channel.middleman.MessageChannel MessageChannel} channel = event.getChannel();
* final long time = System.currentTimeMillis();
* {@literal RestAction<Message>} action = channel.sendMessage("Calculating Response Time...");
* {@link java.util.function.Consumer Consumer}{@literal <Message>} callback = (message) {@literal -> {
* Message m = message; // ^This is a lambda parameter!^
* m.editMessage("Response Time: " + (System.currentTimeMillis() - time) + "ms").queue();
* // End with queue() to not block the callback thread!
* }};
* // You can also inline this with the queue parameter: action.queue(m {@literal ->} m.editMessage(...).queue());
* action.{@link #queue(Consumer) queue(callback)};
* </code></pre>
*
* <p><b>Example Complete:</b><br>
* <pre><code>
* {@link net.dv8tion.jda.api.entities.channel.middleman.MessageChannel MessageChannel} channel = event.getChannel();
* final long time = System.currentTimeMillis();
* {@literal RestAction<Message>} action = channel.sendMessage("Calculating Response Time...");
* Message message = action.{@link #complete() complete()};
* message.editMessage("Response Time: " + (System.currentTimeMillis() - time) + "ms").queue();
* // End with {@link #queue() queue()} to not block the callback thread!
* </code></pre>
*
* <p><b>Example Planning:</b><br>
* <pre><code>
* {@link net.dv8tion.jda.api.entities.channel.middleman.MessageChannel MessageChannel} channel = event.getChannel();
* {@literal RestAction<Message>} action = channel.sendMessage("This message will destroy itself in 5 seconds!");
* action.queue((message) {@literal ->} message.delete().{@link #queueAfter(long, TimeUnit) queueAfter(5, TimeUnit.SECONDS)});
* </code></pre>
*
* <p><b>Developer Note:</b> It is generally a good practice to use asynchronous logic because blocking threads requires resources
* which can be avoided by using callbacks over blocking operations:
* <br>{@link #queue(Consumer)} {@literal >} {@link #complete()}
*
* <p>There is a dedicated <a href="https://github.com/discord-jda/JDA/wiki/7)-Using-RestAction" target="_blank">wiki page</a>
* for RestActions that can be useful for learning.
*
* @param <T>
* The generic response type for this RestAction
*
* @since 3.0
*
* @see net.dv8tion.jda.api.exceptions.ErrorHandler
* @see net.dv8tion.jda.api.exceptions.ErrorResponseException
*/
public interface RestAction<T>
{
/**
* If enabled this will pass a {@link net.dv8tion.jda.api.exceptions.ContextException ContextException}
* as root-cause to all failure consumers.
* <br>This might cause performance decrease due to the creation of exceptions for <b>every</b> execution.
*
* <p>It is recommended to pass a context consumer as failure manually using {@code queue(success, ContextException.here(failure))}
*
* @param enable
* True, if context should be passed to all failure consumers
*/
static void setPassContext(boolean enable)
{
RestActionImpl.setPassContext(enable);
}
/**
* Whether RestActions will use {@link net.dv8tion.jda.api.exceptions.ContextException ContextException}
* automatically to keep track of the caller context.
* <br>If set to {@code true} this can cause performance drops due to the creation of stack-traces on execution.
*
* @return True, if RestActions will keep track of context automatically
*
* @see #setPassContext(boolean)
*/
static boolean isPassContext()
{
return RestActionImpl.isPassContext();
}
/**
* The default failure callback used when none is provided in {@link #queue(Consumer, Consumer)}.
*
* @param callback
* The fallback to use, or null to ignore failures (not recommended)
*/
static void setDefaultFailure(@Nullable final Consumer<? super Throwable> callback)
{
RestActionImpl.setDefaultFailure(callback);
}
/**
* The default success callback used when none is provided in {@link #queue(Consumer, Consumer)} or {@link #queue(Consumer)}.
*
* @param callback
* The fallback to use, or null to ignore success
*/
static void setDefaultSuccess(@Nullable final Consumer<Object> callback)
{
RestActionImpl.setDefaultSuccess(callback);
}
/**
* Default timeout to apply to every RestAction.
* <br>This will use no timeout unless specified otherwise.
* <br>If the request doesn't get executed within the specified timeout it will fail.
*
* <p>When a RestAction times out, it will fail with a {@link java.util.concurrent.TimeoutException TimeoutException}.
*
* @param timeout
* The default timeout to use
* @param unit
* {@link TimeUnit Unit} for the timeout value
*
* @throws IllegalArgumentException
* If the provided unit is null
*/
static void setDefaultTimeout(long timeout, @Nonnull TimeUnit unit)
{
RestActionImpl.setDefaultTimeout(timeout, unit);
}
/**
* The default timeout to apply to every RestAction in milliseconds.
* <br>If no timeout has been configured, this will return 0.
*
* <p>When a RestAction times out, it will fail with a {@link java.util.concurrent.TimeoutException TimeoutException}.
*
* @return The default timeout in milliseconds, or 0
*/
static long getDefaultTimeout()
{
return RestActionImpl.getDefaultTimeout();
}
/**
* The default failure callback used when none is provided in {@link #queue(Consumer, Consumer)}.
*
* @return The fallback consumer
*/
@Nonnull
static Consumer<? super Throwable> getDefaultFailure()
{
return RestActionImpl.getDefaultFailure();
}
/**
* The default success callback used when none is provided in {@link #queue(Consumer, Consumer)} or {@link #queue(Consumer)}.
*
* @return The fallback consumer
*/
@Nonnull
static Consumer<Object> getDefaultSuccess()
{
return RestActionImpl.getDefaultSuccess();
}
/**
* Creates a RestAction instance which accumulates all results of the provided actions.
* <br>If one action fails, all others will be cancelled.
* To handle failures individually instead of cancelling you can use {@link #mapToResult()}.
*
* @param first
* The initial RestAction starting point
* @param others
* The remaining actions to accumulate
* @param <E>
* The result type
*
* @throws IllegalArgumentException
* If null is provided
*
* @return RestAction - Type: {@link List} of the results
*
* @see #and(RestAction, BiFunction)
* @see #zip(RestAction, RestAction[])
*
* @since 4.2.1
*/
@Nonnull
@SafeVarargs
@CheckReturnValue
static <E> RestAction<List<E>> allOf(@Nonnull RestAction<? extends E> first, @Nonnull RestAction<? extends E>... others)
{
Checks.notNull(first, "RestAction");
Checks.noneNull(others, "RestAction");
List<RestAction<? extends E>> list = new ArrayList<>(others.length + 1);
list.add(first);
Collections.addAll(list, others);
return allOf(list);
}
/**
* Creates a RestAction instance which accumulates all results of the provided actions.
* <br>If one action fails, all others will be cancelled.
* To handle failures individually instead of cancelling you can use {@link #mapToResult()}.
*
* @param actions
* Non-empty collection of RestActions to accumulate
* @param <E>
* The result type
*
* @throws IllegalArgumentException
* If null is provided or the collection is empty
*
* @return RestAction - Type: {@link List} of the results
*
* @see #and(RestAction, BiFunction)
* @see #zip(RestAction, RestAction[])
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
static <E> RestAction<List<E>> allOf(@Nonnull Collection<? extends RestAction<? extends E>> actions)
{
return accumulate(actions, Collectors.toList());
}
/**
* Creates a RestAction instance which accumulates all results of the provided actions.
* <br>If one action fails, all others will be cancelled.
* To handle failures individually instead of cancelling you can use {@link #mapToResult()}.
*
* @param actions
* Non-empty collection of RestActions to accumulate
* @param collector
* The {@link Collector} to use
* @param <E>
* The input type
* @param <A>
* The accumulator type
* @param <O>
* The output type
*
* @throws IllegalArgumentException
* If null is provided or the collection is empty
*
* @return RestAction - Type: {@link List} of the results
*
* @see #and(RestAction, BiFunction)
* @see #zip(RestAction, RestAction[])
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
static <E, A, O> RestAction<O> accumulate(@Nonnull Collection<? extends RestAction<? extends E>> actions, @Nonnull Collector<? super E, A, ? extends O> collector)
{
Checks.noneNull(actions, "RestAction");
Checks.notEmpty(actions, "RestActions");
Checks.notNull(collector, "Collector");
Supplier<A> accumulator = collector.supplier();
BiConsumer<A, ? super E> add = collector.accumulator();
Function<A, ? extends O> output = collector.finisher();
actions = new LinkedHashSet<>(actions);
Iterator<? extends RestAction<? extends E>> iterator = actions.iterator();
RestAction<A> result = iterator.next().map(it -> {
A list = accumulator.get();
add.accept(list, it);
return list;
});
while (iterator.hasNext())
{
RestAction<? extends E> next = iterator.next();
result = result.and(next, (list, b) -> {
add.accept(list, b);
return list;
});
}
return result.map(output);
}
/**
* The current JDA instance
*
* @return The corresponding JDA instance
*/
@Nonnull
JDA getJDA();
/**
* Sets the last-second checks before finally executing the http request in the queue.
* <br>If the provided supplier evaluates to {@code false} or throws an exception this will not be finished.
* When an exception is thrown from the supplier it will be provided to the failure callback.
*
* @param checks
* The checks to run before executing the request, or {@code null} to run no checks
*
* @return The current RestAction for chaining convenience
*
* @see #getCheck()
* @see #addCheck(BooleanSupplier)
*/
@Nonnull
RestAction<T> setCheck(@Nullable BooleanSupplier checks);
/**
* The current checks for this RestAction.
*
* @return The current checks, or null if none were set
*
* @see #setCheck(BooleanSupplier)
*
* @since 4.2.1
*/
@Nullable
default BooleanSupplier getCheck()
{
return null;
}
/**
* Shortcut for {@code setCheck(() -> getCheck().getAsBoolean() && checks.getAsBoolean())}.
*
* @param checks
* Other checks to run
*
* @throws IllegalArgumentException
* If the provided checks are null
*
* @return The current RestAction for chaining convenience
*
* @see #setCheck(BooleanSupplier)
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
default RestAction<T> addCheck(@Nonnull BooleanSupplier checks)
{
Checks.notNull(checks, "Checks");
BooleanSupplier check = getCheck();
return setCheck(() -> (check == null || check.getAsBoolean()) && checks.getAsBoolean());
}
/**
* Timeout for this RestAction instance.
* <br>If the request doesn't get executed within the timeout it will fail.
*
* <p>When a RestAction times out, it will fail with a {@link java.util.concurrent.TimeoutException TimeoutException}.
* This is the same as {@code deadline(System.currentTimeMillis() + unit.toMillis(timeout))}.
*
* <p><b>Example</b><br>
* <pre>{@code
* action.timeout(10, TimeUnit.SECONDS) // 10 seconds from now
* .queueAfter(20, SECONDS); // request will not be executed within deadline and timeout immediately after 20 seconds
* }</pre>
*
* @param timeout
* The timeout to use
* @param unit
* {@link TimeUnit Unit} for the timeout value
*
* @throws IllegalArgumentException
* If the provided unit is null
*
* @return The same RestAction instance with the applied timeout
*
* @see #setDefaultTimeout(long, TimeUnit)
*/
@Nonnull
default RestAction<T> timeout(long timeout, @Nonnull TimeUnit unit)
{
Checks.notNull(unit, "TimeUnit");
return deadline(timeout <= 0 ? 0 : System.currentTimeMillis() + unit.toMillis(timeout));
}
/**
* Similar to {@link #timeout(long, TimeUnit)} but schedules a deadline at which the request has to be completed.
* <br>If the deadline is reached, the request will fail with a {@link java.util.concurrent.TimeoutException TimeoutException}.
*
* <p>This does not mean that the request will immediately timeout when the deadline is reached. JDA will check the deadline
* right before executing the request or within intervals in a worker thread. This only means the request will timeout
* if the deadline has passed.
*
* <p><b>Example</b><br>
* <pre>{@code
* action.deadline(System.currentTimeMillis() + 10000) // 10 seconds from now
* .queueAfter(20, SECONDS); // request will not be executed within deadline and timeout immediately after 20 seconds
* }</pre>
*
* @param timestamp
* Millisecond timestamp at which the request will timeout
*
* @return The same RestAction with the applied deadline
*
* @see #timeout(long, TimeUnit)
* @see #setDefaultTimeout(long, TimeUnit)
*/
@Nonnull
default RestAction<T> deadline(long timestamp)
{
throw new UnsupportedOperationException();
}
/**
* Submits a Request for execution.
* <br>Using the default callback functions:
* {@link #setDefaultSuccess(Consumer)} and {@link #setDefaultFailure(Consumer)}
*
* <p>To access the response you can use {@link #queue(java.util.function.Consumer)}
* and to handle failures use {@link #queue(java.util.function.Consumer, java.util.function.Consumer)}.
*
* <p><b>This method is asynchronous</b>
*
* <p><b>Example</b><br>
* <pre>{@code
* public static void sendMessage(MessageChannel channel, String content)
* {
* // sendMessage returns "MessageAction" which is a specialization for "RestAction<Message>"
* RestAction<Message> action = channel.sendMessage(content);
* // call queue() to send the message off to discord.
* action.queue();
* }
* }</pre>
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
*
* @see net.dv8tion.jda.api.entities.channel.middleman.MessageChannel#sendMessage(java.lang.CharSequence) MessageChannel.sendMessage(CharSequence)
* @see #queue(java.util.function.Consumer) queue(Consumer)
* @see #queue(java.util.function.Consumer, java.util.function.Consumer) queue(Consumer, Consumer)
*/
default void queue()
{
queue(null);
}
/**
* Submits a Request for execution.
* <br>Using the default failure callback function.
*
* <p>To handle failures use {@link #queue(java.util.function.Consumer, java.util.function.Consumer)}.
*
* <p><b>This method is asynchronous</b>
*
* <p><b>Example</b><br>
* <pre>{@code
* public static void sendPrivateMessage(User user, String content)
* {
* // The "<PrivateChannel>" is the response type for the parameter in the success callback
* RestAction<PrivateChannel> action = user.openPrivateChannel();
* // "channel" is the identifier we use to access the channel of the response
* // this is like the "user" we declared above, just a name for the function parameter
* action.queue((channel) -> channel.sendMessage(content).queue());
* }
* }</pre>
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
*
* @param success
* The success callback that will be called at a convenient time
* for the API. (can be null)
*
* @see #queue(java.util.function.Consumer, java.util.function.Consumer) queue(Consumer, Consumer)
*/
default void queue(@Nullable Consumer<? super T> success)
{
queue(success, null);
}
/**
* Submits a Request for execution.
*
* <p><b>This method is asynchronous</b>
*
* <p><b>Example</b><br>
* <pre>{@code
* public static void sendPrivateMessage(JDA jda, String userId, String content)
* {
* // Retrieve the user by their id
* RestAction<User> action = jda.retrieveUserById(userId);
* action.queue(
* // Handle success if the user exists
* (user) -> user.openPrivateChannel().queue(
* (channel) -> channel.sendMessage(content).queue()),
*
* // Handle failure if the user does not exist (or another issue appeared)
* (error) -> error.printStackTrace()
* );
*
* // Alternatively use submit() to remove nested callbacks
* }
* }</pre>
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
*
* @param success
* The success callback that will be called at a convenient time
* for the API. (can be null to use default)
* @param failure
* The failure callback that will be called if the Request
* encounters an exception at its execution point. (can be null to use default)
*
* @see #submit()
* @see net.dv8tion.jda.api.exceptions.ErrorHandler
*/
void queue(@Nullable Consumer<? super T> success, @Nullable Consumer<? super Throwable> failure);
/**
* Blocks the current Thread and awaits the completion
* of an {@link #submit()} request.
* <br>Used for synchronous logic.
*
* <p><b>This might throw {@link java.lang.RuntimeException RuntimeExceptions}</b>
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
* @throws IllegalStateException
* If used within a {@link #queue(Consumer, Consumer) queue(...)} callback
*
* @return The response value
*/
default T complete()
{
try
{
return complete(true);
}
catch (RateLimitedException e)
{
//This is so beyond impossible, but on the off chance that the laws of nature are rewritten
// after the writing of this code, I'm placing this here.
//Better safe than sorry?
throw new AssertionError(e);
}
}
/**
* Blocks the current Thread and awaits the completion
* of an {@link #submit()} request.
* <br>Used for synchronous logic.
*
* @param shouldQueue
* Whether this should automatically handle rate limitations (default true)
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
* @throws IllegalStateException
* If used within a {@link #queue(Consumer, Consumer) queue(...)} callback
* @throws RateLimitedException
* If we were rate limited and the {@code shouldQueue} is false.
* Use {@link #complete()} to avoid this Exception.
*
* @return The response value
*/
T complete(boolean shouldQueue) throws RateLimitedException;
/**
* Submits a Request for execution and provides a {@link java.util.concurrent.CompletableFuture CompletableFuture}
* representing its completion task.
* <br>Cancelling the returned Future will result in the cancellation of the Request!
*
* <p><b>Example</b><br>
* <pre>{@code
* public static void sendPrivateMessage(JDA jda, String userId, String content)
* {
* // Retrieve the user by their id
* RestAction<User> action = jda.retrieveUserById(userId);
* action.submit() // CompletableFuture<User>
* // Handle success if the user exists
* .thenCompose((user) -> user.openPrivateChannel().submit()) // CompletableFuture<PrivateChannel>
* .thenCompose((channel) -> channel.sendMessage(content).submit()) // CompletableFuture<Void>
* .whenComplete((v, error) -> {
* // Handle failure if the user does not exist (or another issue appeared)
* if (error != null) error.printStackTrace();
* });
* }
* }</pre>
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
*
* @return Never-null {@link java.util.concurrent.CompletableFuture CompletableFuture} representing the completion promise
*/
@Nonnull
default CompletableFuture<T> submit()
{
return submit(true);
}
/**
* Submits a Request for execution and provides a {@link java.util.concurrent.CompletableFuture CompletableFuture}
* representing its completion task.
* <br>Cancelling the returned Future will result in the cancellation of the Request!
*
* @throws java.util.concurrent.RejectedExecutionException
* If the requester has been shutdown by {@link JDA#shutdown()} or {@link JDA#shutdownNow()}
*
* @param shouldQueue
* Whether the Request should automatically handle rate limitations. (default true)
*
* @return Never-null {@link java.util.concurrent.CompletableFuture CompletableFuture} task representing the completion promise
*/
@Nonnull
CompletableFuture<T> submit(boolean shouldQueue);
/**
* Converts the success and failure callbacks into a {@link Result}.
* <br>This means the {@link #queue(Consumer, Consumer)} failure consumer will never be used.
* Instead, all results will be evaluated into a success consumer which provides an instance of {@link Result}.
*
* <p>{@link Result} will either be {@link Result#isSuccess() successful} or {@link Result#isFailure() failed}.
* This can be useful in combination with {@link #allOf(Collection)} to handle failed requests individually for each
* action.
*
* <p><b>Note: You have to handle failures explicitly with this.</b>
* You should use {@link Result#onFailure(Consumer)}, {@link Result#getFailure()}, or {@link Result#expect(Predicate)}!
*
* @return RestAction - Type: {@link Result}
*
* @since 4.2.1
*/
@Nonnull
@CheckReturnValue
default RestAction<Result<T>> mapToResult()
{
return map(Result::success).onErrorMap(Result::failure);
}
/**
* Intermediate operator that returns a modified RestAction.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on successful execution.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<String> retrieveMemberNickname(Guild guild, String userId) {
* return guild.retrieveMemberById(userId)
* .map(Member::getNickname);
* }
* }</pre>
*
* @param map
* The mapping function to apply to the action result
*
* @param <O>
* The target output type
*
* @return RestAction for the mapped type
*
* @since 4.1.1
*/
@Nonnull
@CheckReturnValue
default <O> RestAction<O> map(@Nonnull Function<? super T, ? extends O> map)
{
Checks.notNull(map, "Function");
return new MapRestAction<>(this, map);
}
/**
* An intermediate operator that returns a modified RestAction.
*
* <p>This does not modify this instance but returns a new RestAction, which will consume
* the actions result using the given consumer on successful execution.
* The resulting action continues with the previous result.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<String> retrieveMemberNickname(Guild guild, String userId) {
* return guild.retrieveMemberById(userId)
* .map(Member::getNickname)
* .onSuccess(System.out::println);
* }
* }</pre>
*
* Prefer using {@link #queue(Consumer)} instead, if continuation of the action
* chain is not desired.
*
* @param consumer
* The consuming function to apply to the action result, failures are propagated
* into the resulting action
*
* @throws IllegalArgumentException
* If the consumer is null
*
* @return RestAction that consumes the action result
*/
@Nonnull
@CheckReturnValue
default RestAction<T> onSuccess(@Nonnull Consumer<? super T> consumer)
{
Checks.notNull(consumer, "Consumer");
return map(result -> {
consumer.accept(result);
return result;
});
}
/**
* Supply a fallback value when the RestAction fails for any reason.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on failed execution.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<String> sendMessage(User user, String content) {
* return user.openPrivateChannel() // RestAction<PrivateChannel>
* .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
* .map(Message::getContentRaw) // RestAction<String>
* .onErrorMap(Throwable::getMessage); // RestAction<String> (must be the same as above)
* }
* }</pre>
*
* @param map
* The mapping function which provides the fallback value to use
*
* @throws IllegalArgumentException
* If the mapping function is null
*
* @return RestAction with fallback handling
*
* @since 4.2.0
*/
@Nonnull
@CheckReturnValue
default RestAction<T> onErrorMap(@Nonnull Function<? super Throwable, ? extends T> map)
{
return onErrorMap(null, map);
}
/**
* Supply a fallback value when the RestAction fails for a specific reason.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on failed execution.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<String> sendMessage(User user, String content) {
* return user.openPrivateChannel() // RestAction<PrivateChannel>
* .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
* .map(Message::getContentRaw) // RestAction<String>
* .onErrorMap(CANNOT_SEND_TO_USER::test, Throwable::getMessage); // RestAction<String> (must be the same as above)
* }
* }</pre>
*
* @param condition
* A condition that must return true to apply this fallback
* @param map
* The mapping function which provides the fallback value to use
*
* @throws IllegalArgumentException
* If the mapping function is null
*
* @return RestAction with fallback handling
*
* @see ErrorResponse#test(Throwable)
* @see ErrorResponse#test(ErrorResponse...)
*
* @since 4.2.0
*/
@Nonnull
@CheckReturnValue
default RestAction<T> onErrorMap(@Nullable Predicate<? super Throwable> condition, @Nonnull Function<? super Throwable, ? extends T> map)
{
Checks.notNull(map, "Function");
return new MapErrorRestAction<>(this, condition == null ? (x) -> true : condition, map);
}
/**
* Supply a fallback value when the RestAction fails for a any reason.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on failed execution.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<Message> sendMessage(User user, TextChannel context, String content) {
* return user.openPrivateChannel() // RestAction<PrivateChannel>
* .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
* .onErrorFlatMap(
* (error) -> context.sendMessage("Failed to send direct message to " + user.getAsMention() + " Reason: " + error)
* ); // RestAction<Message> (must be the same as above)
* }
* }</pre>
*
* @param map
* The mapping function which provides the fallback action to use
*
* @throws IllegalArgumentException
* If the mapping function is null
*
* @return RestAction with fallback handling
*
* @since 4.2.0
*/
@Nonnull
@CheckReturnValue
default RestAction<T> onErrorFlatMap(@Nonnull Function<? super Throwable, ? extends RestAction<? extends T>> map)
{
return onErrorFlatMap(null, map);
}
/**
* Supply a fallback value when the RestAction fails for a specific reason.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on failed execution.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<Message> sendMessage(User user, TextChannel context, String content) {
* return user.openPrivateChannel() // RestAction<PrivateChannel>
* .flatMap((channel) -> channel.sendMessage(content)) // RestAction<Message>
* .onErrorFlatMap(CANNOT_SEND_TO_USER::test,
* (error) -> context.sendMessage("Cannot send direct message to " + user.getAsMention())
* ); // RestAction<Message> (must be the same as above)
* }
* }</pre>
*
* @param condition
* A condition that must return true to apply this fallback
* @param map
* The mapping function which provides the fallback action to use
*
* @throws IllegalArgumentException
* If the mapping function is null
*
* @return RestAction with fallback handling
*
* @see ErrorResponse#test(Throwable)
* @see ErrorResponse#test(ErrorResponse...)
*
* @since 4.2.0
*/
@Nonnull
@CheckReturnValue
default RestAction<T> onErrorFlatMap(@Nullable Predicate<? super Throwable> condition, @Nonnull Function<? super Throwable, ? extends RestAction<? extends T>> map)
{
Checks.notNull(map, "Function");
return new FlatMapErrorRestAction<>(this, condition == null ? (x) -> true : condition, map);
}
/**
* Intermediate operator that returns a modified RestAction.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on successful execution. This will compute the result of both RestActions.
* <br>The returned RestAction must not be null!
* To terminate the execution chain on a specific condition you can use {@link #flatMap(Predicate, Function)}.
*
* <p><b>Example</b><br>
* <pre>{@code
* public RestAction<Void> initializeGiveaway(Guild guild, String channelName) {
* return guild.createTextChannel(channelName)
* .addPermissionOverride(guild.getPublicRole(), null, EnumSet.of(Permission.MESSAGE_SEND)) // deny write for everyone
* .addPermissionOverride(guild.getSelfMember(), EnumSet.of(Permission.MESSAGE_SEND), null) // allow for self user
* .flatMap((channel) -> channel.sendMessage("React to enter giveaway!")) // send message
* .flatMap((message) -> message.addReaction(REACTION)); // add reaction
* }
* }</pre>
*
* @param flatMap
* The mapping function to apply to the action result, must return a RestAction
*
* @param <O>
* The target output type
*
* @return RestAction for the mapped type
*
* @since 4.1.1
*/
@Nonnull
@CheckReturnValue
default <O> RestAction<O> flatMap(@Nonnull Function<? super T, ? extends RestAction<O>> flatMap)
{
return flatMap(null, flatMap);
}
/**
* Intermediate operator that returns a modified RestAction.
*
* <p>This does not modify this instance but returns a new RestAction which will apply
* the map function on successful execution. This will compute the result of both RestActions.
* <br>The provided RestAction must not be null!
*
* <p><b>Example</b><br>
* <pre>{@code
* private static final int MAX_COUNT = 1000;
* public void updateCount(MessageChannel channel, String messageId, int count) {
* channel.retrieveMessageById(messageId) // retrieve message for check
* .map(Message::getContentRaw) // get content of the message