/
Helpers.java
319 lines (283 loc) · 9.41 KB
/
Helpers.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
/*
* 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.internal.utils;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.map.hash.TLongObjectHashMap;
import net.dv8tion.jda.api.entities.channel.Channel;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import javax.annotation.Nullable;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.ToLongFunction;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* This class has major inspiration from <a href="https://commons.apache.org/proper/commons-lang/" target="_blank">Lang 3</a>
*
* <p>Specifically StringUtils.java and ExceptionUtils.java
*/
public final class Helpers
{
private static final ZoneOffset OFFSET = ZoneOffset.of("+00:00");
@SuppressWarnings("rawtypes")
private static final Consumer EMPTY_CONSUMER = (v) -> {};
@SuppressWarnings("unchecked")
public static <T> Consumer<T> emptyConsumer()
{
return (Consumer<T>) EMPTY_CONSUMER;
}
public static <T extends Channel> T safeChannelCast(Object instance, Class<T> toObjectClass)
{
if (toObjectClass.isInstance(instance))
return toObjectClass.cast(instance);
String cleanedClassName = instance.getClass().getSimpleName().replace("Impl", "");
throw new IllegalStateException(Helpers.format("Cannot convert channel of type %s to %s!", cleanedClassName, toObjectClass.getSimpleName()));
}
public static OffsetDateTime toOffset(long instant)
{
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(instant), OFFSET);
}
public static long toTimestamp(String iso8601String)
{
TemporalAccessor joinedAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(iso8601String);
return Instant.from(joinedAt).toEpochMilli();
}
public static OffsetDateTime toOffsetDateTime(@Nullable TemporalAccessor temporal)
{
if (temporal == null)
{
return null;
}
else if (temporal instanceof OffsetDateTime)
{
return (OffsetDateTime) temporal;
}
else
{
ZoneOffset offset;
try
{
offset = ZoneOffset.from(temporal);
}
catch (DateTimeException ignore)
{
offset = ZoneOffset.UTC;
}
try
{
LocalDateTime ldt = LocalDateTime.from(temporal);
return OffsetDateTime.of(ldt, offset);
}
catch (DateTimeException ignore)
{
try
{
Instant instant = Instant.from(temporal);
return OffsetDateTime.ofInstant(instant, offset);
}
catch (DateTimeException ex)
{
throw new DateTimeException("Unable to obtain OffsetDateTime from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName(), ex);
}
}
}
}
// locale-safe String#format
public static String format(String format, Object... args)
{
return String.format(Locale.ROOT, format, args);
}
// ## StringUtils ##
public static boolean isEmpty(final CharSequence seq)
{
return seq == null || seq.length() == 0;
}
public static boolean containsWhitespace(final CharSequence seq)
{
if (isEmpty(seq))
return false;
for (int i = 0; i < seq.length(); i++)
{
if (Character.isWhitespace(seq.charAt(i)))
return true;
}
return false;
}
public static boolean isBlank(final CharSequence seq)
{
if (isEmpty(seq))
return true;
for (int i = 0; i < seq.length(); i++)
{
if (!Character.isWhitespace(seq.charAt(i)))
return false;
}
return true;
}
public static int countMatches(final CharSequence seq, final char c)
{
if (isEmpty(seq))
return 0;
int count = 0;
for (int i = 0; i < seq.length(); i++)
{
if (seq.charAt(i) == c)
count++;
}
return count;
}
public static String truncate(final String input, final int maxWidth)
{
if (input == null)
return null;
Checks.notNegative(maxWidth, "maxWidth");
if (input.length() <= maxWidth)
return input;
if (maxWidth == 0)
return "";
return input.substring(0, maxWidth);
}
public static String rightPad(final String input, final int size)
{
int pads = size - input.length();
if (pads <= 0)
return input;
StringBuilder out = new StringBuilder(input);
for (int i = pads; i > 0; i--)
out.append(' ');
return out.toString();
}
public static String leftPad(final String input, final int size)
{
int pads = size - input.length();
if (pads <= 0)
return input;
StringBuilder out = new StringBuilder();
for (int i = pads; i > 0; i--)
out.append(' ');
return out.append(input).toString();
}
public static boolean isNumeric(final String input)
{
if (isEmpty(input))
return false;
for (char c : input.toCharArray())
{
if (!Character.isDigit(c))
return false;
}
return true;
}
public static int codePointLength(final CharSequence string)
{
return (int) string.codePoints().count();
}
public static String[] split(String input, String match)
{
List<String> out = new ArrayList<>();
int i = 0;
while (i < input.length())
{
int j = input.indexOf(match, i);
if (j == -1)
{
out.add(input.substring(i));
break;
}
out.add(input.substring(i, j));
i = j + match.length();
}
return out.toArray(new String[0]);
}
// ## CollectionUtils ##
public static boolean deepEquals(Collection<?> first, Collection<?> second)
{
if (first == second)
return true;
if (first == null || second == null || first.size() != second.size())
return false;
for (Iterator<?> itFirst = first.iterator(), itSecond = second.iterator(); itFirst.hasNext(); )
{
Object elementFirst = itFirst.next();
Object elementSecond = itSecond.next();
if (!Objects.equals(elementFirst, elementSecond))
return false;
}
return true;
}
public static boolean deepEqualsUnordered(Collection<?> first, Collection<?> second)
{
if (first == second) return true;
if (first == null || second == null) return false;
return first.size() == second.size() && second.containsAll(first);
}
public static <E extends Enum<E>> EnumSet<E> copyEnumSet(Class<E> clazz, Collection<E> col)
{
return col == null || col.isEmpty() ? EnumSet.noneOf(clazz) : EnumSet.copyOf(col);
}
@SafeVarargs
public static <T> Set<T> setOf(T... elements)
{
Set<T> set = new HashSet<>(elements.length);
Collections.addAll(set, elements);
return set;
}
@SafeVarargs
public static <T> List<T> listOf(T... elements)
{
return Collections.unmodifiableList(Arrays.asList(elements));
}
public static TLongObjectMap<DataObject> convertToMap(ToLongFunction<DataObject> getId, DataArray array)
{
TLongObjectMap<DataObject> map = new TLongObjectHashMap<>();
for (int i = 0; i < array.length(); i++)
{
DataObject obj = array.getObject(i);
long objId = getId.applyAsLong(obj);
map.put(objId, obj);
}
return map;
}
// ## ExceptionUtils ##
public static <T extends Throwable> T appendCause(T throwable, Throwable cause)
{
Throwable t = throwable;
while (t.getCause() != null)
t = t.getCause();
t.initCause(cause);
return throwable;
}
public static boolean hasCause(Throwable throwable, Class<? extends Throwable> cause)
{
Throwable cursor = throwable;
while (cursor != null)
{
if (cause.isInstance(cursor))
return true;
cursor = cursor.getCause();
}
return false;
}
public static <T> Collector<T, ?, List<T>> toUnmodifiableList()
{
return Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList);
}
}