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 @ 45789

History | View | Annotate | Download (21.8 KB)

1
package org.gvsig.expressionevaluator;
2

    
3
import java.awt.Color;
4
import java.io.File;
5
import java.net.MalformedURLException;
6
import java.net.URL;
7
import java.util.List;
8
import java.util.regex.Matcher;
9
import java.util.regex.Pattern;
10
import org.apache.commons.lang3.ArrayUtils;
11
import org.apache.commons.lang3.StringUtils;
12
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
13
import static org.gvsig.expressionevaluator.ExpressionEvaluatorManager.DYNAMICTEXT_ENDTAG;
14
import static org.gvsig.expressionevaluator.ExpressionEvaluatorManager.DYNAMICTEXT_STARTTAG;
15
import org.gvsig.expressionevaluator.spi.DynObjectSymbolTable;
16
import org.gvsig.tools.dataTypes.DataTypeUtils;
17
import org.gvsig.tools.dynobject.DynObject;
18
import org.gvsig.tools.util.ListBuilder;
19

    
20
/**
21
 *
22
 * @author gvSIG Team
23
 */
24
@SuppressWarnings("UseSpecificCatch")
25
public class ExpressionUtils {
26

    
27
    public static boolean isEmpty(Expression expression) {
28
        return expression == null || expression.isEmpty();
29
    }
30

    
31
    public static boolean isPhraseEmpty(Expression expression) {
32
        return expression == null || expression.isPhraseEmpty();
33
    }
34
    
35
    public static Expression defaultIfEmpty(Expression expression, Expression defaultValue) {
36
        if( expression==null || expression.isEmpty() ) {
37
            return defaultValue;
38
        }
39
        return expression;
40
    }
41
    
42
    public static Expression defaultNullIfEmpty(Expression expression) {
43
        if( expression==null || expression.isEmpty() ) {
44
            return null;
45
        }
46
        return expression;
47
    }
48
    
49
    public static Expression defaultIfPhraseEmpty(Expression expression, Expression defaultValue) {
50
        if( expression==null || expression.isPhraseEmpty() ) {
51
            return defaultValue;
52
        }
53
        return expression;
54
    }
55

    
56
    public static Expression defaultNullIfPhraseEmpty(Expression expression) {
57
        if( expression==null || expression.isPhraseEmpty() ) {
58
            return null;
59
        }
60
        return expression;
61
    }
62
   
63
    public static Expression createExpression() {
64
        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
65
        return expression;
66
    }
67

    
68
    public static Expression createExpression(String phrase) {
69
        if( StringUtils.isBlank(phrase) ) {
70
            return null;
71
        }
72
        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
73
        expression.setPhrase(phrase);
74
        return expression;
75
    }
76

    
77
//    public static Expression createExpression(String phrase, String code, Script... scripts) {
78
//        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
79
//        expression.setPhrase(phrase);
80
//        expression.setUserScript(code);
81
//        for (Script script : scripts) {
82
//            expression.addScript(script);
83
//        }
84
//        return expression;
85
//    }
86
//
87
//    public static Expression createExpression(String phrase, String code, String languaje, Script... scripts) {
88
//        Expression expression = ExpressionEvaluatorLocator.getManager().createExpression();
89
//        expression.setPhrase(phrase);
90
//        expression.setUserScript(code, languaje);
91
//        for (Script script : scripts) {
92
//            expression.addScript(script);
93
//        }
94
//        return expression;
95
//    }
96

    
97
    public static ExpressionBuilder createExpressionBuilder() {
98
        ExpressionBuilder builder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder();
99
        return builder;
100
    }
101

    
102
    public static Code compile(String expression) {
103
        if( StringUtils.isBlank(expression) ) {
104
            return null;
105
        }
106
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
107
        Code code = manager.compile(expression);
108
        return code;
109
    }
110

    
111
    public static Object evaluate(String expression) {
112
        return evaluate(null, expression);
113
    }
114
    
115
    public static Object evaluate(SymbolTable symbolTable, String expression) {
116
        if( StringUtils.isBlank(expression) ) {
117
            return null;
118
        }
119
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
120
        Object x = manager.evaluate(symbolTable, expression);
121
        return x;
122
    }
123

    
124
    public static Object evaluate(SymbolTable symbolTable, Code code) {
125
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
126
        Object x = manager.evaluate(symbolTable, code);
127
        return x;
128
    }
129

    
130
    public static Code optimize(SymbolTable symbolTable, Code code) {
131
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
132
        code = manager.optimize(symbolTable, code);
133
        return code;
134
    }
135

    
136
    public static String toString(Value value, Formatter formatter) {
137
        if( value == null ) {
138
            return null;
139
        }
140
        if( formatter==null ) {
141
            ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
142
            formatter = manager.getExpressionBuilderFormatter();
143
        }
144
        return value.toString(formatter);
145
    }
146

    
147
    public static String toString(Value value) {
148
      return toString(value, null);
149
    }
150

    
151
    public static String toString(Code code, Formatter formatter) {
152
        if( code == null ) {
153
            return null;
154
        }
155
        if( formatter==null ) {
156
            formatter = Code.EMPTY_FORMATTER;
157
        }
158
        return code.toString(formatter);
159
    }
160

    
161
    public static String toString(Code code) {
162
      return toString(code, null);
163
    }
164

    
165
    public static Expression createExpressionFromJSON(String json) {
166
        Expression expression = ExpressionUtils.createExpression();
167
        expression.fromJSON(json);
168
        return expression;
169
    }
170

    
171
    public static MutableSymbolTable createSymbolTable() {
172
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
173
        MutableSymbolTable symbolTable = manager.createSymbolTable();
174
        return symbolTable;
175
    }
176
    
177
    public static MutableSymbolTable createSymbolTable(DynObject obj) {
178
        DynObjectSymbolTable symbolTable = new DynObjectSymbolTable("object",obj);
179
        return symbolTable;
180
    }
181
    
182
    public static MutableSymbolTable createSymbolTable(String name, DynObject obj) {
183
        DynObjectSymbolTable symbolTable = new DynObjectSymbolTable(name, obj);
184
        return symbolTable;
185
    }
186
    
187
    public static String surroundByDynamicTextTag(String source) {
188
        return surroundByDynamicTextTag(source, true);
189
    }
190
    
191
    public static String surroundByDynamicTextTag(String source, boolean insert) {
192
        if( source==null ) {
193
            return null;
194
        }
195
        if( insert ) {
196
            return DYNAMICTEXT_STARTTAG+ "=" + source + DYNAMICTEXT_ENDTAG;
197
        }
198
        return DYNAMICTEXT_STARTTAG + source + DYNAMICTEXT_ENDTAG;
199
    }
200
    
201
    public static boolean isDynamicText(String source) {
202
        if( StringUtils.isBlank(source) || !source.contains(DYNAMICTEXT_STARTTAG) ) {
203
          return false;
204
        }
205
        String[] sources = StringUtils.substringsBetween(source, DYNAMICTEXT_STARTTAG, DYNAMICTEXT_ENDTAG);
206
        if( ArrayUtils.isEmpty(sources) ) {
207
            return false;
208
        }
209
        return true;
210
    }
211

    
212
    public static String evaluateDynamicText(String source) {
213
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
214
        return manager.evaluateDynamicText(source);
215
    }
216
    
217
    public static String evaluateDynamicText(SymbolTable symbolTable, String source) {
218
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
219
        return manager.evaluateDynamicText(symbolTable, source);
220
    }
221

    
222
    public static File evaluateFilename(File source) {
223
        return evaluateFilename(null, source);
224
    }
225

    
226
    public static URL evaluateURL(URL source) {
227
        return evaluateURL(null, source);
228
    }
229

    
230
    public static boolean isDynamicFilename(File source) {
231
        if( source == null ) {
232
            return false;
233
        }
234
        return isDynamicText(source.getPath());
235
    }
236

    
237
    public static boolean isDynamicURL(URL source) {
238
        if( source == null ) {
239
            return false;
240
        }
241
        return isDynamicText(source.toString());
242
    }
243

    
244
    public static File createDynamicFile(Value builder) {
245
        File f = new File(surroundByDynamicTextTag(builder.toString()));
246
        return f;
247
    }
248
    
249
    public static File createDynamicFile(String expression) {
250
        File f = new File(surroundByDynamicTextTag(expression));
251
        return f;
252
    }
253
    
254
    @SuppressWarnings("StringEquality")
255
    public static File evaluateFilename(SymbolTable symbolTable, File source) {
256
        String src =  source.getPath();
257
        if( !isDynamicText(src) ) {
258
            return source;
259
        }
260
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
261
        String r = manager.evaluateDynamicText(symbolTable, src);
262
        if( r == src ) { // !!! I compare that it is the same pointer, it is what I want.
263
            return source;
264
        }
265
        File f = new File(r);
266
        return f;
267
    }
268

    
269
    @SuppressWarnings("StringEquality")
270
    public static URL evaluateURL(SymbolTable symbolTable, URL source) {
271
        String src =  source.toString();
272
        if( !isDynamicText(src) ) {
273
            return source;
274
        }
275
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
276
        String r = manager.evaluateDynamicText(symbolTable, src);
277
        if( r == src ) { // !!! I compare that it is the same pointer, it is what I want.
278
            return source;
279
        }
280
        try {
281
            URL url = new URL(r);
282
            return url;
283
        } catch (MalformedURLException ex) {
284
            return source;
285
        }
286
    }
287

    
288
    public static int parseInt(String s) throws NumberFormatException {
289
        if( StringUtils.isBlank(s) ) {
290
            throw new NumberFormatException("Can't get integer from a blank string.");
291
        }
292
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
293
        SymbolTable symbolTable = null; //manager.getInmutableSymbolTable();
294
        Object x;
295
        try {
296
            x = manager.evaluate(symbolTable, s);
297
            if( x instanceof Number ) {
298
                return ((Number) x).intValue();
299
            }
300
        } catch(Exception ex) {
301
            NumberFormatException ex1 = new NumberFormatException("Can't get integer from '"+s+"'.");
302
            ex1.initCause(ex);
303
            throw ex;
304
        }
305
        if( x == null ) {
306
            throw new NumberFormatException("Can't get integer from '"+s+"' value is null.");
307
        }
308
        throw new NumberFormatException("Can't get integer from '"+s+"' value is a "+x.getClass().getSimpleName()+".");
309
    }
310

    
311
    public static long parseLong(String s) throws NumberFormatException {
312
        if( StringUtils.isBlank(s) ) {
313
            throw new NumberFormatException("Can't get long from a blank string.");
314
        }
315
        try {
316
            int value = Integer.parseInt(s);
317
            return value;
318
        } catch(Exception ex) {
319
            
320
        }
321
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
322
        SymbolTable symbolTable = null; //manager.getInmutableSymbolTable();
323
        Object x;
324
        try {
325
            x = manager.evaluate(symbolTable, s);
326
            if( x instanceof Number ) {
327
                return ((Number) x).longValue();
328
            }
329
        } catch(Exception ex) {
330
            NumberFormatException ex1 = new NumberFormatException("Can't get long from '"+s+"'.");
331
            ex1.initCause(ex);
332
            throw ex;
333
        }
334
        if( x == null ) {
335
            throw new NumberFormatException("Can't get long from '"+s+"' value is null.");
336
        }
337
        throw new NumberFormatException("Can't get long from '"+s+"' value is a "+x.getClass().getSimpleName()+".");
338
    }
339

    
340
    public static double parseDouble(String s) throws NumberFormatException {
341
        if( StringUtils.isBlank(s) ) {
342
            throw new NumberFormatException("Can't get double from a blank string.");
343
        }
344
        try {
345
            double value = Double.parseDouble(s);
346
            return value;
347
        } catch(Exception ex) {
348
            
349
        }
350
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
351
        SymbolTable symbolTable = null; //manager.getInmutableSymbolTable();
352
        Object x;
353
        try {
354
            x = manager.evaluate(symbolTable, s);
355
            if( x instanceof Number ) {
356
                return ((Number) x).doubleValue();
357
            }
358
        } catch(Exception ex) {
359
            NumberFormatException ex1 = new NumberFormatException("Can't get double from '"+s+"'.");
360
            ex1.initCause(ex);
361
            throw ex;
362
        }
363
        if( x == null ) {
364
            throw new NumberFormatException("Can't get double from '"+s+"' value is null.");
365
        }
366
        throw new NumberFormatException("Can't get double from '"+s+"' value is a "+x.getClass().getSimpleName()+".");
367
    }
368

    
369
    public static Compiler createCompiler() {
370
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
371
        Compiler compiler = manager.createCompiler();
372
        return compiler;
373
    }
374

    
375
    public static Interpreter createInterpreter() {
376
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
377
        Interpreter interpreter = manager.createInterpreter();
378
        return interpreter;
379
    }
380

    
381
    public static Optimizer createOptimizer() {
382
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
383
        Optimizer optimizer = manager.createOptimizer();
384
        return optimizer;
385
    }
386

    
387
    public static String repr(Object value) {
388
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
389
        ReprMethod method = manager.getReprMethod(value);
390
        return method.repr(value);
391
    }
392
    
393
    public static CodeBuilder createCodeBuilder() {
394
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
395
        return manager.createCodeBuilder();
396
    }
397
    
398
    private static final List<String> TRUE_VALUES = ListBuilder.create("true","on","t", "1", "-1" );
399
    private static final List<String> FALSE_VALUES =  ListBuilder.create("false","off","f", "0" );
400
    
401
    public static boolean parseBoolean(SymbolTable symbolTable, String expression, boolean defaultValue) {
402
        expression = StringUtils.trimToNull(expression);
403
        if( StringUtils.isBlank(expression) ) {
404
            return defaultValue;
405
        }
406
        if( TRUE_VALUES.contains(expression.toLowerCase()))  {
407
            return true;
408
        }
409
        if( FALSE_VALUES.contains(expression.toLowerCase()))  {
410
            return false;
411
        }
412
        try {
413
            return (boolean) ExpressionUtils.evaluate(symbolTable, expression);
414
        } catch(Exception ex) {
415
            return defaultValue;
416
        }
417
    }
418
    
419
    public static boolean parseBoolean(String expression) {
420
        expression = StringUtils.trimToNull(expression);
421
        if( StringUtils.isBlank(expression) ) {
422
            throw new IllegalArgumentException("Can't get boolean from a blank string.");
423
        }
424
        if( TRUE_VALUES.contains(expression.toLowerCase()))  {
425
            return true;
426
        }
427
        if( FALSE_VALUES.contains(expression.toLowerCase()))  {
428
            return false;
429
        }
430
        Object x;
431
        try {
432
            x = ExpressionUtils.evaluate(null, expression);
433
            return (boolean) x;
434
        } catch(Exception ex) {
435
            IllegalArgumentException ex1 = new IllegalArgumentException("Can't get boolean from '"+expression+"'.");
436
            ex1.initCause(ex);
437
            throw ex;
438
        }
439
    }
440
    
441
    public static int parseInt(SymbolTable symbolTable, String expression, int defaultValue) {
442
        if( StringUtils.isBlank(expression) ) {
443
            return defaultValue;
444
        }
445
        try {
446
            int value = Integer.parseInt(expression);
447
            return value;
448
        } catch(Exception ex) {
449
            
450
        }
451
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
452
        Object x;
453
        try {
454
            x = manager.evaluate(symbolTable, expression);
455
            if( x instanceof Number ) {
456
                return ((Number) x).intValue();
457
            }
458
        } catch(Exception ex) {
459
        }
460
        return defaultValue;
461
    }
462
    
463
    public static long parseLong(SymbolTable symbolTable, String expression, long defaultValue) {
464
        if( StringUtils.isBlank(expression) ) {
465
            return defaultValue;
466
        }
467
        try {
468
            int value = Integer.parseInt(expression);
469
            return value;
470
        } catch(Exception ex) {
471
            
472
        }
473
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
474
        Object x;
475
        try {
476
            x = manager.evaluate(symbolTable, expression);
477
            if( x instanceof Number ) {
478
                return ((Number) x).longValue();
479
            }
480
        } catch(Exception ex) {
481
        }
482
        return defaultValue;
483
    }
484
    
485
    public static double parseDouble(SymbolTable symbolTable, String expression, double defaultValue) {
486
        if( StringUtils.isBlank(expression) ) {
487
            return defaultValue;
488
        }
489
        try {
490
            double value = Double.parseDouble(expression);
491
            return value;
492
        } catch(Exception ex) {
493
            
494
        }
495
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
496
        Object x;
497
        try {
498
            x = manager.evaluate(symbolTable, expression);
499
            if( x instanceof Number ) {
500
                return ((Number) x).doubleValue();
501
            }
502
        } catch(Exception ex) {
503
        }
504
        return defaultValue;
505
    }
506
    
507
    private static final Pattern COLOR_PATTERN3 = Pattern.compile("COLOR[(][ ]*(?<R>[0-9]{1,3})[ ]*,[ ]*(?<G>[0-9]{1,3})[ ]*,[ ]*(?<B>[0-9]{1,3})[ ]*[)]", Pattern.CASE_INSENSITIVE);
508
    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);
509

    
510
    public static Color parseColor(SymbolTable symbolTable, String expression, Color defaultValue) {
511
        if( StringUtils.isBlank(expression) ) {
512
            return defaultValue;
513
        }
514
        try {
515
            Color color;
516
            if( StringUtils.startsWithIgnoreCase(expression, "color(") && 
517
                    StringUtils.endsWithIgnoreCase(expression, ")")) {
518
                Matcher m = COLOR_PATTERN4.matcher(expression);
519
                if( m != null && m.matches()) {
520
                    color = new Color(
521
                        Integer.valueOf(m.group("R")),
522
                        Integer.valueOf(m.group("G")),
523
                        Integer.valueOf(m.group("B")),
524
                        Integer.valueOf(m.group("A"))
525
                    );
526
                    return color;
527
                }
528
                m = COLOR_PATTERN3.matcher(expression);
529
                if( m != null && m.matches()) {
530
                    color = new Color(
531
                        Integer.valueOf(m.group("R")),
532
                        Integer.valueOf(m.group("G")),
533
                        Integer.valueOf(m.group("B"))
534
                    );
535
                    return color;
536
                }
537
            }
538
            ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
539
            Object x;
540
            x = manager.evaluate(symbolTable, expression);
541
            if( x instanceof Color ) {
542
                return (Color) x;
543
            }
544
            color = (Color) DataTypeUtils.coerce(DataTypes.COLOR, expression, null);
545
            if( color != null ) {
546
                return color;
547
            }
548
        } catch(Exception ex) {
549
        }
550
        return defaultValue;
551
    }
552
    
553
    public static Color parseColor(String expression) {
554
        if( StringUtils.isBlank(expression) ) {
555
            throw new IllegalArgumentException("Can't get color from a blank string.");
556
        }
557
        Object x;
558
        try {
559
            if( StringUtils.startsWithIgnoreCase(expression, "color(") && 
560
                    StringUtils.endsWithIgnoreCase(expression, ")")) {
561
                Matcher m = COLOR_PATTERN4.matcher(expression);
562
                if( m != null && m.matches()) {
563
                    Color color = new Color(
564
                        Integer.valueOf(m.group("R")),
565
                        Integer.valueOf(m.group("G")),
566
                        Integer.valueOf(m.group("B")),
567
                        Integer.valueOf(m.group("A"))
568
                    );
569
                    return color;
570
                }
571
                m = COLOR_PATTERN3.matcher(expression);
572
                if( m != null && m.matches()) {
573
                    Color color = new Color(
574
                        Integer.valueOf(m.group("R")),
575
                        Integer.valueOf(m.group("G")),
576
                        Integer.valueOf(m.group("B")),
577
                        Integer.valueOf(m.group("A"))
578
                    );
579
                    return color;
580
                }
581
            }
582
            ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
583
            x = manager.evaluate(null, expression);
584
            if( x instanceof Color ) {
585
                return (Color) x;
586
            }
587
            if( x instanceof Number ) {
588
                return new Color(((Number) x).intValue());
589
            }
590
        } catch(Exception ex) {
591
            IllegalArgumentException ex1 = new IllegalArgumentException("Can't get color from '"+expression+"'.");
592
            ex1.initCause(ex);
593
            throw ex;
594
        }
595
        if( x == null ) {
596
            throw new IllegalArgumentException("Can't get double from '"+expression+"' value is null.");
597
        }
598
        throw new IllegalArgumentException("Can't get double from '"+expression+"' value is a "+x.getClass().getSimpleName()+".");
599
    }
600
    
601
}
602