001: package org.mvel;
002:
003: import org.mvel.util.StringAppender;
004:
005: import java.io.IOException;
006: import java.io.Reader;
007: import java.util.Collections;
008: import static java.util.Collections.synchronizedMap;
009: import java.util.HashMap;
010: import java.util.Iterator;
011: import java.util.Map;
012:
013: public class MVELTemplateRegistry implements TemplateRegistry {
014: private Map<String, String> registry;
015:
016: public MVELTemplateRegistry() {
017: //noinspection unchecked
018: this .registry = Collections.EMPTY_MAP;
019: }
020:
021: public String getTemplate(String name) {
022: return this .registry.get(name);
023: }
024:
025: public void registerTemplate(String name, String template) {
026: if (this .registry == Collections.EMPTY_MAP) {
027: if (MVEL.THREAD_SAFE) {
028: this .registry = synchronizedMap(new HashMap<String, String>());
029: } else {
030: this .registry = new HashMap<String, String>();
031: }
032:
033: }
034: this .registry.put(name, template);
035: }
036:
037: public void registerTemplate(Reader reader) {
038: if (reader == null)
039: throw new CompileException("Reader cannot be null");
040: int nameStart = -1;
041: int nameEnd = -1;
042: int contentStart = -1;
043: int contentEnd;
044: StringAppender sb = new StringAppender();
045: // char ch;
046:
047: try {
048: int c;
049: while ((c = reader.read()) != -1) {
050: // ch = (char)c;
051: if ('<' == (char) c
052: && sb.charAt(sb.length() - 1) == '<'
053: && sb.charAt(sb.length() - 2) == '='
054: && sb.charAt(sb.length() - 3) == ':'
055: && sb.charAt(sb.length() - 4) == ':') {
056: // we have ::=<< so backtrack to get function name
057: contentStart = sb.length() + 1;
058:
059: // backtrack to ()
060: int pos = sb.length() - 4;
061: while (sb.charAt(pos) != ')'
062: && sb.charAt(pos - 1) != '(') {
063: pos--;
064: }
065: //pos is now at the end of the template name
066: nameEnd = pos;
067:
068: // backtrack to new line or
069: while (pos != -1 && sb.charAt(pos) != '\n'
070: && sb.charAt(pos) != '\r'
071: && sb.charAt(pos) != ' ') {
072: pos--;
073: }
074: nameStart = pos + 1;
075: }
076:
077: if (':' == (char) c
078: && sb.charAt(sb.length() - 1) == ':'
079: && sb.charAt(sb.length() - 2) == '='
080: && sb.charAt(sb.length() - 3) == '>'
081: && sb.charAt(sb.length() - 4) == '>') {
082: // we have ::=>>
083: contentEnd = sb.length() - 4;
084: registerTemplate(new String(sb.getChars(nameStart,
085: nameEnd - nameStart - 1)), new String(sb
086: .getChars(contentStart, contentEnd
087: - contentStart)));
088: nameStart = -1;
089: nameEnd = -1;
090: contentStart = -1;
091: // contentEnd=-1;
092: }
093: sb.append((char) c);
094: }
095: } catch (IOException e) {
096: //empty
097: }
098: }
099:
100: public boolean isEmpty() {
101: return this .registry.isEmpty();
102: }
103:
104: public Iterator iterateTemplates() {
105: return this.registry.keySet().iterator();
106: }
107: }
|