01: /* $Id: TemplateFormat.java 722 2006-10-30 10:15:22Z hengels $ */
02: package org.conform.format;
03:
04: import ognl.*;
05:
06: import java.io.Serializable;
07: import java.util.*;
08: import java.util.regex.Matcher;
09: import java.util.regex.Pattern;
10:
11: /**
12: * @author hengels
13: */
14: public class TemplateFormat extends AbstractFormat implements
15: Serializable {
16: /*
17: {
18: OgnlRuntime.setMethodAccessor(Object.class, new ObjectMethodAccessor() {
19: public Object callMethod(Map map, Object object, String methodName, Object[] objects)
20: throws MethodFailedException
21: {
22: if ("format".equals(methodName)) {
23: if (object == null)
24: return "-";
25: else {
26: format("");
27: }
28: }
29: else
30: return super.callMethod(map, object, methodName, objects);
31: }
32: });
33: }
34: */
35:
36: protected Pattern compiledPattern;
37:
38: public TemplateFormat() {
39: }
40:
41: public TemplateFormat(String pattern) {
42: this .pattern = pattern;
43: }
44:
45: public void setPattern(String pattern) {
46: super .setPattern(pattern);
47: this .compiledPattern = null;
48: }
49:
50: public String format(Object obj) {
51: StringBuffer buffer = new StringBuffer();
52: Map context = new HashMap();
53: if (obj instanceof Map)
54: context.putAll((Map) obj);
55: else
56: context.put("root", obj);
57:
58: try {
59: Pattern pattern = compiledPattern();
60: Matcher matcher = pattern.matcher(this .pattern);
61: while (matcher.find()) {
62: String expression = this .pattern.substring(matcher
63: .start() + 1, matcher.end() - 1);
64: Object value = Ognl.getValue(expression, context);
65: matcher.appendReplacement(buffer, "" + value);
66: }
67: matcher.appendTail(buffer);
68: } catch (OgnlException e) {
69: e.printStackTrace();
70: throw new IllegalArgumentException(e.getMessage());
71: }
72: return buffer.toString();
73: }
74:
75: private Pattern compiledPattern() {
76: if (compiledPattern == null)
77: compiledPattern = Pattern.compile("\\{[^\\{\\}]+\\}");
78: return compiledPattern;
79: }
80:
81: public static void main(String[] args) {
82: System.out.println(new TemplateFormat(
83: "{format(root.firstName)} {root.lastName}")
84: .format(new Object() {
85: public List getFirstName() {
86: return Arrays.asList("Holger", "The Boss");
87: }
88:
89: public String getLastName() {
90: return "Engels";
91: }
92: }));
93: }
94: }
|