Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.expressionevaluator / org.gvsig.expressionevaluator.lib / org.gvsig.expressionevaluator.lib.api / src / main / java / org / gvsig / expressionevaluator / ExpressionUtils.java @ 45527

History | View | Annotate | Download (21.2 KB)

1 44163 jjdelcerro
package org.gvsig.expressionevaluator;
2
3 45523 jjdelcerro
import java.awt.Color;
4 44389 jjdelcerro
import java.io.File;
5 45527 jjdelcerro
import java.net.MalformedURLException;
6
import java.net.URL;
7 45523 jjdelcerro
import java.util.List;
8
import java.util.regex.Matcher;
9
import java.util.regex.Pattern;
10 44397 jjdelcerro
import org.apache.commons.lang3.ArrayUtils;
11 44215 jjdelcerro
import org.apache.commons.lang3.StringUtils;
12 44198 jjdelcerro
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
13 44818 jjdelcerro
import static org.gvsig.expressionevaluator.ExpressionEvaluatorManager.DYNAMICTEXT_ENDTAG;
14
import static org.gvsig.expressionevaluator.ExpressionEvaluatorManager.DYNAMICTEXT_STARTTAG;
15 45523 jjdelcerro
import org.gvsig.tools.util.ListBuilder;
16 44163 jjdelcerro
17
/**
18
 *
19 45523 jjdelcerro
 * @author gvSIG Team
20 44163 jjdelcerro
 */
21 45523 jjdelcerro
@SuppressWarnings("UseSpecificCatch")
22 44163 jjdelcerro
public class ExpressionUtils {
23
24
    public static boolean isEmpty(Expression expression) {
25
        return expression == null || expression.isEmpty();
26
    }
27
28
    public static boolean isPhraseEmpty(Expression expression) {
29
        return expression == null || expression.isPhraseEmpty();
30
    }
31
32
    public static Expression defaultIfEmpty(Expression expression, Expression defaultValue) {
33
        if( expression==null || expression.isEmpty() ) {
34
            return defaultValue;
35
        }
36
        return expression;
37
    }
38
39
    public static Expression defaultNullIfEmpty(Expression expression) {
40
        if( expression==null || expression.isEmpty() ) {
41
            return null;
42
        }
43
        return expression;
44
    }
45
46
    public static Expression defaultIfPhraseEmpty(Expression expression, Expression defaultValue) {
47
        if( expression==null || expression.isPhraseEmpty() ) {
48
            return defaultValue;
49
        }
50
        return expression;
51
    }
52
53
    public static Expression defaultNullIfPhraseEmpty(Expression expression) {
54
        if( expression==null || expression.isPhraseEmpty() ) {
55
            return null;
56
        }
57
        return expression;
58
    }
59
60
    public static Expression createExpression() {
61
        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
62
        return expression;
63
    }
64
65
    public static Expression createExpression(String phrase) {
66 44215 jjdelcerro
        if( StringUtils.isBlank(phrase) ) {
67
            return null;
68
        }
69 44163 jjdelcerro
        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
70
        expression.setPhrase(phrase);
71
        return expression;
72
    }
73
74 44533 jjdelcerro
//    public static Expression createExpression(String phrase, String code, Script... scripts) {
75
//        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
76
//        expression.setPhrase(phrase);
77
//        expression.setUserScript(code);
78
//        for (Script script : scripts) {
79
//            expression.addScript(script);
80
//        }
81
//        return expression;
82
//    }
83
//
84
//    public static Expression createExpression(String phrase, String code, String languaje, Script... scripts) {
85
//        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
86
//        expression.setPhrase(phrase);
87
//        expression.setUserScript(code, languaje);
88
//        for (Script script : scripts) {
89
//            expression.addScript(script);
90
//        }
91
//        return expression;
92
//    }
93 44163 jjdelcerro
94 44198 jjdelcerro
    public static ExpressionBuilder createExpressionBuilder() {
95
        ExpressionBuilder builder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder();
96
        return builder;
97
    }
98
99
    public static Code compile(String expression) {
100 44215 jjdelcerro
        if( StringUtils.isBlank(expression) ) {
101
            return null;
102
        }
103 44198 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
104
        Code code = manager.compile(expression);
105
        return code;
106
    }
107
108 44346 jjdelcerro
    public static Object evaluate(String expression) {
109
        return evaluate(null, expression);
110
    }
111
112 44198 jjdelcerro
    public static Object evaluate(SymbolTable symbolTable, String expression) {
113 44215 jjdelcerro
        if( StringUtils.isBlank(expression) ) {
114
            return null;
115
        }
116 44198 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
117
        Object x = manager.evaluate(symbolTable, expression);
118
        return x;
119
    }
120
121
    public static Object evaluate(SymbolTable symbolTable, Code code) {
122
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
123
        Object x = manager.evaluate(symbolTable, code);
124
        return x;
125
    }
126
127
    public static Code optimize(SymbolTable symbolTable, Code code) {
128
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
129
        code = manager.optimize(symbolTable, code);
130
        return code;
131
    }
132
133
    public static String toString(Value value, Formatter formatter) {
134
        if( value == null ) {
135
            return null;
136
        }
137
        if( formatter==null ) {
138 44769 jjdelcerro
            ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
139
            formatter = manager.getExpressionBuilderFormatter();
140 44198 jjdelcerro
        }
141
        return value.toString(formatter);
142
    }
143
144
    public static String toString(Value value) {
145 44769 jjdelcerro
      return toString(value, null);
146 44198 jjdelcerro
    }
147
148
    public static String toString(Code code, Formatter formatter) {
149
        if( code == null ) {
150
            return null;
151
        }
152
        if( formatter==null ) {
153
            formatter = Code.EMPTY_FORMATTER;
154
        }
155
        return code.toString(formatter);
156
    }
157
158
    public static String toString(Code code) {
159 44769 jjdelcerro
      return toString(code, null);
160 44198 jjdelcerro
    }
161
162 44215 jjdelcerro
    public static Expression createExpressionFromJSON(String json) {
163
        Expression expression = ExpressionUtils.createExpression();
164
        expression.fromJSON(json);
165
        return expression;
166
    }
167
168
    public static MutableSymbolTable createSymbolTable() {
169
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
170
        MutableSymbolTable symbolTable = manager.createSymbolTable();
171
        return symbolTable;
172
    }
173 44397 jjdelcerro
174 44408 jjdelcerro
    public static String surroundByDynamicTextTag(String source) {
175
        return surroundByDynamicTextTag(source, true);
176
    }
177
178
    public static String surroundByDynamicTextTag(String source, boolean insert) {
179
        if( source==null ) {
180
            return null;
181
        }
182
        if( insert ) {
183 44818 jjdelcerro
            return DYNAMICTEXT_STARTTAG+ "=" + source + DYNAMICTEXT_ENDTAG;
184 44408 jjdelcerro
        }
185 44818 jjdelcerro
        return DYNAMICTEXT_STARTTAG + source + DYNAMICTEXT_ENDTAG;
186 44408 jjdelcerro
    }
187
188 44397 jjdelcerro
    public static boolean isDynamicText(String source) {
189 44818 jjdelcerro
        if( !source.contains(DYNAMICTEXT_STARTTAG) ) {
190
          return false;
191
        }
192
        String[] sources = StringUtils.substringsBetween(source, DYNAMICTEXT_STARTTAG, DYNAMICTEXT_ENDTAG);
193 44397 jjdelcerro
        if( ArrayUtils.isEmpty(sources) ) {
194
            return false;
195
        }
196
        return true;
197
    }
198 44215 jjdelcerro
199 44397 jjdelcerro
    public static String evaluateDynamicText(String source) {
200 44389 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
201 44397 jjdelcerro
        return manager.evaluateDynamicText(source);
202 44389 jjdelcerro
    }
203
204 44397 jjdelcerro
    public static String evaluateDynamicText(SymbolTable symbolTable, String source) {
205 44389 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
206 44397 jjdelcerro
        return manager.evaluateDynamicText(symbolTable, source);
207 44389 jjdelcerro
    }
208
209 44390 jjdelcerro
    public static File evaluateFilename(File source) {
210 44389 jjdelcerro
        return evaluateFilename(null, source);
211
    }
212 44397 jjdelcerro
213 45527 jjdelcerro
    public static URL evaluateURL(URL source) {
214
        return evaluateURL(null, source);
215
    }
216
217 44397 jjdelcerro
    public static boolean isDynamicFilename(File source) {
218
        if( source == null ) {
219
            return false;
220
        }
221
        return isDynamicText(source.getPath());
222
    }
223 45163 jjdelcerro
224 45527 jjdelcerro
    public static boolean isDynamicURL(URL source) {
225
        if( source == null ) {
226
            return false;
227
        }
228
        return isDynamicText(source.toString());
229
    }
230
231 45163 jjdelcerro
    public static File createDynamicFile(Value builder) {
232
        File f = new File(surroundByDynamicTextTag(builder.toString()));
233
        return f;
234
    }
235 44389 jjdelcerro
236 45163 jjdelcerro
    public static File createDynamicFile(String expression) {
237
        File f = new File(surroundByDynamicTextTag(expression));
238
        return f;
239
    }
240
241 44389 jjdelcerro
    @SuppressWarnings("StringEquality")
242 44390 jjdelcerro
    public static File evaluateFilename(SymbolTable symbolTable, File source) {
243 45527 jjdelcerro
        String src =  source.getPath();
244
        if( !isDynamicText(src) ) {
245
            return source;
246
        }
247 44389 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
248 44397 jjdelcerro
        String r = manager.evaluateDynamicText(symbolTable, src);
249 44389 jjdelcerro
        if( r == src ) { // !!! I compare that it is the same pointer, it is what I want.
250
            return source;
251
        }
252
        File f = new File(r);
253
        return f;
254
    }
255 44444 jjdelcerro
256 45527 jjdelcerro
    @SuppressWarnings("StringEquality")
257
    public static URL evaluateURL(SymbolTable symbolTable, URL source) {
258
        String src =  source.toString();
259
        if( !isDynamicText(src) ) {
260
            return source;
261
        }
262
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
263
        String r = manager.evaluateDynamicText(symbolTable, src);
264
        if( r == src ) { // !!! I compare that it is the same pointer, it is what I want.
265
            return source;
266
        }
267
        try {
268
            URL url = new URL(r);
269
            return url;
270
        } catch (MalformedURLException ex) {
271
            return source;
272
        }
273
    }
274
275 44444 jjdelcerro
    public static int parseInt(String s) throws NumberFormatException {
276
        if( StringUtils.isBlank(s) ) {
277
            throw new NumberFormatException("Can't get integer from a blank string.");
278
        }
279
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
280 44446 jjdelcerro
        SymbolTable symbolTable = null; //manager.getInmutableSymbolTable();
281 44444 jjdelcerro
        Object x;
282
        try {
283
            x = manager.evaluate(symbolTable, s);
284
            if( x instanceof Number ) {
285
                return ((Number) x).intValue();
286
            }
287
        } catch(Exception ex) {
288
            NumberFormatException ex1 = new NumberFormatException("Can't get integer from '"+s+"'.");
289
            ex1.initCause(ex);
290
            throw ex;
291
        }
292
        if( x == null ) {
293
            throw new NumberFormatException("Can't get integer from '"+s+"' value is null.");
294
        }
295
        throw new NumberFormatException("Can't get integer from '"+s+"' value is a "+x.getClass().getSimpleName()+".");
296
    }
297
298
    public static long parseLong(String s) throws NumberFormatException {
299
        if( StringUtils.isBlank(s) ) {
300
            throw new NumberFormatException("Can't get long from a blank string.");
301
        }
302 45523 jjdelcerro
        try {
303
            int value = Integer.parseInt(s);
304
            return value;
305
        } catch(Exception ex) {
306
307
        }
308 44444 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
309 44446 jjdelcerro
        SymbolTable symbolTable = null; //manager.getInmutableSymbolTable();
310 44444 jjdelcerro
        Object x;
311
        try {
312
            x = manager.evaluate(symbolTable, s);
313
            if( x instanceof Number ) {
314
                return ((Number) x).longValue();
315
            }
316
        } catch(Exception ex) {
317
            NumberFormatException ex1 = new NumberFormatException("Can't get long from '"+s+"'.");
318
            ex1.initCause(ex);
319
            throw ex;
320
        }
321
        if( x == null ) {
322
            throw new NumberFormatException("Can't get long from '"+s+"' value is null.");
323
        }
324
        throw new NumberFormatException("Can't get long from '"+s+"' value is a "+x.getClass().getSimpleName()+".");
325
    }
326
327
    public static double parseDouble(String s) throws NumberFormatException {
328
        if( StringUtils.isBlank(s) ) {
329
            throw new NumberFormatException("Can't get double from a blank string.");
330
        }
331 45523 jjdelcerro
        try {
332
            double value = Double.parseDouble(s);
333
            return value;
334
        } catch(Exception ex) {
335
336
        }
337 44444 jjdelcerro
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
338 44446 jjdelcerro
        SymbolTable symbolTable = null; //manager.getInmutableSymbolTable();
339 44444 jjdelcerro
        Object x;
340
        try {
341
            x = manager.evaluate(symbolTable, s);
342
            if( x instanceof Number ) {
343
                return ((Number) x).doubleValue();
344
            }
345
        } catch(Exception ex) {
346
            NumberFormatException ex1 = new NumberFormatException("Can't get double from '"+s+"'.");
347
            ex1.initCause(ex);
348
            throw ex;
349
        }
350
        if( x == null ) {
351
            throw new NumberFormatException("Can't get double from '"+s+"' value is null.");
352
        }
353
        throw new NumberFormatException("Can't get double from '"+s+"' value is a "+x.getClass().getSimpleName()+".");
354
    }
355 44644 jjdelcerro
356
    public static Compiler createCompiler() {
357
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
358
        Compiler compiler = manager.createCompiler();
359
        return compiler;
360
    }
361
362
    public static Interpreter createInterpreter() {
363
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
364
        Interpreter interpreter = manager.createInterpreter();
365
        return interpreter;
366
    }
367
368
    public static Optimizer createOptimizer() {
369
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
370
        Optimizer optimizer = manager.createOptimizer();
371
        return optimizer;
372
    }
373
374
    public static String repr(Object value) {
375
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
376
        ReprMethod method = manager.getReprMethod(value);
377
        return method.repr(value);
378
    }
379 44750 jjdelcerro
380
    public static CodeBuilder createCodeBuilder() {
381
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
382
        return manager.createCodeBuilder();
383
    }
384 45523 jjdelcerro
385
    private static final List<String> TRUE_VALUES = ListBuilder.create("true","on","t", "1", "-1" );
386
    private static final List<String> FALSE_VALUES =  ListBuilder.create("false","off","f", "0" );
387
388
    public static boolean parseBoolean(SymbolTable symbolTable, String expression, boolean defaultValue) {
389
        expression = StringUtils.trimToNull(expression);
390
        if( StringUtils.isBlank(expression) ) {
391
            return defaultValue;
392
        }
393
        if( TRUE_VALUES.contains(expression.toLowerCase()))  {
394
            return true;
395
        }
396
        if( FALSE_VALUES.contains(expression.toLowerCase()))  {
397
            return false;
398
        }
399
        try {
400
            return (boolean) ExpressionUtils.evaluate(symbolTable, expression);
401
        } catch(Exception ex) {
402
            return defaultValue;
403
        }
404
    }
405
406
    public static boolean parseBoolean(String expression) {
407
        expression = StringUtils.trimToNull(expression);
408
        if( StringUtils.isBlank(expression) ) {
409
            throw new IllegalArgumentException("Can't get boolean from a blank string.");
410
        }
411
        if( TRUE_VALUES.contains(expression.toLowerCase()))  {
412
            return true;
413
        }
414
        if( FALSE_VALUES.contains(expression.toLowerCase()))  {
415
            return false;
416
        }
417
        Object x;
418
        try {
419
            x = ExpressionUtils.evaluate(null, expression);
420
            return (boolean) x;
421
        } catch(Exception ex) {
422
            IllegalArgumentException ex1 = new IllegalArgumentException("Can't get boolean from '"+expression+"'.");
423
            ex1.initCause(ex);
424
            throw ex;
425
        }
426
    }
427
428
    public static int parseInt(SymbolTable symbolTable, String expression, int defaultValue) {
429
        if( StringUtils.isBlank(expression) ) {
430
            return defaultValue;
431
        }
432
        try {
433
            int value = Integer.parseInt(expression);
434
            return value;
435
        } catch(Exception ex) {
436
437
        }
438
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
439
        Object x;
440
        try {
441
            x = manager.evaluate(symbolTable, expression);
442
            if( x instanceof Number ) {
443
                return ((Number) x).intValue();
444
            }
445
        } catch(Exception ex) {
446
        }
447
        return defaultValue;
448
    }
449
450
    public static long parseLong(SymbolTable symbolTable, String expression, long defaultValue) {
451
        if( StringUtils.isBlank(expression) ) {
452
            return defaultValue;
453
        }
454
        try {
455
            int value = Integer.parseInt(expression);
456
            return value;
457
        } catch(Exception ex) {
458
459
        }
460
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
461
        Object x;
462
        try {
463
            x = manager.evaluate(symbolTable, expression);
464
            if( x instanceof Number ) {
465
                return ((Number) x).longValue();
466
            }
467
        } catch(Exception ex) {
468
        }
469
        return defaultValue;
470
    }
471
472
    public static double parseDouble(SymbolTable symbolTable, String expression, double defaultValue) {
473
        if( StringUtils.isBlank(expression) ) {
474
            return defaultValue;
475
        }
476
        try {
477
            double value = Double.parseDouble(expression);
478
            return value;
479
        } catch(Exception ex) {
480
481
        }
482
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
483
        Object x;
484
        try {
485
            x = manager.evaluate(symbolTable, expression);
486
            if( x instanceof Number ) {
487
                return ((Number) x).doubleValue();
488
            }
489
        } catch(Exception ex) {
490
        }
491
        return defaultValue;
492
    }
493
494
    private static final Pattern COLOR_PATTERN3 = Pattern.compile("COLOR[(][ ]*(?<R>[0-9]{1,3})[ ]*,[ ]*(?<G>[0-9]{1,3})[ ]*,[ ]*(?<A>[0-9]{1,3})[ ]*[)]", Pattern.CASE_INSENSITIVE);
495
    private static final Pattern COLOR_PATTERN4 = Pattern.compile("COLOR[(][ ]*(?<R>[0-9]{1,3})[ ]*,[ ]*(?<G>[0-9]{1,3})[ ]*,[ ]*(?<B>[0-9]{1,3})[ ]*,[ ]*(?<A>[0-9]{1,3})[ ]*[)]", Pattern.CASE_INSENSITIVE);
496
497
    public static Color parseColor(SymbolTable symbolTable, String expression, Color defaultValue) {
498
        if( StringUtils.isBlank(expression) ) {
499
            return defaultValue;
500
        }
501
        try {
502
            if( StringUtils.startsWithIgnoreCase(expression, "color(") &&
503
                    StringUtils.endsWithIgnoreCase(expression, ")")) {
504
                Matcher m = COLOR_PATTERN4.matcher(expression);
505
                if( m != null && m.matches()) {
506
                    Color color = new Color(
507
                        Integer.valueOf(m.group("R")),
508
                        Integer.valueOf(m.group("G")),
509
                        Integer.valueOf(m.group("B")),
510
                        Integer.valueOf(m.group("A"))
511
                    );
512
                    return color;
513
                }
514
                m = COLOR_PATTERN3.matcher(expression);
515
                if( m != null && m.matches()) {
516
                    Color color = new Color(
517
                        Integer.valueOf(m.group("R")),
518
                        Integer.valueOf(m.group("G")),
519
                        Integer.valueOf(m.group("B")),
520
                        Integer.valueOf(m.group("A"))
521
                    );
522
                    return color;
523
                }
524
            }
525
            ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
526
            Object x;
527
            x = manager.evaluate(symbolTable, expression);
528
            if( x instanceof Color ) {
529
                return (Color) x;
530
            }
531
            if( x instanceof Number ) {
532
                return new Color(((Number) x).intValue());
533
            }
534
        } catch(Exception ex) {
535
        }
536
        return defaultValue;
537
    }
538
539
    public static Color parseColor(String expression) {
540
        if( StringUtils.isBlank(expression) ) {
541
            throw new IllegalArgumentException("Can't get color from a blank string.");
542
        }
543
        Object x;
544
        try {
545
            if( StringUtils.startsWithIgnoreCase(expression, "color(") &&
546
                    StringUtils.endsWithIgnoreCase(expression, ")")) {
547
                Matcher m = COLOR_PATTERN4.matcher(expression);
548
                if( m != null && m.matches()) {
549
                    Color color = new Color(
550
                        Integer.valueOf(m.group("R")),
551
                        Integer.valueOf(m.group("G")),
552
                        Integer.valueOf(m.group("B")),
553
                        Integer.valueOf(m.group("A"))
554
                    );
555
                    return color;
556
                }
557
                m = COLOR_PATTERN3.matcher(expression);
558
                if( m != null && m.matches()) {
559
                    Color color = new Color(
560
                        Integer.valueOf(m.group("R")),
561
                        Integer.valueOf(m.group("G")),
562
                        Integer.valueOf(m.group("B")),
563
                        Integer.valueOf(m.group("A"))
564
                    );
565
                    return color;
566
                }
567
            }
568
            ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
569
            x = manager.evaluate(null, expression);
570
            if( x instanceof Color ) {
571
                return (Color) x;
572
            }
573
            if( x instanceof Number ) {
574
                return new Color(((Number) x).intValue());
575
            }
576
        } catch(Exception ex) {
577
            IllegalArgumentException ex1 = new IllegalArgumentException("Can't get color from '"+expression+"'.");
578
            ex1.initCause(ex);
579
            throw ex;
580
        }
581
        if( x == null ) {
582
            throw new IllegalArgumentException("Can't get double from '"+expression+"' value is null.");
583
        }
584
        throw new IllegalArgumentException("Can't get double from '"+expression+"' value is a "+x.getClass().getSimpleName()+".");
585
    }
586
587 44163 jjdelcerro
}