-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathUtils.java
445 lines (392 loc) · 14.2 KB
/
Utils.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
// Copyright (c) 2020-2021 VMware, Inc. or its affiliates. All rights reserved.
//
// This software, the RabbitMQ Stream Java client library, is dual-licensed under the
// Mozilla Public License 2.0 ("MPL"), and the Apache License version 2 ("ASL").
// For the MPL, please see LICENSE-MPL-RabbitMQ. For the ASL,
// please see LICENSE-APACHE2.
//
// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
// either express or implied. See the LICENSE file for specific language governing
// rights and limitations of this software.
//
// If you have any questions regarding licensing, please contact us at
package com.rabbitmq.stream.perf;
import com.rabbitmq.stream.ByteCapacity;
import com.rabbitmq.stream.OffsetSpecification;
import com.rabbitmq.stream.StreamCreator.LeaderLocator;
import com.rabbitmq.stream.compression.Compression;
import java.security.cert.X509Certificate;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import picocli.CommandLine.ITypeConverter;
class Utils {
static final X509TrustManager TRUST_EVERYTHING_TRUST_MANAGER = new TrustEverythingTrustManager();
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
private static final String RANGE_SEPARATOR_1 = "-";
private static final String RANGE_SEPARATOR_2 = "..";
static void writeLong(byte[] array, long value) {
// from Guava Longs
for (int i = 7; i >= 0; i--) {
array[i] = (byte) (value & 0xffL);
value >>= 8;
}
}
static long readLong(byte[] array) {
// from Guava Longs
return (array[0] & 0xFFL) << 56
| (array[1] & 0xFFL) << 48
| (array[2] & 0xFFL) << 40
| (array[3] & 0xFFL) << 32
| (array[4] & 0xFFL) << 24
| (array[5] & 0xFFL) << 16
| (array[6] & 0xFFL) << 8
| (array[7] & 0xFFL);
}
static List<String> streams(String range, List<String> streams) {
if (range.contains(RANGE_SEPARATOR_2)) {
range = range.replace(RANGE_SEPARATOR_2, RANGE_SEPARATOR_1);
}
int from, to;
if (range.contains(RANGE_SEPARATOR_1)) {
String[] fromTo = range.split(RANGE_SEPARATOR_1);
from = Integer.parseInt(fromTo[0]);
to = Integer.parseInt(fromTo[1]) + 1;
} else {
int count = Integer.parseInt(range);
from = 1;
to = count + 1;
}
if (from == 1 && to == 2) {
return streams;
} else {
if (streams.size() != 1) {
throw new IllegalArgumentException("Enter only 1 stream when --stream-count is specified");
}
String format = streams.get(0);
String streamFormat;
if (!format.contains("%")) {
int digits = String.valueOf(to - 1).length();
streamFormat = format + "-%0" + digits + "d";
} else {
streamFormat = format;
}
return IntStream.range(from, to)
.mapToObj(i -> String.format(streamFormat, i))
.collect(Collectors.toList());
}
}
static String formatByte(double bytes) {
// based on
// https://stackoverflow.com/questions/3758606/how-can-i-convert-byte-size-into-a-human-readable-format-in-java
if (-1000 < bytes && bytes < 1000) {
return String.valueOf(bytes);
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}
static long physicalMemory() {
try {
com.sun.management.OperatingSystemMXBean os =
(com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
return os.getTotalPhysicalMemorySize();
} catch (Throwable e) {
// we can get NoClassDefFoundError, so we catch from Throwable and below
LOGGER.warn("Could not get physical memory", e);
return 0;
}
}
private static void throwConversionException(String format, String... arguments) {
throw new CommandLine.TypeConversionException(String.format(format, (Object[]) arguments));
}
static class ByteCapacityTypeConverter implements CommandLine.ITypeConverter<ByteCapacity> {
@Override
public ByteCapacity convert(String value) {
try {
return ByteCapacity.from(value);
} catch (IllegalArgumentException e) {
throw new CommandLine.TypeConversionException(
"'" + value + "' is not valid, valid example values: 100gb, 50mb");
}
}
}
static class NameStrategyConverter
implements CommandLine.ITypeConverter<BiFunction<String, Integer, String>> {
@Override
public BiFunction<String, Integer, String> convert(String input) {
if ("uuid".equals(input)) {
return (stream, index) -> UUID.randomUUID().toString();
} else {
return new PatternNameStrategy(input);
}
}
}
static class SniServerNamesConverter implements ITypeConverter<List<SNIServerName>> {
@Override
public List<SNIServerName> convert(String value) throws Exception {
if (value == null || value.trim().isEmpty()) {
return Collections.emptyList();
} else {
return Arrays.stream(value.split(","))
.map(s -> s.trim())
.map(s -> new SNIHostName(s))
.collect(Collectors.toList());
}
}
}
static class RangeTypeConverter implements CommandLine.ITypeConverter<String> {
@Override
public String convert(String input) {
String value;
if (input.contains(RANGE_SEPARATOR_2)) {
value = input.replace(RANGE_SEPARATOR_2, RANGE_SEPARATOR_1);
} else {
value = input;
}
if (value.contains(RANGE_SEPARATOR_1)) {
String[] fromTo = value.split(RANGE_SEPARATOR_1);
if (fromTo == null || fromTo.length != 2) {
throwConversionException("'%s' is not valid, valid examples values: 10, 1-10", input);
}
Arrays.stream(fromTo)
.forEach(
v -> {
try {
int i = Integer.parseInt(v);
if (i <= 0) {
throwConversionException(
"'%s' is not valid, the value must be a positive integer", v);
}
} catch (NumberFormatException e) {
throwConversionException(
"'%s' is not valid, the value must be a positive integer", v);
}
});
int from = Integer.parseInt(fromTo[0]);
int to = Integer.parseInt(fromTo[1]);
if (from >= to) {
throwConversionException("'%s' is not valid, valid examples values: 10, 1-10", input);
}
} else {
try {
int count = Integer.parseInt(value);
if (count <= 0) {
throwConversionException(
"'%s' is not valid, the value must be a positive integer", input);
}
} catch (NumberFormatException e) {
throwConversionException("'%s' is not valid, valid example values: 10, 1-10", input);
}
}
return input;
}
}
static class DurationTypeConverter implements CommandLine.ITypeConverter<Duration> {
@Override
public Duration convert(String value) {
try {
Duration duration = Duration.parse(value);
if (duration.isNegative() || duration.isZero()) {
throw new CommandLine.TypeConversionException(
"'" + value + "' is not valid, it must be positive");
}
return duration;
} catch (DateTimeParseException e) {
throw new CommandLine.TypeConversionException(
"'" + value + "' is not valid, valid example values: PT15M, PT10H");
}
}
}
static class LeaderLocatorTypeConverter implements CommandLine.ITypeConverter<LeaderLocator> {
@Override
public LeaderLocator convert(String value) {
try {
return LeaderLocator.from(value);
} catch (Exception e) {
throw new CommandLine.TypeConversionException(
"'"
+ value
+ "' is not valid, possible values: "
+ Arrays.stream(LeaderLocator.values())
.map(ll -> ll.value())
.collect(Collectors.joining(", ")));
}
}
}
static class OffsetSpecificationTypeConverter
implements CommandLine.ITypeConverter<OffsetSpecification> {
private static final Map<String, OffsetSpecification> SPECS =
Collections.unmodifiableMap(
new HashMap<String, OffsetSpecification>() {
{
put("first", OffsetSpecification.first());
put("last", OffsetSpecification.last());
put("next", OffsetSpecification.next());
}
});
@Override
public OffsetSpecification convert(String value) throws Exception {
if (value == null || value.trim().isEmpty()) {
return OffsetSpecification.first();
}
if (SPECS.containsKey(value.toLowerCase())) {
return SPECS.get(value.toLowerCase());
}
try {
long offset = Long.parseUnsignedLong(value);
return OffsetSpecification.offset(offset);
} catch (NumberFormatException e) {
// trying next
}
try {
TemporalAccessor accessor = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(value);
return OffsetSpecification.timestamp(Instant.from(accessor).toEpochMilli());
} catch (DateTimeParseException e) {
throw new CommandLine.TypeConversionException(
"'"
+ value
+ "' is not a valid offset value, valid values are 'first', 'last', 'next', "
+ "an unsigned long, or an ISO 8601 formatted timestamp (eg. 2020-06-03T07:45:54Z)");
}
}
}
static class PositiveIntegerTypeConverter implements CommandLine.ITypeConverter<Integer> {
@Override
public Integer convert(String input) {
try {
Integer value = Integer.valueOf(input);
if (value <= 0) {
throw new IllegalArgumentException();
}
return value;
} catch (Exception e) {
throw new CommandLine.TypeConversionException(input + " is not a positive integer");
}
}
}
static class CompressionTypeConverter implements CommandLine.ITypeConverter<Compression> {
@Override
public Compression convert(String input) {
try {
return Compression.valueOf(input.toUpperCase(Locale.ENGLISH));
} catch (Exception e) {
throw new CommandLine.TypeConversionException(
input
+ " is not a valid compression value. "
+ "Accepted values are "
+ Arrays.stream(Compression.values())
.map(Compression::name)
.map(String::toLowerCase)
.collect(Collectors.joining(", "))
+ ".");
}
}
}
private abstract static class RangeIntegerTypeConverter
implements CommandLine.ITypeConverter<Integer> {
private final int min, max;
private RangeIntegerTypeConverter(int min, int max) {
this.min = min;
this.max = max;
}
@Override
public Integer convert(String input) {
try {
Integer value = Integer.valueOf(input);
if (value < this.min || value > this.max) {
throw new IllegalArgumentException();
}
return value;
} catch (Exception e) {
throw new CommandLine.TypeConversionException(
input + " must an integer between " + this.min + " and " + this.max);
}
}
}
static class OneTo255RangeIntegerTypeConverter extends RangeIntegerTypeConverter {
OneTo255RangeIntegerTypeConverter() {
super(1, 255);
}
}
static class NotNegativeIntegerTypeConverter implements CommandLine.ITypeConverter<Integer> {
@Override
public Integer convert(String input) {
try {
Integer value = Integer.valueOf(input);
if (value < 0) {
throw new IllegalArgumentException();
}
return value;
} catch (Exception e) {
throw new CommandLine.TypeConversionException(input + " is not a non-negative integer");
}
}
}
static class NamedThreadFactory implements ThreadFactory {
private final ThreadFactory backingThreaFactory;
private final String prefix;
private final AtomicLong count = new AtomicLong(0);
public NamedThreadFactory(String prefix) {
this(Executors.defaultThreadFactory(), prefix);
}
public NamedThreadFactory(ThreadFactory backingThreaFactory, String prefix) {
this.backingThreaFactory = backingThreaFactory;
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = this.backingThreaFactory.newThread(r);
thread.setName(prefix + count.getAndIncrement());
return thread;
}
}
private static class TrustEverythingTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
static final class PatternNameStrategy implements BiFunction<String, Integer, String> {
private final String pattern;
PatternNameStrategy(String pattern) {
this.pattern = pattern;
}
@Override
public String apply(String stream, Integer index) {
return String.format(pattern, stream, index);
}
}
}