3
3
import java .nio .ByteBuffer ;
4
4
import java .nio .ByteOrder ;
5
5
6
+ import java .util .Arrays ;
6
7
import java .util .HashMap ;
8
+ import java .util .HashSet ;
7
9
import java .util .Map ;
10
+ import java .util .Set ;
8
11
9
12
import redis .clients .jedis .util .SafeEncoder ;
10
13
@@ -18,6 +21,18 @@ public class RediSearchUtil {
18
21
* @return map with string value
19
22
*/
20
23
public static Map <String , String > toStringMap (Map <String , Object > input ) {
24
+ return toStringMap (input , false );
25
+ }
26
+
27
+ /**
28
+ * Jedis' {@code hset} methods do not support {@link Object}s as values. This method eases process
29
+ * of converting a {@link Map} with Objects as values so that the returning Map can be set to a
30
+ * {@code hset} method.
31
+ * @param input map with object value
32
+ * @param stringEscape whether to escape the String objects
33
+ * @return map with string value
34
+ */
35
+ public static Map <String , String > toStringMap (Map <String , Object > input , boolean stringEscape ) {
21
36
Map <String , String > output = new HashMap <>(input .size ());
22
37
for (Map .Entry <String , Object > entry : input .entrySet ()) {
23
38
String key = entry .getKey ();
@@ -32,9 +47,9 @@ public static Map<String, String> toStringMap(Map<String, Object> input) {
32
47
redis .clients .jedis .GeoCoordinate geo = (redis .clients .jedis .GeoCoordinate ) obj ;
33
48
str = geo .getLongitude () + "," + geo .getLatitude ();
34
49
} else if (obj instanceof String ) {
35
- str = (String ) obj ;
50
+ str = stringEscape ? escape (( String ) obj ) : (String ) obj ;
36
51
} else {
37
- str = obj . toString ( );
52
+ str = String . valueOf ( obj );
38
53
}
39
54
output .put (key , str );
40
55
}
@@ -54,6 +69,39 @@ public static byte[] ToByteArray(float[] input) {
54
69
return bytes ;
55
70
}
56
71
72
+ private static final Set <Character > ESCAPE_CHARS = new HashSet <>(Arrays .asList (//
73
+ ',' , '.' , '<' , '>' , '{' , '}' , '[' , //
74
+ ']' , '"' , '\'' , ':' , ';' , '!' , '@' , //
75
+ '#' , '$' , '%' , '^' , '&' , '*' , '(' , //
76
+ ')' , '-' , '+' , '=' , '~' , '|' //
77
+ ));
78
+
79
+ public static String escape (String text ) {
80
+ return escape (text , false );
81
+ }
82
+
83
+ public static String escapeQuery (String query ) {
84
+ return escape (query , true );
85
+ }
86
+
87
+ public static String escape (String text , boolean querying ) {
88
+ char [] chars = text .toCharArray ();
89
+
90
+ StringBuilder sb = new StringBuilder ();
91
+ for (char ch : chars ) {
92
+ if (ESCAPE_CHARS .contains (ch )
93
+ || (querying && ch == ' ' )) {
94
+ sb .append ("\\ " );
95
+ }
96
+ sb .append (ch );
97
+ }
98
+ return sb .toString ();
99
+ }
100
+
101
+ public static String unescape (String text ) {
102
+ return text .replace ("\\ " , "" );
103
+ }
104
+
57
105
private RediSearchUtil () {
58
106
throw new InstantiationError ("Must not instantiate this class" );
59
107
}
0 commit comments