1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.joda.time.contrib.jsptag;
18
19 import java.io.IOException;
20 import java.text.DateFormat;
21 import java.util.Locale;
22
23 import javax.servlet.jsp.JspException;
24 import javax.servlet.jsp.JspTagException;
25 import javax.servlet.jsp.PageContext;
26 import javax.servlet.jsp.tagext.TagSupport;
27
28 import org.joda.time.DateTimeZone;
29 import org.joda.time.ReadableInstant;
30 import org.joda.time.ReadablePartial;
31 import org.joda.time.format.DateTimeFormat;
32 import org.joda.time.format.DateTimeFormatter;
33
34
35
36
37
38
39
40
41 public abstract class FormatSupport extends TagSupport {
42
43
44 protected Object value;
45
46 protected String pattern;
47
48 protected String style;
49
50 protected DateTimeZone dateTimeZone;
51
52 protected Locale locale;
53
54 private String var;
55
56 private int scope;
57
58
59
60
61 public FormatSupport() {
62 super();
63 init();
64 }
65
66 private void init() {
67 var = null;
68 value = null;
69 pattern = null;
70 style = null;
71 dateTimeZone = null;
72 locale = null;
73 scope = PageContext.PAGE_SCOPE;
74 }
75
76 public void setVar(String var) {
77 this.var = var;
78 }
79
80 public void setScope(String scope) {
81 this.scope = Util.getScope(scope);
82 }
83
84
85
86
87 public int doEndTag() throws JspException {
88 if (value == null) {
89 if (var != null) {
90 pageContext.removeAttribute(var, scope);
91 }
92 return EVAL_PAGE;
93 }
94
95
96 DateTimeFormatter formatter;
97 if (pattern != null) {
98 formatter = DateTimeFormat.forPattern(pattern);
99 } else if (style != null) {
100 formatter = DateTimeFormat.forStyle(style);
101 } else {
102
103 formatter = DateTimeFormat.mediumDate();
104 }
105
106
107 Locale locale = this.locale;
108 if (locale == null) {
109 locale = Util.getFormattingLocale(pageContext, this, true,
110 DateFormat.getAvailableLocales());
111 }
112 if (locale != null) {
113 formatter = formatter.withLocale(locale);
114 }
115
116
117 DateTimeZone tz = this.dateTimeZone;
118 if (tz == null) {
119 tz = DateTimeZoneSupport.getDateTimeZone(pageContext, this);
120 }
121 if (tz != null) {
122 formatter = formatter.withZone(tz);
123 }
124
125
126 String formatted;
127 if (value instanceof ReadableInstant) {
128 formatted = formatter.print((ReadableInstant) value);
129 } else if (value instanceof ReadablePartial) {
130 formatted = formatter.print((ReadablePartial) value);
131 } else {
132 throw new JspException(
133 "value attribute of format tag must be a ReadableInstant or ReadablePartial," +
134 " was: " + value.getClass().getName());
135 }
136
137 if (var != null) {
138 pageContext.setAttribute(var, formatted, scope);
139 } else {
140 try {
141 pageContext.getOut().print(formatted);
142 } catch (IOException ioe) {
143 throw new JspTagException(ioe.toString(), ioe);
144 }
145 }
146
147 return EVAL_PAGE;
148 }
149
150
151 public void release() {
152 init();
153 }
154
155 }