/
DataArray.java
770 lines (721 loc) · 21.7 KB
/
DataArray.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
/*
* 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.utils.data;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.CollectionType;
import net.dv8tion.jda.api.exceptions.ParsingException;
import net.dv8tion.jda.api.utils.data.etf.ExTermDecoder;
import net.dv8tion.jda.api.utils.data.etf.ExTermEncoder;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.Helpers;
import org.jetbrains.annotations.Contract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Represents a list of values used in communication with the Discord API.
*
* <p>Throws {@link java.lang.IndexOutOfBoundsException}
* if provided with index out of bounds.
*
* <p>This class is not Thread-Safe
*/
public class DataArray implements Iterable<Object>, SerializableArray
{
private static final Logger log = LoggerFactory.getLogger(DataObject.class);
private static final ObjectMapper mapper;
private static final SimpleModule module;
private static final CollectionType listType;
static
{
mapper = new ObjectMapper();
module = new SimpleModule();
module.addAbstractTypeMapping(Map.class, HashMap.class);
module.addAbstractTypeMapping(List.class, ArrayList.class);
mapper.registerModule(module);
listType = mapper.getTypeFactory().constructRawCollectionType(ArrayList.class);
}
protected final List<Object> data;
protected DataArray(List<Object> data)
{
this.data = data;
}
/**
* Creates a new empty DataArray, ready to be populated with values.
*
* @return An empty DataArray instance
*
* @see #add(Object)
*/
@Nonnull
public static DataArray empty()
{
return new DataArray(new ArrayList<>());
}
/**
* Creates a new DataArray and populates it with the contents
* of the provided collection.
*
* @param col
* The {@link java.util.Collection}
*
* @return A new DataArray populated with the contents of the collection
*/
@Nonnull
public static DataArray fromCollection(@Nonnull Collection<?> col)
{
return empty().addAll(col);
}
/**
* Parses a JSON Array into a DataArray instance.
*
* @param json
* The correctly formatted JSON Array
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the provided JSON is incorrectly formatted
*
* @return A new DataArray instance for the provided array
*/
@Nonnull
public static DataArray fromJson(@Nonnull String json)
{
try
{
return new DataArray(mapper.readValue(json, listType));
}
catch (IOException e)
{
throw new ParsingException(e);
}
}
/**
* Parses a JSON Array into a DataArray instance.
*
* @param json
* The correctly formatted JSON Array
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the provided JSON is incorrectly formatted or an I/O error occurred
*
* @return A new DataArray instance for the provided array
*/
@Nonnull
public static DataArray fromJson(@Nonnull InputStream json)
{
try
{
return new DataArray(mapper.readValue(json, listType));
}
catch (IOException e)
{
throw new ParsingException(e);
}
}
/**
* Parses a JSON Array into a DataArray instance.
*
* @param json
* The correctly formatted JSON Array
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the provided JSON is incorrectly formatted or an I/O error occurred
*
* @return A new DataArray instance for the provided array
*/
@Nonnull
public static DataArray fromJson(@Nonnull Reader json)
{
try
{
return new DataArray(mapper.readValue(json, listType));
}
catch (IOException e)
{
throw new ParsingException(e);
}
}
/**
* Parses using {@link ExTermDecoder}.
* The provided data must start with the correct version header (131).
*
* @param data
* The data to decode
*
* @throws IllegalArgumentException
* If the provided data is null
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the provided ETF payload is incorrectly formatted or an I/O error occurred
*
* @return A DataArray instance for the provided payload
*
* @since 4.2.1
*/
@Nonnull
public static DataArray fromETF(@Nonnull byte[] data)
{
Checks.notNull(data, "Data");
try
{
List<Object> list = ExTermDecoder.unpackList(ByteBuffer.wrap(data));
return new DataArray(list);
}
catch (Exception ex)
{
log.error("Failed to parse ETF data {}", Arrays.toString(data), ex);
throw new ParsingException(ex);
}
}
/**
* Whether the value at the specified index is null.
*
* @param index
* The index to check
*
* @return True, if the value at the index is null
*/
public boolean isNull(int index)
{
return data.get(index) == null;
}
/**
* Whether the value at the specified index is of the specified type.
*
* @param index
* The index to check
* @param type
* The type to check
*
* @return True, if the type check is successful
*
* @see net.dv8tion.jda.api.utils.data.DataType#isType(Object) DataType.isType(Object)
*/
public boolean isType(int index, @Nonnull DataType type)
{
return type.isType(data.get(index));
}
/**
* The length of the array.
*
* @return The length of the array
*/
public int length()
{
return data.size();
}
/**
* Whether this array is empty
*
* @return True, if this array is empty
*/
public boolean isEmpty()
{
return data.isEmpty();
}
/**
* Resolves the value at the specified index to a DataObject
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type or missing
*
* @return The resolved DataObject
*/
@Nonnull
@SuppressWarnings("unchecked")
public DataObject getObject(int index)
{
Map<String, Object> child = null;
try
{
child = (Map<String, Object>) get(Map.class, index);
}
catch (ClassCastException ex)
{
log.error("Unable to extract child data", ex);
}
if (child == null)
throw valueError(index, "DataObject");
return new DataObject(child);
}
/**
* Resolves the value at the specified index to a DataArray
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type or null
*
* @return The resolved DataArray
*/
@Nonnull
@SuppressWarnings("unchecked")
public DataArray getArray(int index)
{
List<Object> child = null;
try
{
child = (List<Object>) get(List.class, index);
}
catch (ClassCastException ex)
{
log.error("Unable to extract child data", ex);
}
if (child == null)
throw valueError(index, "DataArray");
return new DataArray(child);
}
/**
* Resolves the value at the specified index to a String.
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type or null
*
* @return The resolved String
*/
@Nonnull
public String getString(int index)
{
String value = get(String.class, index, UnaryOperator.identity(), String::valueOf);
if (value == null)
throw valueError(index, "String");
return value;
}
/**
* Resolves the value at the specified index to a String.
*
* @param index
* The index to resolve
* @param defaultValue
* Alternative value to use when the value associated with the index is null
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved String
*/
@Contract("_, !null -> !null")
public String getString(int index, @Nullable String defaultValue)
{
String value = get(String.class, index, UnaryOperator.identity(), String::valueOf);
return value == null ? defaultValue : value;
}
/**
* Resolves the value at the specified index to a boolean.
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return True, if the value is present and set to true. Otherwise false.
*/
public boolean getBoolean(int index)
{
return getBoolean(index, false);
}
/**
* Resolves the value at the specified index to a boolean.
*
* @param index
* The index to resolve
* @param defaultValue
* Alternative value to use when the value associated with the index is null
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return True, if the value is present and set to true. False, if it is set to false. Otherwise defaultValue.
*/
public boolean getBoolean(int index, boolean defaultValue)
{
Boolean value = get(Boolean.class, index, Boolean::parseBoolean, null);
return value == null ? defaultValue : value;
}
/**
* Resolves the value at the specified index to an int.
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved int value
*/
public int getInt(int index)
{
Integer value = get(Integer.class, index, Integer::parseInt, Number::intValue);
if (value == null)
throw valueError(index, "int");
return value;
}
/**
* Resolves the value at the specified index to an int.
*
* @param index
* The index to resolve
* @param defaultValue
* Alternative value to use when the value associated with the index is null
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved int value
*/
public int getInt(int index, int defaultValue)
{
Integer value = get(Integer.class, index, Integer::parseInt, Number::intValue);
return value == null ? defaultValue : value;
}
/**
* Resolves the value at the specified index to an unsigned int.
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved unsigned int value
*/
public int getUnsignedInt(int index)
{
Integer value = get(Integer.class, index, Integer::parseUnsignedInt, Number::intValue);
if (value == null)
throw valueError(index, "unsigned int");
return value;
}
/**
* Resolves the value at the specified index to an unsigned int.
*
* @param index
* The index to resolve
* @param defaultValue
* Alternative value to use when the value associated with the index is null
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved unsigned int value
*/
public int getUnsignedInt(int index, int defaultValue)
{
Integer value = get(Integer.class, index, Integer::parseUnsignedInt, Number::intValue);
return value == null ? defaultValue : value;
}
/**
* Resolves the value at the specified index to a long.
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved long value
*/
public long getLong(int index)
{
Long value = get(Long.class, index, Long::parseLong, Number::longValue);
if (value == null)
throw valueError(index, "long");
return value;
}
/**
* Resolves the value at the specified index to a long.
*
* @param index
* The index to resolve
* @param defaultValue
* Alternative value to use when the value associated with the index is null
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved long value
*/
public long getLong(int index, long defaultValue)
{
Long value = get(Long.class, index, Long::parseLong, Number::longValue);
return value == null ? defaultValue : value;
}
/**
* Resolves the value at the specified index to an unsigned long.
*
* @param index
* The index to resolve
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved unsigned long value
*/
public long getUnsignedLong(int index)
{
Long value = get(Long.class, index, Long::parseUnsignedLong, Number::longValue);
if (value == null)
throw valueError(index, "unsigned long");
return value;
}
/**
* Resolves the value at the specified index to an unsigned long.
*
* @param index
* The index to resolve
* @param defaultValue
* Alternative value to use when the value associated with the index is null
*
* @throws net.dv8tion.jda.api.exceptions.ParsingException
* If the value is of the wrong type
*
* @return The resolved unsigned long value
*/
public long getUnsignedLong(int index, long defaultValue)
{
Long value = get(Long.class, index, Long::parseUnsignedLong, Number::longValue);
return value == null ? defaultValue : value;
}
/**
* Appends the provided value to the end of the array.
*
* @param value
* The value to append
*
* @return A DataArray with the value inserted at the end
*/
@Nonnull
public DataArray add(@Nullable Object value)
{
if (value instanceof SerializableData)
data.add(((SerializableData) value).toData().data);
else if (value instanceof SerializableArray)
data.add(((SerializableArray) value).toDataArray().data);
else
data.add(value);
return this;
}
/**
* Appends the provided values to the end of the array.
*
* @param values
* The values to append
*
* @return A DataArray with the values inserted at the end
*/
@Nonnull
public DataArray addAll(@Nonnull Collection<?> values)
{
values.forEach(this::add);
return this;
}
/**
* Appends the provided values to the end of the array.
*
* @param array
* The values to append
*
* @return A DataArray with the values inserted at the end
*/
@Nonnull
public DataArray addAll(@Nonnull DataArray array)
{
return addAll(array.data);
}
/**
* Inserts the specified value at the provided index.
*
* @param index
* The target index
* @param value
* The value to insert
*
* @return A DataArray with the value inserted at the specified index
*/
@Nonnull
public DataArray insert(int index, @Nullable Object value)
{
if (value instanceof SerializableData)
data.add(index, ((SerializableData) value).toData().data);
else if (value instanceof SerializableArray)
data.add(index, ((SerializableArray) value).toDataArray().data);
else
data.add(index, value);
return this;
}
/**
* Removes the value at the specified index.
*
* @param index
* The target index to remove
*
* @return A DataArray with the value removed
*/
@Nonnull
public DataArray remove(int index)
{
data.remove(index);
return this;
}
/**
* Removes the specified value.
*
* @param value
* The value to remove
*
* @return A DataArray with the value removed
*/
@Nonnull
public DataArray remove(@Nullable Object value)
{
data.remove(value);
return this;
}
/**
* Serializes this object as JSON.
*
* @return byte array containing the JSON representation of this object
*/
@Nonnull
public byte[] toJson()
{
try
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mapper.writeValue(outputStream, data);
return outputStream.toByteArray();
}
catch (IOException e)
{
throw new UncheckedIOException(e);
}
}
/**
* Serializes this object as ETF LIST term.
*
* @return byte array containing the encoded ETF term
*
* @since 4.2.1
*/
@Nonnull
public byte[] toETF()
{
ByteBuffer buffer = ExTermEncoder.pack(data);
return Arrays.copyOfRange(buffer.array(), buffer.arrayOffset(), buffer.arrayOffset() + buffer.limit());
}
@Override
public String toString()
{
try
{
return mapper.writeValueAsString(data);
}
catch (JsonProcessingException e)
{
throw new ParsingException(e);
}
}
@Nonnull
public String toPrettyString()
{
DefaultPrettyPrinter.Indenter indent = new DefaultIndenter(" ", DefaultIndenter.SYS_LF);
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.withObjectIndenter(indent).withArrayIndenter(indent);
try
{
return mapper.writer(printer).writeValueAsString(data);
}
catch (JsonProcessingException e)
{
throw new ParsingException(e);
}
}
/**
* Converts this DataArray to a {@link java.util.List}.
*
* @return The resulting list
*/
@Nonnull
public List<Object> toList()
{
return data;
}
private ParsingException valueError(int index, String expectedType)
{
return new ParsingException("Unable to resolve value at " + index + " to type " + expectedType + ": " + data.get(index));
}
@Nullable
private <T> T get(@Nonnull Class<T> type, int index)
{
return get(type, index, null, null);
}
@Nullable
private <T> T get(@Nonnull Class<T> type, int index, @Nullable Function<String, T> stringMapper, @Nullable Function<Number, T> numberMapper)
{
Object value = data.get(index);
if (value == null)
return null;
if (type.isInstance(value))
return type.cast(value);
if (type == String.class)
return type.cast(value.toString());
// attempt type coercion
if (stringMapper != null && value instanceof String)
return stringMapper.apply((String) value);
else if (numberMapper != null && value instanceof Number)
return numberMapper.apply((Number) value);
throw new ParsingException(Helpers.format("Cannot parse value for index %d into type %s: %s instance of %s",
index, type.getSimpleName(), value, value.getClass().getSimpleName()));
}
@Nonnull
@Override
public Iterator<Object> iterator()
{
return data.iterator();
}
@Nonnull
public <T> Stream<T> stream(BiFunction<? super DataArray, Integer, ? extends T> mapper)
{
return IntStream.range(0, length())
.mapToObj(index -> mapper.apply(this, index));
}
@Nonnull
@Override
public DataArray toDataArray()
{
return this;
}
}