summaryrefslogtreecommitdiffstats
path: root/java/src/main/java/com/redhat/IdPMapping/Token.java
blob: 9b835cb9032ede2480cd925452cacf3f40856a59 (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
/*
 * Copyright (C) 2014 Red Hat
 * All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.aaa.idpmapping;



import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

enum TokenStorageType {
  UNKNOWN, CONSTANT, VARIABLE
}


enum TokenType {
  STRING, // java String
  ARRAY, // java List
  MAP, // java Map
  INTEGER, // java Long
  BOOLEAN, // java Boolean
  NULL, // java null
  REAL, // java Double
  UNKNOWN, // undefined
}


/**
 * Rule statements can contain variables or constants, this class
 * encapsulates those values, enforces type handling and supports
 * reading and writing of those values.
 *
 * Technically at the syntactic level these are not tokens. A token
 * would have finer granularity such as identifier, operator, etc. I
 * just couldn't think of a better name for how they're used here and
 * thought token was a reasonable compromise as a name.
 *
 * @author John Dennis <jdennis@redhat.com>
 */

class Token {

  /*
   * Regexp to identify a variable beginning with $ Supports array notation, e.g. $foo[bar] Optional
   * delimiting braces may be used to separate variable from surrounding text.
   * 
   * Examples: $foo ${foo} $foo[bar] ${foo[bar] where foo is the variable name and bar is the array
   * index.
   * 
   * Identifer is any alphabetic followed by alphanumeric or underscore
   */
  private static final String VARIABLE_PAT = "(?<!\\\\)\\$" + // non-escaped $
                                                              // sign
      "\\{?" + // optional delimiting brace
      "([a-zA-Z][a-zA-Z0-9_]*)" + // group 1: variable name
      "(\\[" + // group 2: optional index
      "([a-zA-Z0-9_]+)" + // group 3: array index
      "\\])?" + // end optional index
      "\\}?"; // optional delimiting brace
  public static final Pattern VARIABLE_RE = Pattern.compile(VARIABLE_PAT);
  /*
   * Requires only a variable to be present in the string but permits leading and trailing
   * whitespace.
   */
  private static final String VARIABLE_ONLY_PAT = "^\\s*" + VARIABLE_PAT + "\\s*$";
  public static final Pattern VARIABLE_ONLY_RE = Pattern.compile(VARIABLE_ONLY_PAT);

  private Object value = null;

  public Map<String, Object> namespace = null;
  public TokenStorageType storageType = TokenStorageType.UNKNOWN;
  public TokenType type = TokenType.UNKNOWN;
  public String name = null;
  public String index = null;

  Token(Object input, Map<String, Object> namespace) {
    this.namespace = namespace;
    if (input instanceof String) {
      parseVariable((String) input);
      if (this.storageType == TokenStorageType.CONSTANT) {
        this.value = input;
        this.type = classify(input);
      }
    } else {
      this.storageType = TokenStorageType.CONSTANT;
      this.value = input;
      this.type = classify(input);
    }
  }

  @Override
  public String toString() {
    if (this.storageType == TokenStorageType.CONSTANT) {
      return String.format("%s", this.value);
    } else if (this.storageType == TokenStorageType.VARIABLE) {
      if (this.index == null) {
        return String.format("$%s", this.name);
      } else {
        return String.format("$%s[%s]", this.name, this.index);
      }
    } else {
      return "UNKNOWN";
    }
  }

  void parseVariable(String string) {
    Matcher matcher = VARIABLE_ONLY_RE.matcher(string);
    if (matcher.find()) {
      String name = matcher.group(1);
      String index = matcher.group(3);

      this.storageType = TokenStorageType.VARIABLE;
      this.name = name;
      this.index = index;
    } else {
      this.storageType = TokenStorageType.CONSTANT;
    }
  }

  public static TokenType classify(Object value) {
    TokenType tokenType = TokenType.UNKNOWN;
    // ordered by expected occurrence
    if (value instanceof String) {
      tokenType = TokenType.STRING;
    } else if (value instanceof List) {
      tokenType = TokenType.ARRAY;
    } else if (value instanceof Map) {
      tokenType = TokenType.MAP;
    } else if (value instanceof Long) {
      tokenType = TokenType.INTEGER;
    } else if (value instanceof Boolean) {
      tokenType = TokenType.BOOLEAN;
    } else if (value == null) {
      tokenType = TokenType.NULL;
    } else if (value instanceof Double) {
      tokenType = TokenType.REAL;
    } else {
      throw new InvalidRuleException(String.format(
          "Type must be String, Long, Double, Boolean, List, Map, or null, not %s", value
              .getClass().getSimpleName(), value));
    }
    return tokenType;
  }

  Object get() {
    return get(null);
  }

  Object get(Object index) {
    Object base = null;

    if (this.storageType == TokenStorageType.CONSTANT) {
      return this.value;
    }

    if (this.namespace.containsKey(this.name)) {
      base = this.namespace.get(this.name);
    } else {
      throw new UndefinedValueException(String.format("variable '%s' not defined", this.name));
    }

    if (index == null) {
      index = this.index;
    }

    if (index == null) { // scalar types
      value = base;
    } else {
      if (base instanceof List) {
        @SuppressWarnings("unchecked")
        List<Object> list = (List<Object>) base;
        Integer idx = null;

        if (index instanceof Long) {
          idx = new Integer(((Long) index).intValue());
        } else if (index instanceof String) {
          try {
            idx = new Integer((String) index);
          } catch (NumberFormatException e) {
            throw new InvalidTypeException(
                String
                    .format(
                        "variable '%s' is an array indexed by '%s', however the index cannot be converted to an integer",
                        this.name, index));
          }
        } else {
          throw new InvalidTypeException(
              String
                  .format(
                      "variable '%s' is an array indexed by '%s', however the index must be an integer or string not %s",
                      this.name, index, index.getClass().getSimpleName()));
        }

        try {
          value = list.get(idx);
        } catch (IndexOutOfBoundsException e) {
          throw new UndefinedValueException(
              String
                  .format(
                      "variable '%s' is an array of size %d indexed by '%s', however the index is out of bounds",
                      this.name, list.size(), idx));
        }
      } else if (base instanceof Map) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) base;
        String idx = null;
        if (index instanceof String) {
          idx = (String) index;
        } else {
          throw new InvalidTypeException(String.format(
              "variable '%s' is a map indexed by '%s', however the index must be a string not %s",
              this.name, index, index.getClass().getSimpleName()));
        }
        if (!map.containsKey(idx)) {
          throw new UndefinedValueException(String.format(
              "variable '%s' is a map indexed by '%s', however the index does not exist",
              this.name, index));
        }
        value = map.get(idx);
      } else {
        throw new InvalidTypeException(String.format(
            "variable '%s' is indexed by '%s', variable must be an array or map, not %s",
            this.name, index, base.getClass().getSimpleName()));

      }
    }
    this.type = classify(value);
    return value;
  }

  void set(Object value) {
    set(value, null);
  }

  void set(Object value, Object index) {

    if (this.storageType == TokenStorageType.CONSTANT) {
      throw new InvalidTypeException("cannot assign to a constant");
    }

    if (index == null) {
      index = this.index;
    }

    if (index == null) { // scalar types
      this.namespace.put(this.name, value);
    } else {
      Object base = null;

      if (this.namespace.containsKey(this.name)) {
        base = this.namespace.get(this.name);
      } else {
        throw new UndefinedValueException(String.format("variable '%s' not defined", this.name));
      }

      if (base instanceof List) {
        @SuppressWarnings("unchecked")
        List<Object> list = (List<Object>) base;
        Integer idx = null;

        if (index instanceof Long) {
          idx = new Integer(((Long) index).intValue());
        } else if (index instanceof String) {
          try {
            idx = new Integer((String) index);
          } catch (NumberFormatException e) {
            throw new InvalidTypeException(
                String
                    .format(
                        "variable '%s' is an array indexed by '%s', however the index cannot be converted to an integer",
                        this.name, index));
          }
        } else {
          throw new InvalidTypeException(
              String
                  .format(
                      "variable '%s' is an array indexed by '%s', however the index must be an integer or string not %s",
                      this.name, index, index.getClass().getSimpleName()));
        }

        try {
          value = list.set(idx, value);
        } catch (IndexOutOfBoundsException e) {
          throw new UndefinedValueException(
              String
                  .format(
                      "variable '%s' is an array of size %d indexed by '%s', however the index is out of bounds",
                      this.name, list.size(), idx));
        }
      } else if (base instanceof Map) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) base;
        String idx = null;
        if (index instanceof String) {
          idx = (String) index;
        } else {
          throw new InvalidTypeException(String.format(
              "variable '%s' is a map indexed by '%s', however the index must be a string not %s",
              this.name, index, index.getClass().getSimpleName()));
        }
        if (!map.containsKey(idx)) {
          throw new UndefinedValueException(String.format(
              "variable '%s' is a map indexed by '%s', however the index does not exist",
              this.name, index));
        }
        value = map.put(idx, value);
      } else {
        throw new InvalidTypeException(String.format(
            "variable '%s' is indexed by '%s', variable must be an array or map, not %s",
            this.name, index, base.getClass().getSimpleName()));

      }
    }
  }

  public Object load() {
    this.value = get();
    return this.value;
  }

  public Object load(Object index) {
    this.value = get(index);
    return this.value;
  }

  public String getStringValue() {
    if (this.type == TokenType.STRING) {
      return (String) this.value;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.STRING, this.type));
    }
  }

  public List<Object> getListValue() {
    if (this.type == TokenType.ARRAY) {
      @SuppressWarnings("unchecked")
      List<Object> list = (List<Object>) this.value;
      return list;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.ARRAY, this.type));
    }
  }

  public Map<String, Object> getMapValue() {
    if (this.type == TokenType.MAP) {
      @SuppressWarnings("unchecked")
      Map<String, Object> map = (Map<String, Object>) this.value;
      return map;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.MAP, this.type));
    }
  }

  public Long getLongValue() {
    if (this.type == TokenType.INTEGER) {
      return (Long) this.value;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.INTEGER, this.type));
    }
  }

  public Boolean getBooleanValue() {
    if (this.type == TokenType.BOOLEAN) {
      return (Boolean) this.value;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.BOOLEAN, this.type));
    }
  }

  public Double getDoubleValue() {
    if (this.type == TokenType.REAL) {
      return (Double) this.value;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.REAL, this.type));
    }
  }

  public Object getNullValue() {
    if (this.type == TokenType.NULL) {
      return this.value;
    } else {
      throw new InvalidTypeException(String.format("expected %s value but token type is %s",
          TokenType.NULL, this.type));
    }
  }

  public Object getObjectValue() {
    return this.value;
  }



}