summaryrefslogtreecommitdiff
path: root/qpid/java/common/src/main/java/org/apache/qpid/filter/ComparisonExpression.java
blob: 2cfb97dc6c8712fb220171d4f1c48bb6c565a7aa (plain)
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
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.qpid.filter;
//
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//

import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;

/**
 * A filter performing a comparison of two objects
 */
public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression
{

    public static BooleanExpression createBetween(Expression value, Expression left, Expression right)
    {
        return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, right));
    }

    public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right)
    {
        return LogicExpression.createOR(createLessThan(value, left), createGreaterThan(value, right));
    }

    private static final HashSet<Character> REGEXP_CONTROL_CHARS = new HashSet<Character>();

    static
    {
        REGEXP_CONTROL_CHARS.add('.');
        REGEXP_CONTROL_CHARS.add('\\');
        REGEXP_CONTROL_CHARS.add('[');
        REGEXP_CONTROL_CHARS.add(']');
        REGEXP_CONTROL_CHARS.add('^');
        REGEXP_CONTROL_CHARS.add('$');
        REGEXP_CONTROL_CHARS.add('?');
        REGEXP_CONTROL_CHARS.add('*');
        REGEXP_CONTROL_CHARS.add('+');
        REGEXP_CONTROL_CHARS.add('{');
        REGEXP_CONTROL_CHARS.add('}');
        REGEXP_CONTROL_CHARS.add('|');
        REGEXP_CONTROL_CHARS.add('(');
        REGEXP_CONTROL_CHARS.add(')');
        REGEXP_CONTROL_CHARS.add(':');
        REGEXP_CONTROL_CHARS.add('&');
        REGEXP_CONTROL_CHARS.add('<');
        REGEXP_CONTROL_CHARS.add('>');
        REGEXP_CONTROL_CHARS.add('=');
        REGEXP_CONTROL_CHARS.add('!');
    }

    static class LikeExpression extends UnaryExpression implements BooleanExpression
    {

        private Pattern likePattern;

        /**
         * @param right
         */
        public LikeExpression(Expression right, String like, int escape)
        {
            super(right);

            StringBuffer regexp = new StringBuffer(like.length() * 2);
            regexp.append("\\A"); // The beginning of the input
            for (int i = 0; i < like.length(); i++)
            {
                char c = like.charAt(i);
                if (escape == (0xFFFF & c))
                {
                    i++;
                    if (i >= like.length())
                    {
                        // nothing left to escape...
                        break;
                    }

                    char t = like.charAt(i);
                    regexp.append("\\x");
                    regexp.append(Integer.toHexString(0xFFFF & t));
                }
                else if (c == '%')
                {
                    regexp.append(".*?"); // Do a non-greedy match
                }
                else if (c == '_')
                {
                    regexp.append("."); // match one
                }
                else if (REGEXP_CONTROL_CHARS.contains(c))
                {
                    regexp.append("\\x");
                    regexp.append(Integer.toHexString(0xFFFF & c));
                }
                else
                {
                    regexp.append(c);
                }
            }

            regexp.append("\\z"); // The end of the input

            likePattern = Pattern.compile(regexp.toString(), Pattern.DOTALL);
        }

        /**
         *  org.apache.activemq.filter.UnaryExpression#getExpressionSymbol()
         */
        public String getExpressionSymbol()
        {
            return "LIKE";
        }

        /**
         *  org.apache.activemq.filter.Expression#evaluate(MessageEvaluationContext)
         */
        public Object evaluate(FilterableMessage message)
        {

            Object rv = this.getRight().evaluate(message);

            if (rv == null)
            {
                return null;
            }

            if (!(rv instanceof String))
            {
                return
                    Boolean.FALSE;
            }

            return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE;
        }

        public boolean matches(FilterableMessage message)
        {
            Object object = evaluate(message);

            return (object != null) && (object == Boolean.TRUE);
        }
    }

    public static BooleanExpression createLike(Expression left, String right, String escape)
    {
        if ((escape != null) && (escape.length() != 1))
        {
            throw new SelectorParsingException(
                "The ESCAPE string literal is invalid.  It can only be one character.  Litteral used: " + escape);
        }

        int c = -1;
        if (escape != null)
        {
            c = 0xFFFF & escape.charAt(0);
        }

        return new LikeExpression(left, right, c);
    }

    public static BooleanExpression createNotLike(Expression left, String right, String escape)
    {
        return UnaryExpression.createNOT(createLike(left, right, escape));
    }

    public static BooleanExpression createInFilter(Expression left, List elements)
    {

        if (!(left instanceof PropertyExpression))
        {
            throw new SelectorParsingException("Expected a property for In expression, got: " + left);
        }

        return UnaryExpression.createInExpression((PropertyExpression) left, elements, false);

    }

    public static BooleanExpression createNotInFilter(Expression left, List elements)
    {

        if (!(left instanceof PropertyExpression))
        {
            throw new SelectorParsingException("Expected a property for In expression, got: " + left);
        }

        return UnaryExpression.createInExpression((PropertyExpression) left, elements, true);

    }

    public static BooleanExpression createIsNull(Expression left)
    {
        return doCreateEqual(left, ConstantExpression.NULL);
    }

    public static BooleanExpression createIsNotNull(Expression left)
    {
        return UnaryExpression.createNOT(doCreateEqual(left, ConstantExpression.NULL));
    }

    public static BooleanExpression createNotEqual(Expression left, Expression right)
    {
        return UnaryExpression.createNOT(createEqual(left, right));
    }

    public static BooleanExpression createEqual(Expression left, Expression right)
    {
        checkEqualOperand(left);
        checkEqualOperand(right);
        checkEqualOperandCompatability(left, right);

        return doCreateEqual(left, right);
    }

    private static BooleanExpression doCreateEqual(Expression left, Expression right)
    {
        return new EqualExpression(left, right);
    }

    public static BooleanExpression createGreaterThan(final Expression left, final Expression right)
    {
        checkLessThanOperand(left);
        checkLessThanOperand(right);

        return new ComparisonExpression(left, right)
            {
                protected boolean asBoolean(int answer)
                {
                    return answer > 0;
                }

                public String getExpressionSymbol()
                {
                    return ">";
                }
            };
    }

    public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right)
    {
        checkLessThanOperand(left);
        checkLessThanOperand(right);

        return new ComparisonExpression(left, right)
            {
                protected boolean asBoolean(int answer)
                {
                    return answer >= 0;
                }

                public String getExpressionSymbol()
                {
                    return ">=";
                }
            };
    }

    public static BooleanExpression createLessThan(final Expression left, final Expression right)
    {
        checkLessThanOperand(left);
        checkLessThanOperand(right);

        return new ComparisonExpression(left, right)
            {

                protected boolean asBoolean(int answer)
                {
                    return answer < 0;
                }

                public String getExpressionSymbol()
                {
                    return "<";
                }

            };
    }

    public static BooleanExpression createLessThanEqual(final Expression left, final Expression right)
    {
        checkLessThanOperand(left);
        checkLessThanOperand(right);

        return new ComparisonExpression(left, right)
            {

                protected boolean asBoolean(int answer)
                {
                    return answer <= 0;
                }

                public String getExpressionSymbol()
                {
                    return "<=";
                }
            };
    }

    /**
     * Only Numeric expressions can be used in >, >=, < or <= expressions.s
     *
     * @param expr
     */
    public static void checkLessThanOperand(Expression expr)
    {
        if (expr instanceof ConstantExpression)
        {
            Object value = ((ConstantExpression) expr).getValue();
            if (value instanceof Number)
            {
                return;
            }

            // Else it's boolean or a String..
            throw new SelectorParsingException("Value '" + expr + "' cannot be compared.");
        }

        if (expr instanceof BooleanExpression)
        {
            throw new SelectorParsingException("Value '" + expr + "' cannot be compared.");
        }
    }

    /**
     * Validates that the expression can be used in == or <> expression.
     * Cannot not be NULL TRUE or FALSE literals.
     *
     * @param expr
     */
    public static void checkEqualOperand(Expression expr)
    {
        if (expr instanceof ConstantExpression)
        {
            Object value = ((ConstantExpression) expr).getValue();
            if (value == null)
            {
                throw new SelectorParsingException("'" + expr + "' cannot be compared.");
            }
        }
    }

    /**
     *
     * @param left
     * @param right
     */
    private static void checkEqualOperandCompatability(Expression left, Expression right)
    {
        if ((left instanceof ConstantExpression) && (right instanceof ConstantExpression))
        {
            if ((left instanceof BooleanExpression) && !(right instanceof BooleanExpression))
            {
                throw new SelectorParsingException("'" + left + "' cannot be compared with '" + right + "'");
            }
        }
    }

    /**
     * @param left
     * @param right
     */
    public ComparisonExpression(Expression left, Expression right)
    {
        super(left, right);
    }

    public Object evaluate(FilterableMessage message)
    {
        Comparable lv = (Comparable) getLeft().evaluate(message);
        if (lv == null)
        {
            return null;
        }

        Comparable rv = (Comparable) getRight().evaluate(message);
        if (rv == null)
        {
            return null;
        }

        return compare(lv, rv);
    }

    protected Boolean compare(Comparable lv, Comparable rv)
    {
        Class lc = lv.getClass();
        Class rc = rv.getClass();
        // If the the objects are not of the same type,
        // try to convert up to allow the comparison.
        if (lc != rc)
        {
            if (lc == Byte.class)
            {
                if (rc == Short.class)
                {
                    lv = ((Number) lv).shortValue();
                }
                else if (rc == Integer.class)
                {
                    lv = ((Number) lv).intValue();
                }
                else if (rc == Long.class)
                {
                    lv = ((Number) lv).longValue();
                }
                else if (rc == Float.class)
                {
                    lv = ((Number) lv).floatValue();
                }
                else if (rc == Double.class)
                {
                    lv = ((Number) lv).doubleValue();
                }
                else
                {
                    return Boolean.FALSE;
                }
            }
            else if (lc == Short.class)
            {
                if (rc == Integer.class)
                {
                    lv = ((Number) lv).intValue();
                }
                else if (rc == Long.class)
                {
                    lv = ((Number) lv).longValue();
                }
                else if (rc == Float.class)
                {
                    lv = ((Number) lv).floatValue();
                }
                else if (rc == Double.class)
                {
                    lv = ((Number) lv).doubleValue();
                }
                else
                {
                    return Boolean.FALSE;
                }
            }
            else if (lc == Integer.class)
            {
                if (rc == Long.class)
                {
                    lv = ((Number) lv).longValue();
                }
                else if (rc == Float.class)
                {
                    lv = ((Number) lv).floatValue();
                }
                else if (rc == Double.class)
                {
                    lv = ((Number) lv).doubleValue();
                }
                else
                {
                    return Boolean.FALSE;
                }
            }
            else if (lc == Long.class)
            {
                if (rc == Integer.class)
                {
                    rv = ((Number) rv).longValue();
                }
                else if (rc == Float.class)
                {
                    lv = ((Number) lv).floatValue();
                }
                else if (rc == Double.class)
                {
                    lv = ((Number) lv).doubleValue();
                }
                else
                {
                    return Boolean.FALSE;
                }
            }
            else if (lc == Float.class)
            {
                if (rc == Integer.class)
                {
                    rv = ((Number) rv).floatValue();
                }
                else if (rc == Long.class)
                {
                    rv = ((Number) rv).floatValue();
                }
                else if (rc == Double.class)
                {
                    lv = ((Number) lv).doubleValue();
                }
                else
                {
                    return Boolean.FALSE;
                }
            }
            else if (lc == Double.class)
            {
                if (rc == Integer.class)
                {
                    rv = ((Number) rv).doubleValue();
                }
                else if (rc == Long.class)
                {
                    rv = ((Number) rv).doubleValue();
                }
                else if (rc == Float.class)
                {
                    rv = ((Number) rv).doubleValue();
                }
                else
                {
                    return Boolean.FALSE;
                }
            }
            else
            {
                return Boolean.FALSE;
            }
        }

        return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE;
    }

    protected abstract boolean asBoolean(int answer);

    public boolean matches(FilterableMessage message)
    {
        Object object = evaluate(message);

        return (object != null) && (object == Boolean.TRUE);
    }

    private static class EqualExpression extends ComparisonExpression
    {
        public EqualExpression(final Expression left, final Expression right)
        {
            super(left, right);
        }

        public Object evaluate(FilterableMessage message)
        {
            Object lv = getLeft().evaluate(message);
            Object rv = getRight().evaluate(message);

            // Iff one of the values is null
            if ((lv == null) ^ (rv == null))
            {
                return Boolean.FALSE;
            }

            if ((lv == rv) || lv.equals(rv))
            {
                return Boolean.TRUE;
            }

            if ((lv instanceof Comparable) && (rv instanceof Comparable))
            {
                return compare((Comparable) lv, (Comparable) rv);
            }

            return Boolean.FALSE;
        }

        protected boolean asBoolean(int answer)
        {
            return answer == 0;
        }

        public String getExpressionSymbol()
        {
            return "=";
        }
    }
}