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
|
# [Android Components](../../../README.md) > Libraries > JEXL
Javascript Expression Language: Powerful context-based expression parser and evaluator.
This implementation is based on [Mozjexl](https://github.com/mozilla/mozjexl), a fork of Jexl (designed and created at TechnologyAdvice) for use at Mozilla, specifically as a part of SHIELD and Normandy.
Features not supported yet:
* JavaScript object properties (e.g. [String.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length))
* Adding custom operators (binary/unary)
Other implementations:
* [JavaScript](https://github.com/mozilla/mozjexl)
* [Python](https://github.com/mozilla/pyjexl)
## Usage
### Setting up the dependency
Use Gradle to download the library from [maven.mozilla.org](https://maven.mozilla.org/) ([Setup repository](../../../README.md#maven-repository)):
```Groovy
implementation "org.mozilla.components:jexl:{latest-version}
```
### Evaluating expressions
```Kotlin
val jexl = Jexl()
val result = jexl.evaluate("75 > 42")
// evaluate() returns an object of type JexlValue. Calling toKotlin() converts this
// into a matching Kotlin type (in this case a Boolean).
println(result.value) // Prints "true"
```
Often expressions should return a `Boolean`value. In this case `evaluateBooleanExpression` is a helper that always returns a Kotlin `Boolean` and never throws an exception (Returns false).
```Kotlin
val jexl = Jexl()
// "result" has type Boolean and value "true"
val result = jexl.evaluateBooleanExpression("42 + 23 > 50", defaultValue = false)
```
### Unary Operators
| Operation | Symbol |
|-----------|:------:|
| Negate | ! |
### Binary Operators
| Operation | Symbol |
|------------------|:----------------:|
| Add, Concat | + |
| Subtract | - |
| Multiply | * |
| Divide | / |
| Divide and floor | // |
| Modulus | % |
| Power of | ^ |
| Logical AND | && |
| Logical OR | || |
### Comparison
| Comparison | Symbol |
|----------------------------|:------:|
| Equal | == |
| Not equal | != |
| Greater than | > |
| Greater than or equal | >= |
| Less than | < |
| Less than or equal | <= |
| Element in array or string | in |
### Ternary operator
Conditional expressions check to see if the first segment evaluates to a truthy
value. If so, the consequent segment is evaluated. Otherwise, the alternate
is. If the consequent section is missing, the test result itself will be used
instead.
| Expression | Result |
|-------------------------------------|--------|
| `"" ? "Full" : "Empty"` | Empty |
| `"foo" in "foobar" ? "Yes" : "No"` | Yes |
| `{agent: "Archer"}.agent ?: "Kane"` | Archer |
### Native Types
| Type | Examples |
|-----------|:------------------------------:|
| Booleans | `true`, `false` |
| Strings | "Hello \"user\"", 'Hey there!' |
| Integers | 6, -7, 5, -3 |
| Doubles | -7.2, -3.14159 |
| Objects | {hello: "world!"} |
| Arrays | ['hello', 'world!'] |
| Undefined | `undefined` |
The JavaScript implementation of Jexl uses a `Numeric` type. This implementation dynamically casts between `Integer` and `Double` as needed.
### Groups
Parentheses work just how you'd expect them to:
| Expression | Result |
|---------------------------------------|:-------|
| `(83 + 1) / 2` | 42 |
| `1 < 3 && (4 > 2 || 2 > 4)` | true |
### Identifiers
Access variables in the context object by just typing their name. Objects can
be traversed with dot notation, or by using brackets to traverse to a dynamic
property name.
Example context:
```javascript
{
name: {
first: "Malory",
last: "Archer"
},
exes: [
"Nikolai Jakov",
"Len Trexler",
"Burt Reynolds"
],
lastEx: 2
}
```
| Expression | Result |
|---------------------|---------------|
| `name.first` | Malory |
| `name['la' + 'st']` | Archer |
| `exes[2]` | Burt Reynolds |
| `exes[lastEx - 1]` | Len Trexler |
### Collections
Collections, or arrays of objects, can be filtered by including a filter
expression in brackets. Properties of each collection can be referenced by
prefixing them with a leading dot. The result will be an array of the objects
for which the filter expression resulted in a truthy value.
Example context:
```javascript
{
employees: [
{first: 'Sterling', last: 'Archer', age: 36},
{first: 'Malory', last: 'Archer', age: 75},
{first: 'Lana', last: 'Kane', age: 33},
{first: 'Cyril', last: 'Figgis', age: 45},
{first: 'Cheryl', last: 'Tunt', age: 28}
],
retireAge: 62
}
```
| Expression | Result |
|-------------------------------------------------|---------------------------------------------------------------------------------------|
| `employees[.first == 'Sterling']` | [{first: 'Sterling', last: 'Archer', age: 36}] |
| `employees[.last == 'Tu' + 'nt'].first` | Cheryl |
| `employees[.age >= 30 && .age < 40]` | [{first: 'Sterling', last: 'Archer', age: 36},{first: 'Lana', last: 'Kane', age: 33}] |
| `employees[.age >= 30 && .age < 40][.age < 35]` | [{first: 'Lana', last: 'Kane', age: 33}] |
| `employees[.age >= retireAge].first` | Malory |
### Transforms
The power of Jexl is in transforming data. Transform functions take one or more arguments: The value to be transformed, followed by anything else passed to it in the expression.
```Kotlin
val jexl = Jexl()
jexl.addTransform("split") { value, arguments ->
value.toString().split(arguments.first().toString()).toJexlArray()
}
jexl.addTransform("lower") { value, _ ->
value.toString().toLowerCase().toJexl()
}
jexl.addTransform("last") { value, _ ->
(value as JexlArray).values.last()
}
```
| Expression | Result |
|-------------------------------------------------|-----------------------|
| `"Pam Poovey"|lower|split(' ')|first` | poovey |
| `"password==guest"|split('=' + '=')` | ['password', 'guest'] |
### Context
Variable contexts are straightforward Objects that can be accessed
in the expression.
```Kotlin
val context = Context(
"employees" to JexlArray(
JexlObject(
"first" to "Sterling".toJexl(),
"last" to "Archer".toJexl(),
"age" to 36.toJexl()),
JexlObject(
"first" to "Malory".toJexl(),
"last" to "Archer".toJexl(),
"age" to 75.toJexl()),
JexlObject(
"first" to "Malory".toJexl(),
"last" to "Archer".toJexl(),
"age" to 33.toJexl())
)
)
```
| Expression | Result |
|-------------------------------------------------|------------------------------------------------------------------------------|
| `employees[.age >= 30 && .age < 40]` | [{first=Sterling, last=Archer, age=36}, {first=Malory, last=Archer, age=33}] |
| `employees[.age >= 30 && .age < 90][.age < 37]` | [{first=Malory, last=Archer, age=33}] |
## License
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/
|