-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
LettuceConverters.java
1113 lines (918 loc) · 34.6 KB
/
LettuceConverters.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 2013-2019 the original author or authors.
*
* 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
*
* https://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 org.springframework.data.redis.connection.lettuce;
import io.lettuce.core.*;
import io.lettuce.core.cluster.models.partitions.Partitions;
import io.lettuce.core.cluster.models.partitions.RedisClusterNode.NodeFlag;
import io.lettuce.core.protocol.LettuceCharsets;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.core.convert.converter.Converter;
import org.springframework.dao.DataAccessException;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.BitFieldSubCommands.BitFieldGet;
import org.springframework.data.redis.connection.BitFieldSubCommands.BitFieldIncrBy;
import org.springframework.data.redis.connection.BitFieldSubCommands.BitFieldIncrBy.Overflow;
import org.springframework.data.redis.connection.BitFieldSubCommands.BitFieldSet;
import org.springframework.data.redis.connection.BitFieldSubCommands.BitFieldSubCommand;
import org.springframework.data.redis.connection.DefaultTuple;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisClusterNode.Flag;
import org.springframework.data.redis.connection.RedisClusterNode.LinkState;
import org.springframework.data.redis.connection.RedisClusterNode.SlotRange;
import org.springframework.data.redis.connection.RedisGeoCommands.DistanceUnit;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoLocation;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoRadiusCommandArgs;
import org.springframework.data.redis.connection.RedisListCommands.Position;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisNode.NodeType;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisServer;
import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
import org.springframework.data.redis.connection.RedisZSetCommands;
import org.springframework.data.redis.connection.RedisZSetCommands.Range.Boundary;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.connection.convert.Converters;
import org.springframework.data.redis.connection.convert.ListConverter;
import org.springframework.data.redis.connection.convert.LongToBooleanConverter;
import org.springframework.data.redis.connection.convert.StringToRedisClientInfoConverter;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.core.types.RedisClientInfo;
import org.springframework.data.redis.util.ByteUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Lettuce type converters
*
* @author Jennifer Hickey
* @author Christoph Strobl
* @author Thomas Darimont
* @author Mark Paluch
* @author Ninad Divadkar
*/
abstract public class LettuceConverters extends Converters {
private static final Converter<Date, Long> DATE_TO_LONG;
private static final Converter<List<byte[]>, Set<byte[]>> BYTES_LIST_TO_BYTES_SET;
private static final Converter<byte[], String> BYTES_TO_STRING;
private static final Converter<String, byte[]> STRING_TO_BYTES;
private static final Converter<Set<byte[]>, List<byte[]>> BYTES_SET_TO_BYTES_LIST;
private static final Converter<Collection<byte[]>, List<byte[]>> BYTES_COLLECTION_TO_BYTES_LIST;
private static final Converter<KeyValue<byte[], byte[]>, List<byte[]>> KEY_VALUE_TO_BYTES_LIST;
private static final Converter<List<ScoredValue<byte[]>>, Set<Tuple>> SCORED_VALUES_TO_TUPLE_SET;
private static final Converter<List<ScoredValue<byte[]>>, List<Tuple>> SCORED_VALUES_TO_TUPLE_LIST;
private static final Converter<ScoredValue<byte[]>, Tuple> SCORED_VALUE_TO_TUPLE;
private static final Converter<Exception, DataAccessException> EXCEPTION_CONVERTER = new LettuceExceptionConverter();
private static final Converter<Long, Boolean> LONG_TO_BOOLEAN = new LongToBooleanConverter();
private static final Converter<List<byte[]>, Map<byte[], byte[]>> BYTES_LIST_TO_MAP;
private static final Converter<List<byte[]>, List<Tuple>> BYTES_LIST_TO_TUPLE_LIST_CONVERTER;
private static final Converter<String[], List<RedisClientInfo>> STRING_TO_LIST_OF_CLIENT_INFO = new StringToRedisClientInfoConverter();
private static final Converter<Partitions, List<RedisClusterNode>> PARTITIONS_TO_CLUSTER_NODES;
private static Converter<io.lettuce.core.cluster.models.partitions.RedisClusterNode, RedisClusterNode> CLUSTER_NODE_TO_CLUSTER_NODE_CONVERTER;
private static final Converter<List<byte[]>, Long> BYTES_LIST_TO_TIME_CONVERTER;
private static final Converter<GeoCoordinates, Point> GEO_COORDINATE_TO_POINT_CONVERTER;
private static final ListConverter<GeoCoordinates, Point> GEO_COORDINATE_LIST_TO_POINT_LIST_CONVERTER;
private static final Converter<KeyValue<Object, Object>, Object> KEY_VALUE_UNWRAPPER;
private static final ListConverter<KeyValue<Object, Object>, Object> KEY_VALUE_LIST_UNWRAPPER;
private static final Converter<TransactionResult, List<Object>> TRANSACTION_RESULT_UNWRAPPER;
public static final byte[] PLUS_BYTES;
public static final byte[] MINUS_BYTES;
public static final byte[] POSITIVE_INFINITY_BYTES;
public static final byte[] NEGATIVE_INFINITY_BYTES;
private static final long INDEXED_RANGE_START = 0;
private static final long INDEXED_RANGE_END = -1;
static {
DATE_TO_LONG = source -> source != null ? source.getTime() : null;
BYTES_LIST_TO_BYTES_SET = results -> results != null ? new LinkedHashSet<>(results) : null;
BYTES_TO_STRING = source -> {
if (source == null || Arrays.equals(source, new byte[0])) {
return null;
}
return new String(source);
};
STRING_TO_BYTES = source -> {
if (source == null) {
return null;
}
return source.getBytes();
};
BYTES_SET_TO_BYTES_LIST = results -> results != null ? new ArrayList<>(results) : null;
BYTES_COLLECTION_TO_BYTES_LIST = results -> {
if (results instanceof List) {
return (List<byte[]>) results;
}
return results != null ? new ArrayList<>(results) : null;
};
KEY_VALUE_TO_BYTES_LIST = source -> {
if (source == null) {
return null;
}
List<byte[]> list = new ArrayList<>(2);
list.add(source.getKey());
list.add(source.getValue());
return list;
};
BYTES_LIST_TO_MAP = source -> {
if (CollectionUtils.isEmpty(source)) {
return Collections.emptyMap();
}
Map<byte[], byte[]> target = new LinkedHashMap<>();
Iterator<byte[]> kv = source.iterator();
while (kv.hasNext()) {
target.put(kv.next(), kv.hasNext() ? kv.next() : null);
}
return target;
};
SCORED_VALUES_TO_TUPLE_SET = source -> {
if (source == null) {
return null;
}
Set<Tuple> tuples = new LinkedHashSet<>(source.size());
for (ScoredValue<byte[]> value : source) {
tuples.add(LettuceConverters.toTuple(value));
}
return tuples;
};
SCORED_VALUES_TO_TUPLE_LIST = source -> {
if (source == null) {
return null;
}
List<Tuple> tuples = new ArrayList<>(source.size());
for (ScoredValue<byte[]> value : source) {
tuples.add(LettuceConverters.toTuple(value));
}
return tuples;
};
SCORED_VALUE_TO_TUPLE = source -> source != null
? new DefaultTuple(source.getValue(), Double.valueOf(source.getScore()))
: null;
BYTES_LIST_TO_TUPLE_LIST_CONVERTER = source -> {
if (CollectionUtils.isEmpty(source)) {
return Collections.emptyList();
}
List<Tuple> tuples = new ArrayList<>();
Iterator<byte[]> it = source.iterator();
while (it.hasNext()) {
tuples.add(new DefaultTuple(it.next(), it.hasNext() ? Double.valueOf(toString(it.next())) : null));
}
return tuples;
};
PARTITIONS_TO_CLUSTER_NODES = new Converter<Partitions, List<RedisClusterNode>>() {
@Override
public List<RedisClusterNode> convert(Partitions source) {
if (source == null) {
return Collections.emptyList();
}
List<RedisClusterNode> nodes = new ArrayList<>();
for (io.lettuce.core.cluster.models.partitions.RedisClusterNode node : source) {
nodes.add(CLUSTER_NODE_TO_CLUSTER_NODE_CONVERTER.convert(node));
}
return nodes;
};
};
CLUSTER_NODE_TO_CLUSTER_NODE_CONVERTER = new Converter<io.lettuce.core.cluster.models.partitions.RedisClusterNode, RedisClusterNode>() {
@Override
public RedisClusterNode convert(io.lettuce.core.cluster.models.partitions.RedisClusterNode source) {
Set<Flag> flags = parseFlags(source.getFlags());
return RedisClusterNode.newRedisClusterNode().listeningAt(source.getUri().getHost(), source.getUri().getPort())
.withId(source.getNodeId()).promotedAs(flags.contains(Flag.MASTER) ? NodeType.MASTER : NodeType.SLAVE)
.serving(new SlotRange(source.getSlots())).withFlags(flags)
.linkState(source.isConnected() ? LinkState.CONNECTED : LinkState.DISCONNECTED).slaveOf(source.getSlaveOf())
.build();
}
private Set<Flag> parseFlags(Set<NodeFlag> source) {
Set<Flag> flags = new LinkedHashSet<>(source != null ? source.size() : 8, 1);
for (NodeFlag flag : source) {
switch (flag) {
case NOFLAGS:
flags.add(Flag.NOFLAGS);
break;
case EVENTUAL_FAIL:
flags.add(Flag.PFAIL);
break;
case FAIL:
flags.add(Flag.FAIL);
break;
case HANDSHAKE:
flags.add(Flag.HANDSHAKE);
break;
case MASTER:
flags.add(Flag.MASTER);
break;
case MYSELF:
flags.add(Flag.MYSELF);
break;
case NOADDR:
flags.add(Flag.NOADDR);
break;
case SLAVE:
flags.add(Flag.SLAVE);
break;
}
}
return flags;
}
};
PLUS_BYTES = toBytes("+");
MINUS_BYTES = toBytes("-");
POSITIVE_INFINITY_BYTES = toBytes("+inf");
NEGATIVE_INFINITY_BYTES = toBytes("-inf");
BYTES_LIST_TO_TIME_CONVERTER = source -> {
Assert.notEmpty(source, "Received invalid result from server. Expected 2 items in collection.");
Assert.isTrue(source.size() == 2,
"Received invalid nr of arguments from redis server. Expected 2 received " + source.size());
return toTimeMillis(toString(source.get(0)), toString(source.get(1)));
};
GEO_COORDINATE_TO_POINT_CONVERTER = geoCoordinate -> geoCoordinate != null
? new Point(geoCoordinate.getX().doubleValue(), geoCoordinate.getY().doubleValue())
: null;
GEO_COORDINATE_LIST_TO_POINT_LIST_CONVERTER = new ListConverter<>(GEO_COORDINATE_TO_POINT_CONVERTER);
KEY_VALUE_UNWRAPPER = source -> source.getValueOrElse(null);
KEY_VALUE_LIST_UNWRAPPER = new ListConverter<>(KEY_VALUE_UNWRAPPER);
TRANSACTION_RESULT_UNWRAPPER = transactionResult -> transactionResult.stream().collect(Collectors.toList());
}
public static List<Tuple> toTuple(List<byte[]> list) {
return BYTES_LIST_TO_TUPLE_LIST_CONVERTER.convert(list);
}
public static Converter<List<byte[]>, List<Tuple>> bytesListToTupleListConverter() {
return BYTES_LIST_TO_TUPLE_LIST_CONVERTER;
}
public static Point geoCoordinatesToPoint(GeoCoordinates geoCoordinates) {
return GEO_COORDINATE_TO_POINT_CONVERTER.convert(geoCoordinates);
}
public static Converter<String, List<RedisClientInfo>> stringToRedisClientListConverter() {
return source -> {
if (!StringUtils.hasText(source)) {
return Collections.emptyList();
}
return STRING_TO_LIST_OF_CLIENT_INFO.convert(source.split("\\r?\\n"));
};
}
public static Converter<Date, Long> dateToLong() {
return DATE_TO_LONG;
}
public static Converter<List<byte[]>, Set<byte[]>> bytesListToBytesSet() {
return BYTES_LIST_TO_BYTES_SET;
}
public static Converter<byte[], String> bytesToString() {
return BYTES_TO_STRING;
}
public static Converter<KeyValue<byte[], byte[]>, List<byte[]>> keyValueToBytesList() {
return KEY_VALUE_TO_BYTES_LIST;
}
public static Converter<Collection<byte[]>, List<byte[]>> bytesSetToBytesList() {
return BYTES_COLLECTION_TO_BYTES_LIST;
}
public static Converter<Collection<byte[]>, List<byte[]>> bytesCollectionToBytesList() {
return BYTES_COLLECTION_TO_BYTES_LIST;
}
public static Converter<List<ScoredValue<byte[]>>, Set<Tuple>> scoredValuesToTupleSet() {
return SCORED_VALUES_TO_TUPLE_SET;
}
public static Converter<List<ScoredValue<byte[]>>, List<Tuple>> scoredValuesToTupleList() {
return SCORED_VALUES_TO_TUPLE_LIST;
}
public static Converter<ScoredValue<byte[]>, Tuple> scoredValueToTuple() {
return SCORED_VALUE_TO_TUPLE;
}
public static Converter<Exception, DataAccessException> exceptionConverter() {
return EXCEPTION_CONVERTER;
}
/**
* @return
* @sice 1.3
*/
public static Converter<Long, Boolean> longToBooleanConverter() {
return LONG_TO_BOOLEAN;
}
public static Long toLong(Date source) {
return DATE_TO_LONG.convert(source);
}
public static Set<byte[]> toBytesSet(List<byte[]> source) {
return BYTES_LIST_TO_BYTES_SET.convert(source);
}
public static List<byte[]> toBytesList(KeyValue<byte[], byte[]> source) {
return KEY_VALUE_TO_BYTES_LIST.convert(source);
}
public static List<byte[]> toBytesList(Collection<byte[]> source) {
return BYTES_COLLECTION_TO_BYTES_LIST.convert(source);
}
public static Set<Tuple> toTupleSet(List<ScoredValue<byte[]>> source) {
return SCORED_VALUES_TO_TUPLE_SET.convert(source);
}
public static Tuple toTuple(ScoredValue<byte[]> source) {
return SCORED_VALUE_TO_TUPLE.convert(source);
}
public static String toString(byte[] source) {
return BYTES_TO_STRING.convert(source);
}
public static ScriptOutputType toScriptOutputType(ReturnType returnType) {
switch (returnType) {
case BOOLEAN:
return ScriptOutputType.BOOLEAN;
case MULTI:
return ScriptOutputType.MULTI;
case VALUE:
return ScriptOutputType.VALUE;
case INTEGER:
return ScriptOutputType.INTEGER;
case STATUS:
return ScriptOutputType.STATUS;
default:
throw new IllegalArgumentException("Return type " + returnType + " is not a supported script output type");
}
}
public static boolean toBoolean(Position where) {
Assert.notNull(where, "list positions are mandatory");
return (Position.AFTER.equals(where) ? false : true);
}
public static int toInt(boolean value) {
return (value ? 1 : 0);
}
public static Map<byte[], byte[]> toMap(List<byte[]> source) {
return BYTES_LIST_TO_MAP.convert(source);
}
public static Converter<List<byte[]>, Map<byte[], byte[]>> bytesListToMapConverter() {
return BYTES_LIST_TO_MAP;
}
public static SortArgs toSortArgs(SortParameters params) {
SortArgs args = new SortArgs();
if (params == null) {
return args;
}
if (params.getByPattern() != null) {
args.by(new String(params.getByPattern(), LettuceCharsets.ASCII));
}
if (params.getLimit() != null) {
args.limit(params.getLimit().getStart(), params.getLimit().getCount());
}
if (params.getGetPattern() != null) {
byte[][] pattern = params.getGetPattern();
for (byte[] bs : pattern) {
args.get(new String(bs, LettuceCharsets.ASCII));
}
}
if (params.getOrder() != null) {
if (params.getOrder() == Order.ASC) {
args.asc();
} else {
args.desc();
}
}
Boolean isAlpha = params.isAlphabetic();
if (isAlpha != null && isAlpha) {
args.alpha();
}
return args;
}
public static List<RedisClientInfo> toListOfRedisClientInformation(String clientList) {
return stringToRedisClientListConverter().convert(clientList);
}
public static byte[][] subarray(byte[][] input, int index) {
if (input.length > index) {
byte[][] output = new byte[input.length - index][];
System.arraycopy(input, index, output, 0, output.length);
return output;
}
return null;
}
public static String boundaryToStringForZRange(Boundary boundary, String defaultValue) {
if (boundary == null || boundary.getValue() == null) {
return defaultValue;
}
return boundaryToString(boundary, "", "(");
}
private static String boundaryToString(Boundary boundary, String inclPrefix, String exclPrefix) {
String prefix = boundary.isIncluding() ? inclPrefix : exclPrefix;
String value = null;
if (boundary.getValue() instanceof byte[]) {
value = toString((byte[]) boundary.getValue());
} else {
value = boundary.getValue().toString();
}
return prefix + value;
}
/**
* Convert a {@link org.springframework.data.redis.connection.RedisZSetCommands.Limit} to a Lettuce
* {@link io.lettuce.core.Limit}.
*
* @param limit
* @return a lettuce {@link io.lettuce.core.Limit}.
* @since 2.0
*/
public static io.lettuce.core.Limit toLimit(RedisZSetCommands.Limit limit) {
return limit.isUnlimited() ? Limit.unlimited() : Limit.create(limit.getOffset(), limit.getCount());
}
/**
* Convert a {@link org.springframework.data.redis.connection.RedisZSetCommands.Range} to a lettuce {@link Range}.
*
* @param range
* @return
* @since 2.0
*/
public static <T> Range<T> toRange(org.springframework.data.redis.connection.RedisZSetCommands.Range range) {
return Range.from(lowerBoundaryOf(range, false), upperBoundaryOf(range, false));
}
/**
* Convert a {@link org.springframework.data.redis.connection.RedisZSetCommands.Range} to a lettuce {@link Range}.
*
* @param range
* @param convertNumberToBytes
* @return
* @since 2.2
*/
public static <T> Range<T> toRange(org.springframework.data.redis.connection.RedisZSetCommands.Range range,
boolean convertNumberToBytes) {
return Range.from(lowerBoundaryOf(range, convertNumberToBytes), upperBoundaryOf(range, convertNumberToBytes));
}
/**
* Convert a {@link org.springframework.data.redis.connection.RedisZSetCommands.Range} to a lettuce {@link Range} and
* reverse boundaries.
*
* @param range
* @return
* @since 2.0
*/
public static <T> Range<T> toRevRange(org.springframework.data.redis.connection.RedisZSetCommands.Range range) {
return Range.from(upperBoundaryOf(range, false), lowerBoundaryOf(range, false));
}
@SuppressWarnings("unchecked")
private static <T> Range.Boundary<T> lowerBoundaryOf(
org.springframework.data.redis.connection.RedisZSetCommands.Range range, boolean convertNumberToBytes) {
return (Range.Boundary<T>) rangeToBoundaryArgumentConverter(false, convertNumberToBytes).convert(range);
}
@SuppressWarnings("unchecked")
private static <T> Range.Boundary<T> upperBoundaryOf(
org.springframework.data.redis.connection.RedisZSetCommands.Range range, boolean convertNumberToBytes) {
return (Range.Boundary<T>) rangeToBoundaryArgumentConverter(true, convertNumberToBytes).convert(range);
}
private static Converter<org.springframework.data.redis.connection.RedisZSetCommands.Range, Range.Boundary<?>> rangeToBoundaryArgumentConverter(
boolean upper, boolean convertNumberToBytes) {
return (source) -> {
Boundary sourceBoundary = upper ? source.getMax() : source.getMin();
if (sourceBoundary == null || sourceBoundary.getValue() == null) {
return Range.Boundary.unbounded();
}
boolean inclusive = sourceBoundary.isIncluding();
Object value = sourceBoundary.getValue();
if (value instanceof Number) {
if (convertNumberToBytes) {
value = value.toString();
} else {
return inclusive ? Range.Boundary.including((Number) value) : Range.Boundary.excluding((Number) value);
}
}
if (value instanceof String) {
if (!StringUtils.hasText((String) value) || ObjectUtils.nullSafeEquals(value, "+")
|| ObjectUtils.nullSafeEquals(value, "-")) {
return Range.Boundary.unbounded();
}
return inclusive ? Range.Boundary.including(value.toString().getBytes(LettuceCharsets.UTF8))
: Range.Boundary.excluding(value.toString().getBytes(LettuceCharsets.UTF8));
}
return inclusive ? Range.Boundary.including((byte[]) value) : Range.Boundary.excluding((byte[]) value);
};
}
/**
* @param source List of Maps containing node details from SENTINEL SLAVES or SENTINEL MASTERS. May be empty or
* {@literal null}.
* @return List of {@link RedisServer}'s. List is empty if List of Maps is empty.
* @since 1.5
*/
public static List<RedisServer> toListOfRedisServer(List<Map<String, String>> source) {
if (CollectionUtils.isEmpty(source)) {
return Collections.emptyList();
}
List<RedisServer> sentinels = new ArrayList<>();
for (Map<String, String> info : source) {
sentinels.add(RedisServer.newServerFrom(Converters.toProperties(info)));
}
return sentinels;
}
/**
* @param sentinelConfiguration the sentinel configuration containing one or more sentinels and a master name. Must
* not be {@literal null}
* @return A {@link RedisURI} containing Redis Sentinel addresses of {@link RedisSentinelConfiguration}
* @since 1.5
*/
public static RedisURI sentinelConfigurationToRedisURI(RedisSentinelConfiguration sentinelConfiguration) {
Assert.notNull(sentinelConfiguration, "RedisSentinelConfiguration is required");
Set<RedisNode> sentinels = sentinelConfiguration.getSentinels();
RedisPassword sentinelPassword = sentinelConfiguration.getSentinelPassword();
RedisURI.Builder builder = RedisURI.builder();
for (RedisNode sentinel : sentinels) {
RedisURI.Builder sentinelBuilder = RedisURI.Builder.redis(sentinel.getHost(), sentinel.getPort());
if (sentinelPassword.isPresent()) {
sentinelBuilder.withPassword(sentinelPassword.get());
}
builder.withSentinel(sentinelBuilder.build());
}
RedisPassword password = sentinelConfiguration.getPassword();
if (password.isPresent()) {
builder.withPassword(password.get());
}
builder.withSentinelMasterId(sentinelConfiguration.getMaster().getName());
return builder.build();
}
public static byte[] toBytes(String source) {
return STRING_TO_BYTES.convert(source);
}
public static byte[] toBytes(Integer source) {
return String.valueOf(source).getBytes();
}
public static byte[] toBytes(Long source) {
return String.valueOf(source).getBytes();
}
/**
* @param source
* @return
* @since 1.6
*/
public static byte[] toBytes(Double source) {
return toBytes(String.valueOf(source));
}
/**
* Converts a given {@link Boundary} to its binary representation suitable for {@literal ZRANGEBY*} commands, despite
* {@literal ZRANGEBYLEX}.
*
* @param boundary
* @param defaultValue
* @return
* @since 1.6
*/
public static String boundaryToBytesForZRange(Boundary boundary, byte[] defaultValue) {
if (boundary == null || boundary.getValue() == null) {
return toString(defaultValue);
}
return boundaryToBytes(boundary, new byte[] {}, toBytes("("));
}
/**
* Converts a given {@link Boundary} to its binary representation suitable for ZRANGEBYLEX command.
*
* @param boundary
* @return
* @since 1.6
*/
public static String boundaryToBytesForZRangeByLex(Boundary boundary, byte[] defaultValue) {
if (boundary == null || boundary.getValue() == null) {
return toString(defaultValue);
}
return boundaryToBytes(boundary, toBytes("["), toBytes("("));
}
private static String boundaryToBytes(Boundary boundary, byte[] inclPrefix, byte[] exclPrefix) {
byte[] prefix = boundary.isIncluding() ? inclPrefix : exclPrefix;
byte[] value = null;
if (boundary.getValue() instanceof byte[]) {
value = (byte[]) boundary.getValue();
} else if (boundary.getValue() instanceof Double) {
value = toBytes((Double) boundary.getValue());
} else if (boundary.getValue() instanceof Long) {
value = toBytes((Long) boundary.getValue());
} else if (boundary.getValue() instanceof Integer) {
value = toBytes((Integer) boundary.getValue());
} else if (boundary.getValue() instanceof String) {
value = toBytes((String) boundary.getValue());
} else {
throw new IllegalArgumentException(String.format("Cannot convert %s to binary format", boundary.getValue()));
}
ByteBuffer buffer = ByteBuffer.allocate(prefix.length + value.length);
buffer.put(prefix);
buffer.put(value);
return toString(ByteUtils.getBytes(buffer));
}
public static List<RedisClusterNode> partitionsToClusterNodes(Partitions partitions) {
return PARTITIONS_TO_CLUSTER_NODES.convert(partitions);
}
/**
* @param source
* @return
* @since 1.7
*/
public static RedisClusterNode toRedisClusterNode(io.lettuce.core.cluster.models.partitions.RedisClusterNode source) {
return CLUSTER_NODE_TO_CLUSTER_NODE_CONVERTER.convert(source);
}
/**
* Converts a given {@link Expiration} and {@link SetOption} to the according {@link SetArgs}.<br />
*
* @param expiration can be {@literal null}.
* @param option can be {@literal null}.
* @since 1.7
*/
public static SetArgs toSetArgs(@Nullable Expiration expiration, @Nullable SetOption option) {
SetArgs args = new SetArgs();
if (expiration != null && !expiration.isPersistent()) {
switch (expiration.getTimeUnit()) {
case SECONDS:
args.ex(expiration.getExpirationTime());
break;
default:
args.px(expiration.getConverted(TimeUnit.MILLISECONDS));
break;
}
}
if (option != null) {
switch (option) {
case SET_IF_ABSENT:
args.nx();
break;
case SET_IF_PRESENT:
args.xx();
break;
default:
break;
}
}
return args;
}
static Converter<List<byte[]>, Long> toTimeConverter() {
return BYTES_LIST_TO_TIME_CONVERTER;
}
/**
* Convert {@link Metric} into {@link GeoArgs.Unit}.
*
* @param metric
* @return
* @since 1.8
*/
public static GeoArgs.Unit toGeoArgsUnit(Metric metric) {
Metric metricToUse = metric == null || ObjectUtils.nullSafeEquals(Metrics.NEUTRAL, metric) ? DistanceUnit.METERS
: metric;
return ObjectUtils.caseInsensitiveValueOf(GeoArgs.Unit.values(), metricToUse.getAbbreviation());
}
/**
* Convert {@link GeoRadiusCommandArgs} into {@link GeoArgs}.
*
* @param args
* @return
* @since 1.8
*/
public static GeoArgs toGeoArgs(GeoRadiusCommandArgs args) {
GeoArgs geoArgs = new GeoArgs();
if (args.hasFlags()) {
for (GeoRadiusCommandArgs.Flag flag : args.getFlags()) {
switch (flag) {
case WITHCOORD:
geoArgs.withCoordinates();
break;
case WITHDIST:
geoArgs.withDistance();
break;
}
}
}
if (args.hasSortDirection()) {
switch (args.getSortDirection()) {
case ASC:
geoArgs.asc();
break;
case DESC:
geoArgs.desc();
break;
}
}
if (args.hasLimit()) {
geoArgs.withCount(args.getLimit());
}
return geoArgs;
}
/**
* Convert {@link BitFieldSubCommands} into {@link BitFieldArgs}.
*
* @param subCommands
* @return
* @since 2.1
*/
public static BitFieldArgs toBitFieldArgs(BitFieldSubCommands subCommands) {
BitFieldArgs args = new BitFieldArgs();
for (BitFieldSubCommand subCommand : subCommands) {
BitFieldArgs.BitFieldType bft = subCommand.getType().isSigned()
? BitFieldArgs.signed(subCommand.getType().getBits())
: BitFieldArgs.unsigned(subCommand.getType().getBits());
BitFieldArgs.Offset offset;
if (subCommand.getOffset().isZeroBased()) {
offset = BitFieldArgs.offset((int) subCommand.getOffset().getValue());
} else {
offset = BitFieldArgs.typeWidthBasedOffset((int) subCommand.getOffset().getValue());
}
if (subCommand instanceof BitFieldGet) {
args = args.get(bft, offset);
} else if (subCommand instanceof BitFieldSet) {
args = args.set(bft, offset, ((BitFieldSet) subCommand).getValue());
} else if (subCommand instanceof BitFieldIncrBy) {
BitFieldIncrBy.Overflow overflow = ((BitFieldIncrBy) subCommand).getOverflow();
if (overflow != null) {
BitFieldArgs.OverflowType type;
switch (overflow) {
case SAT:
type = BitFieldArgs.OverflowType.SAT;
break;
case FAIL:
type = BitFieldArgs.OverflowType.FAIL;
break;
case WRAP:
type = BitFieldArgs.OverflowType.WRAP;
break;
default:
throw new IllegalArgumentException(
String.format("Invalid OVERFLOW. Expected one the following %s but got %s.",
Arrays.toString(Overflow.values()), overflow));
}
args = args.overflow(type);
}
args = args.incrBy(bft, (int) subCommand.getOffset().getValue(), ((BitFieldIncrBy) subCommand).getValue());
}
}
return args;
}
/**
* Convert {@link ScanOptions} to {@link ScanArgs}.
*
* @param options the {@link ScanOptions} to convert, may be {@literal null}.
* @return the converted {@link ScanArgs}. Returns {@literal null} if {@link ScanOptions} is {@literal null}.
* @see 2.1
*/
@Nullable
static ScanArgs toScanArgs(@Nullable ScanOptions options) {
if (options == null) {
return null;
}
ScanArgs scanArgs = new ScanArgs();
if (options.getPattern() != null) {
scanArgs.match(options.getPattern());
}
if (options.getCount() != null) {
scanArgs.limit(options.getCount());
}
return scanArgs;
}
/**
* Get {@link Converter} capable of {@link Set} of {@link Byte} into {@link GeoResults}.
*
* @return
* @since 1.8
*/
public static Converter<Set<byte[]>, GeoResults<GeoLocation<byte[]>>> bytesSetToGeoResultsConverter() {
return source -> {
if (CollectionUtils.isEmpty(source)) {
return new GeoResults<>(Collections.<GeoResult<GeoLocation<byte[]>>> emptyList());
}
List<GeoResult<GeoLocation<byte[]>>> results = new ArrayList<>(source.size());
Iterator<byte[]> it = source.iterator();
while (it.hasNext()) {
results.add(new GeoResult<>(new GeoLocation<>(it.next(), null), new Distance(0D)));
}
return new GeoResults<>(results);
};
}
/**
* Get {@link Converter} capable of convering {@link GeoWithin} into {@link GeoResults}.
*
* @param metric
* @return
* @since 1.8
*/
public static Converter<List<GeoWithin<byte[]>>, GeoResults<GeoLocation<byte[]>>> geoRadiusResponseToGeoResultsConverter(
Metric metric) {
return GeoResultsConverterFactory.INSTANCE.forMetric(metric);
}
/**
* @return
* @since 1.8
*/
public static ListConverter<io.lettuce.core.GeoCoordinates, Point> geoCoordinatesToPointConverter() {
return GEO_COORDINATE_LIST_TO_POINT_LIST_CONVERTER;
}
/**
* @return
* @since 2.0
*/
@SuppressWarnings("unchecked")
public static <K, V> ListConverter<KeyValue<K, V>, V> keyValueListUnwrapper() {
return (ListConverter) KEY_VALUE_LIST_UNWRAPPER;
}
public static Converter<TransactionResult, List<Object>> transactionResultUnwrapper() {
return TRANSACTION_RESULT_UNWRAPPER;
}
/**
* Return {@link Optional} lower bound from {@link Range}.
*
* @param range