forked from apache/casbin-jcasbin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtil.java
More file actions
416 lines (374 loc) · 12.5 KB
/
Copy pathUtil.java
File metadata and controls
416 lines (374 loc) · 12.5 KB
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
// Copyright 2018 The casbin Authors. All Rights Reserved.
//
// 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 org.casbin.jcasbin.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
public static boolean enableLog = true;
private static Pattern evalReg = Pattern.compile("\\beval\\(([^),]*)\\)");
private static final Pattern IN_SYNTAX_PATTERN = Pattern.compile("([^\\s]+?) +in +(\\([^)]*\\)|\\S+)");
private static Pattern escapeAssertionRegex = Pattern.compile("\\b(r|p)[0-9]*\\.");
private static Logger LOGGER = LoggerFactory.getLogger("org.casbin.jcasbin");
private static final String md5AlgorithmName = "MD5";
/**
* isLogPrintEnabled checks if {@code logPrint} or {@code logPrintfInfo} are enabled.
*
* @return {@code true} if INFO logs are enabled.
*/
public static boolean isLogPrintEnabled() {
return enableLog && LOGGER.isInfoEnabled();
}
/**
* logPrint prints the log.
*
* @param v the log.
*/
public static void logPrint(String v) {
if (enableLog) {
LOGGER.info(v);
}
}
/**
* logPrintfInfo prints the log with the SLF4J format.
*
* @param format the format of the log.
* @param v the log.
*/
public static void logPrintfInfo(String format, Object... v) {
if (enableLog) {
LOGGER.info(format, v);
}
}
/**
* logPrintf prints the log with the format.
*
* @param format the format of the log.
* @param v the log.
*/
@Deprecated
public static void logPrintf(String format, String... v) {
if (enableLog) {
String tmp = String.format(format, (Object[]) v);
LOGGER.info(tmp);
}
}
/**
* logPrintf prints the log with the format as a warning.
*
* @param format the format of the log.
* @param v the log.
*/
public static void logPrintfWarn(String format, Object... v) {
if (enableLog) {
LOGGER.warn(format, v);
}
}
/**
* logPrintf prints the log with the format as an error.
*
* @param format the format of the log.
* @param v the log.
*/
public static void logPrintfError(String format, Object... v) {
if (enableLog) {
LOGGER.error(format, v);
}
}
/**
* logPrintf prints the log with the format as an error.
*
* @param message the message accompanying the exception
* @param t the exception (throwable) to log
*/
public static void logPrintfError(String message, Throwable t) {
if (enableLog) {
LOGGER.error(message, t);
}
}
/**
* logEnforce prints the log of Enforce.
*
* @param request the Enforce request.
* @param result the Enforce result.
* @param explain to explain enforcement by matched rules.
*/
public static void logEnforce(Object[] request, boolean result, List<String> explain) {
if (enableLog) {
LOGGER.info("Request: " + Arrays.toString(request) + " ---> " + result);
if (explain != null) {
LOGGER.info("Hit Policy: " + explain);
}
}
}
/**
* escapeAssertion escapes the dots in the assertion, because the expression
* evaluation doesn't support such variable names.
*
* @param s the value of the matcher and effect assertions.
* @return the escaped value.
*/
public static String escapeAssertion(String s) {
Matcher m = escapeAssertionRegex.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group().replace(".", "_"));
}
m.appendTail(sb);
return sb.toString();
}
/**
* convertInSyntax Convert 'in' to 'include' to fit aviatorscript,because
* aviatorscript don't support native 'in' syntax
*
* @param expString the value of the matcher
* @return the 'include' expression.
*/
public static String convertInSyntax(String expString) {
if (expString.contains(" in ")) {
Matcher matcher = IN_SYNTAX_PATTERN.matcher(expString);
if (matcher.find()) {
return replaceInSyntaxWithInclude(matcher);
}
}
return expString;
}
private static String replaceInSyntaxWithInclude(Matcher matcher) {
StringBuffer sb = new StringBuffer();
do {
String leftOperand = matcher.group(1);
String rightOperand = matcher.group(2);
// If right operand is a parenthesized expression with commas (tuple literal),
// convert to tuple() function. Otherwise, keep parentheses as-is for grouping.
if (rightOperand.startsWith("(") && rightOperand.endsWith(")") && rightOperand.contains(",")) {
rightOperand = "tuple" + rightOperand;
}
matcher.appendReplacement(sb, Matcher.quoteReplacement("include(" + rightOperand + ", " + leftOperand + ")"));
} while (matcher.find());
matcher.appendTail(sb);
return sb.toString();
}
/**
* removeComments removes the comments starting with # in the text.
*
* @param s a line in the model.
* @return the line without comments.
*/
public static String removeComments(String s) {
int pos = s.indexOf("#");
if (pos == -1) {
return s;
}
return s.substring(0, pos).trim();
}
/**
* arrayEquals determines whether two string arrays are identical.
*
* @param a the first array.
* @param b the second array.
* @return whether a equals to b.
*/
public static boolean arrayEquals(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
}
/**
* array2DEquals determines whether two 2-dimensional string arrays are
* identical.
*
* @param a the first 2-dimensional array.
* @param b the second 2-dimensional array.
* @return whether a equals to b.
*/
public static boolean array2DEquals(List<List<String>> a, List<List<String>> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
for (int i = 0; i < a.size(); i++) {
if (!arrayEquals(a.get(i), b.get(i))) {
return false;
}
}
return true;
}
/**
* arrayRemoveDuplicates removes any duplicated elements in a string array
* preserving the order.
*
* @param s the array.
* @return the array without duplicates.
*/
public static List<String> arrayRemoveDuplicates(List<String> s) {
Set<String> set = new LinkedHashSet<>(s);
return new ArrayList<String>(set);
}
/**
* arrayToString gets a printable string for a string array.
*
* @param s the array.
* @return the string joined by the array elements.
*/
public static String arrayToString(List<String> s) {
return String.join(", ", s);
}
/**
* paramsToString gets a printable string for variable number of parameters.
*
* @param s the parameters.
* @return the string joined by the parameters.
*/
public static String paramsToString(String[] s) {
return String.join(", ", s);
}
/**
* splitCommaDelimited splits a comma-delimited string according to the default
* processing method of the CSV file
* into a string array. It assumes that any number of whitespace might exist
* before or after the token and that tokens do not include
* whitespace as part of their value unless they are enclosed by double
* quotes.
*
* @param s the string.
* @return the array with the string tokens.
*/
public static String[] splitCommaDelimited(String s) {
String[] records = null;
if (s != null) {
try {
CSVFormat csvFormat = CSVFormat.Builder.create().setIgnoreSurroundingSpaces(true).build();
CSVParser csvParser = csvFormat.parse(new StringReader(s));
List<CSVRecord> csvRecords = csvParser.getRecords();
records = new String[csvRecords.get(0).size()];
for (int i = 0; i < csvRecords.get(0).size(); i++) {
records[i] = csvRecords.get(0).get(i).trim();
}
} catch (IOException e) {
Util.logPrintfError("CSV parser failed to parse this line: " + s, e);
}
}
return records;
}
/**
* setEquals determines whether two string sets are identical.
*
* @param a the first set.
* @param b the second set.
* @return whether a equals to b.
*/
public static boolean setEquals(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
if (a.size() != b.size()) {
return false;
}
Collections.sort(a);
Collections.sort(b);
for (int i = 0; i < a.size(); i++) {
if (!a.get(i).equals(b.get(i))) {
return false;
}
}
return true;
}
public static boolean hasEval(String exp) {
return evalReg.matcher(exp).matches();
}
public static String replaceEval(String s, String replacement) {
return evalReg.matcher(s).replaceAll("(" + replacement + ")");
}
public static String md5(String data) {
return new String(getDigest(md5AlgorithmName).digest(data.getBytes(StandardCharsets.UTF_8)));
}
private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Helper method to check if a string is a valid JSON
*
* @param str the string to be checked.
* @return whether the string is a valid
*/
public static boolean isJsonString(String str) {
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readTree(str);
return true;
} catch (JsonProcessingException e) {
return false;
}
}
/**
* setSubtract returns elements in list A that are not in list B.
* Preserves order from list A.
*
* @param a the first list (base)
* @param b the second list (subtrahend)
* @return a - b (elements in A but not in B)
*/
public static List<String> setSubtract(List<String> a, List<String> b) {
if (a == null) {
a = new ArrayList<>();
}
if (b == null) {
b = new ArrayList<>();
}
Set<String> bSet = new HashSet<>(b);
List<String> result = new ArrayList<>();
for (String item : a) {
if (!bSet.contains(item)) {
result.add(item);
}
}
return result;
}
}