KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > kohsuke > stapler > RequestImpl


1 package org.kohsuke.stapler;
2
3 import org.apache.commons.beanutils.BeanUtils;
4 import org.apache.commons.beanutils.PropertyUtils;
5 import org.apache.commons.beanutils.Converter;
6 import org.apache.commons.beanutils.ConvertUtils;
7 import org.kohsuke.stapler.jelly.JellyClassTearOff;
8
9 import javax.servlet.RequestDispatcher JavaDoc;
10 import javax.servlet.ServletContext JavaDoc;
11 import javax.servlet.http.HttpServletRequest JavaDoc;
12 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
13 import javax.servlet.http.HttpServletResponse JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.lang.reflect.InvocationTargetException JavaDoc;
16 import java.lang.reflect.Field JavaDoc;
17 import java.text.ParseException JavaDoc;
18 import java.text.SimpleDateFormat JavaDoc;
19 import java.util.ArrayList JavaDoc;
20 import java.util.Calendar JavaDoc;
21 import java.util.Date JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25 import java.beans.PropertyDescriptor JavaDoc;
26
27 /**
28  * @author Kohsuke Kawaguchi
29  */

30 class RequestImpl extends HttpServletRequestWrapper JavaDoc implements StaplerRequest {
31     /**
32      * Tokenized URLs and consumed tokens.
33      * This object is modified by {@link Stapler} as we parse through the URL.
34      */

35     public final TokenList tokens;
36     /**
37      * Ancesotr nodes traversed so far.
38      * This object is modified by {@link Stapler} as we parse through the URL.
39      */

40     public final List JavaDoc<AncestorImpl> ancestors;
41
42     private final Stapler stapler;
43
44     // lazily computed
45
private String JavaDoc rest;
46
47     private final String JavaDoc originalRequestURI;
48
49     public RequestImpl(Stapler stapler, HttpServletRequest JavaDoc request, List JavaDoc<AncestorImpl> ancestors, TokenList tokens) {
50         super(request);
51         this.stapler = stapler;
52         this.ancestors = ancestors;
53         this.tokens = tokens;
54         this.originalRequestURI = request.getRequestURI();
55     }
56
57     public Stapler getStapler() {
58         return stapler;
59     }
60
61     public String JavaDoc getRestOfPath() {
62         if(rest==null)
63             rest = assembleRestOfPath(tokens);
64         return rest;
65     }
66
67     public ServletContext JavaDoc getServletContext() {
68         return stapler.getServletContext();
69     }
70
71     private static String JavaDoc assembleRestOfPath(TokenList tokens) {
72         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
73         for( int i=tokens.idx; i<tokens.length(); i++ ) {
74             buf.append('/');
75             buf.append(tokens.get(i));
76         }
77         return buf.toString();
78     }
79
80     public RequestDispatcher JavaDoc getView(Object JavaDoc it,String JavaDoc viewName) throws IOException JavaDoc {
81         // check JSP view first
82
RequestDispatcher JavaDoc rd = stapler.getResourceDispatcher(it, viewName);
83         if(rd!=null) return rd;
84
85         // then Jelly view
86
try {
87             rd = MetaClass.get(it.getClass()).loadTearOff(JellyClassTearOff.class).createDispatcher(it,viewName);
88             if(rd!=null)
89                 return rd;
90         } catch (LinkageError JavaDoc e) {
91             // jelly not present
92
}
93
94         return null;
95     }
96
97     public String JavaDoc getRootPath() {
98         StringBuffer JavaDoc buf = super.getRequestURL();
99         int idx = 0;
100         for( int i=0; i<3; i++ )
101             idx = buf.substring(idx).indexOf("/")+1;
102         buf.setLength(idx-1);
103         buf.append(super.getContextPath());
104         return buf.toString();
105     }
106
107     public List JavaDoc getAncestors() {
108         return ancestors;
109     }
110
111     public String JavaDoc getOriginalRequestURI() {
112         return originalRequestURI;
113     }
114
115     public boolean checkIfModified(long lastModified, StaplerResponse rsp) {
116         if(lastModified<=0)
117             return false;
118
119         // send out Last-Modified, or check If-Modified-Since
120
String JavaDoc since = getHeader("If-Modified-Since");
121         SimpleDateFormat JavaDoc format = Stapler.HTTP_DATE_FORMAT.get();
122         if(since!=null) {
123             try {
124                 long ims = format.parse(since).getTime();
125                 if(lastModified<ims+1000) {
126                     // +1000 because date header is second-precision and Java has milli-second precision
127
rsp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
128                     return true;
129                 }
130             } catch (NumberFormatException JavaDoc e) {
131                 // just ignore and serve the content
132
} catch (ParseException JavaDoc e) {
133                 // just ignore and serve the content
134
}
135         }
136         rsp.setHeader("Last-Modified",format.format(new Date JavaDoc(lastModified)));
137         return false;
138     }
139
140     public boolean checkIfModified(Date JavaDoc timestampOfResource, StaplerResponse rsp) {
141         return checkIfModified(timestampOfResource.getTime(),rsp);
142     }
143
144     public boolean checkIfModified(Calendar JavaDoc timestampOfResource, StaplerResponse rsp) {
145         return checkIfModified(timestampOfResource.getTimeInMillis(),rsp);
146     }
147
148     public void bindParameters(Object JavaDoc bean) {
149         bindParameters(bean,"");
150     }
151
152     public void bindParameters(Object JavaDoc bean, String JavaDoc prefix) {
153         Enumeration JavaDoc e = getParameterNames();
154         while(e.hasMoreElements()) {
155             String JavaDoc name = (String JavaDoc)e.nextElement();
156             if(name.startsWith(prefix))
157                 fill(bean,name.substring(prefix.length()), getParameter(name) );
158         }
159     }
160
161     public <T>
162     List JavaDoc<T> bindParametersToList(Class JavaDoc<T> type, String JavaDoc prefix) {
163         List JavaDoc<T> r = new ArrayList JavaDoc<T>();
164
165         int len = Integer.MAX_VALUE;
166
167         Enumeration JavaDoc e = getParameterNames();
168         while(e.hasMoreElements()) {
169             String JavaDoc name = (String JavaDoc)e.nextElement();
170             if(name.startsWith(prefix))
171                 len = Math.min(len,getParameterValues(name).length);
172         }
173
174         try {
175             for( int i=0; i<len; i++ ) {
176                 T t = type.newInstance();
177                 r.add(t);
178
179                 e = getParameterNames();
180                 while(e.hasMoreElements()) {
181                     String JavaDoc name = (String JavaDoc)e.nextElement();
182                     if(name.startsWith(prefix))
183                         fill(t, name.substring(prefix.length()), getParameterValues(name)[i] );
184                 }
185             }
186         } catch (InstantiationException JavaDoc x) {
187             throw new InstantiationError JavaDoc(x.getMessage());
188         } catch (IllegalAccessException JavaDoc x) {
189             throw new IllegalAccessError JavaDoc(x.getMessage());
190         }
191
192         return r;
193     }
194
195     private static void fill(Object JavaDoc bean, String JavaDoc key, String JavaDoc value) {
196         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(key);
197         while(tokens.hasMoreTokens()) {
198             String JavaDoc token = tokens.nextToken();
199             boolean last = !tokens.hasMoreTokens(); // is this the last token?
200

201             try {
202                 if(last) {
203                     copyProperty(bean,token,value);
204                 } else {
205                     bean = BeanUtils.getProperty(bean,token);
206                 }
207             } catch (IllegalAccessException JavaDoc x) {
208                 throw new IllegalAccessError JavaDoc(x.getMessage());
209             } catch (InvocationTargetException JavaDoc x) {
210                 Throwable JavaDoc e = x.getTargetException();
211                 if(e instanceof RuntimeException JavaDoc)
212                     throw (RuntimeException JavaDoc)e;
213                 if(e instanceof Error JavaDoc)
214                     throw (Error JavaDoc)e;
215                 throw new RuntimeException JavaDoc(x);
216             } catch (NoSuchMethodException JavaDoc e) {
217                 // ignore if there's no such property
218
}
219         }
220     }
221
222     private static void copyProperty(Object JavaDoc bean, String JavaDoc name, Object JavaDoc value) throws IllegalAccessException JavaDoc, InvocationTargetException JavaDoc {
223         PropertyDescriptor JavaDoc propDescriptor;
224         try {
225             propDescriptor =
226                 PropertyUtils.getPropertyDescriptor(bean, name);
227         } catch (NoSuchMethodException JavaDoc e) {
228             propDescriptor = null;
229         }
230         if ((propDescriptor != null) &&
231             (propDescriptor.getWriteMethod() == null)) {
232             propDescriptor = null;
233         }
234         if (propDescriptor != null) {
235             Converter converter = ConvertUtils.lookup(propDescriptor.getPropertyType());
236             if (converter != null)
237                 value = converter.convert(propDescriptor.getPropertyType(), value);
238             try {
239                 PropertyUtils.setSimpleProperty(bean, name, value);
240             } catch (NoSuchMethodException JavaDoc e) {
241                 throw new NoSuchMethodError JavaDoc(e.getMessage());
242             }
243             return;
244         }
245
246         // try a field
247
try {
248             Field JavaDoc field = bean.getClass().getField(name);
249             Converter converter = ConvertUtils.lookup(field.getType());
250             if (converter != null)
251                 value = converter.convert(field.getType(), value);
252             field.set(bean,value);
253         } catch (NoSuchFieldException JavaDoc e) {
254             // no such field
255
}
256     }
257 }
258
Popular Tags