aboutsummaryrefslogtreecommitdiff
path: root/java/src/main/java/org/pablotron/luigi/Cache.java
blob: 7be8f6c69a42cf7112749daa08b57825365c9dbe (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
package org.pablotron.luigi;

import java.util.Map;
import java.util.HashMap;
import org.pablotron.luigi.Filter;
import org.pablotron.luigi.Template;
import org.pablotron.luigi.errors.LuigiError;
import org.pablotron.luigi.errors.UnknownTemplateError;
import org.pablotron.luigi.actions.Action;

public final class Cache {
  private final Map<String, String> strings;
  private final Map<String, Filter.Handler> filters;
  private final Map<String, Template> templates = new HashMap<String, Template>();

  public Cache(
    final Map<String, String> strings,
    final Map<String, Filter.Handler> filters
  ) {
    this.strings = strings;
    this.filters = filters;
  }

  public Cache(final Map<String, String> strings) {
    this(strings, Filter.FILTERS);
  }

  public String run(
    final String key,
    final Map<String, String> args
  ) throws LuigiError {
    // run template with args
    return get(key).run(args);
  }

  public boolean containsKey(final String key) {
    return strings.containsKey(key);
  }

  public Template get(final String key) throws LuigiError {
    if (!templates.containsKey(key)) {
      // make sure template exists
      if (!strings.containsKey(key))
        throw new UnknownTemplateError(key);

      // create and cache template
      templates.put(key, new Template(strings.get(key), filters));
    }

    // get template
    return templates.get(key);
  }
};