View Javadoc

1   /*
2    * $Id: StrutsUtil.java 451544 2006-09-30 05:38:02Z mrdon $
3    *
4    * Copyright 2006 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts2.util;
19  
20  import java.io.IOException;
21  import java.io.PrintWriter;
22  import java.io.StringWriter;
23  import java.io.UnsupportedEncodingException;
24  import java.net.URLEncoder;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Collection;
28  import java.util.Hashtable;
29  import java.util.Iterator;
30  import java.util.List;
31  import java.util.Map;
32  
33  import javax.servlet.RequestDispatcher;
34  import javax.servlet.ServletOutputStream;
35  import javax.servlet.http.HttpServletRequest;
36  import javax.servlet.http.HttpServletResponse;
37  import javax.servlet.http.HttpServletResponseWrapper;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  import org.apache.struts2.views.jsp.ui.OgnlTool;
42  import org.apache.struts2.views.util.UrlHelper;
43  
44  import com.opensymphony.xwork2.util.TextUtils;
45  import com.opensymphony.xwork2.util.ValueStack;
46  import com.opensymphony.xwork2.ObjectFactory;
47  
48  
49  /***
50   * Struts base utility class, for use in Velocity and Freemarker templates
51   *
52   */
53  public class StrutsUtil {
54  
55      protected static final Log log = LogFactory.getLog(StrutsUtil.class);
56  
57  
58      protected HttpServletRequest request;
59      protected HttpServletResponse response;
60      protected Map classes = new Hashtable();
61      protected OgnlTool ognl = OgnlTool.getInstance();
62      protected ValueStack stack;
63  
64  
65      public StrutsUtil(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
66          this.stack = stack;
67          this.request = request;
68          this.response = response;
69      }
70  
71  
72      public Object bean(Object aName) throws Exception {
73          String name = aName.toString();
74          Class c = (Class) classes.get(name);
75  
76          if (c == null) {
77              c = ClassLoaderUtils.loadClass(name, StrutsUtil.class);
78              classes.put(name, c);
79          }
80  
81          return ObjectFactory.getObjectFactory().buildBean(c, stack.getContext());
82      }
83  
84      public boolean isTrue(String expression) {
85          Boolean retVal = (Boolean) stack.findValue(expression, Boolean.class);
86          if (retVal == null) {
87              return false;
88          }
89          return retVal.booleanValue();
90      }
91  
92      public Object findString(String name) {
93          return stack.findValue(name, String.class);
94      }
95  
96      public String include(Object aName) throws Exception {
97          return include(aName, request, response);
98      }
99  
100     /***
101      * @deprecated the request and response are stored in this util class, please use include(string)
102      */
103     public String include(Object aName, HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception {
104         try {
105             RequestDispatcher dispatcher = aRequest.getRequestDispatcher(aName.toString());
106 
107             if (dispatcher == null) {
108                 throw new IllegalArgumentException("Cannot find included file " + aName);
109             }
110 
111             ResponseWrapper responseWrapper = new ResponseWrapper(aResponse);
112 
113             dispatcher.include(aRequest, responseWrapper);
114 
115             return responseWrapper.getData();
116         }
117         catch (Exception e) {
118             e.printStackTrace();
119             throw e;
120         }
121     }
122 
123     public String urlEncode(String s) {
124         try {
125             return URLEncoder.encode(s, "UTF-8");
126         } catch (UnsupportedEncodingException e) {
127             return s;
128         }
129     }
130 
131     public String buildUrl(String url) {
132         return UrlHelper.buildUrl(url, request, response, null);
133     }
134 
135     public Object findValue(String expression, String className) throws ClassNotFoundException {
136         return stack.findValue(expression, Class.forName(className));
137     }
138 
139     public String getText(String text) {
140         return (String) stack.findValue("getText('" + text + "')"); 
141     }
142 
143     /*
144 	 * @return the url ContextPath. An empty string if one does not exist.
145 	 */
146 	public String getContext() {
147 		return (request == null)? "" : request.getContextPath();
148 	}
149 
150     /***
151      * the selectedList objects are matched to the list.listValue
152      * <p/>
153      * listKey and listValue are optional, and if not provided, the list item is used
154      *
155      * @param selectedList the name of the action property
156      *                     that contains the list of selected items
157      *                     or single item if its not an array or list
158      * @param list         the name of the action property
159      *                     that contains the list of selectable items
160      * @param listKey      an ognl expression that is exaluated relative to the list item
161      *                     to use as the key of the ListEntry
162      * @param listValue    an ognl expression that is exaluated relative to the list item
163      *                     to use as the value of the ListEntry
164      * @return a List of ListEntry
165      */
166     public List makeSelectList(String selectedList, String list, String listKey, String listValue) {
167         List selectList = new ArrayList();
168 
169         Collection selectedItems = null;
170 
171         Object i = stack.findValue(selectedList);
172 
173         if (i != null) {
174             if (i.getClass().isArray()) {
175                 selectedItems = Arrays.asList((Object[]) i);
176             } else if (i instanceof Collection) {
177                 selectedItems = (Collection) i;
178             } else {
179                 // treat it is a single item
180                 selectedItems = new ArrayList();
181                 selectedItems.add(i);
182             }
183         }
184 
185         Collection items = (Collection) stack.findValue(list);
186 
187         if (items != null) {
188             for (Iterator iter = items.iterator(); iter.hasNext();) {
189                 Object element = (Object) iter.next();
190                 Object key = null;
191 
192                 if ((listKey == null) || (listKey.length() == 0)) {
193                     key = element;
194                 } else {
195                     key = ognl.findValue(listKey, element);
196                 }
197 
198                 Object value = null;
199 
200                 if ((listValue == null) || (listValue.length() == 0)) {
201                     value = element;
202                 } else {
203                     value = ognl.findValue(listValue, element);
204                 }
205 
206                 boolean isSelected = false;
207 
208                 if ((value != null) && (selectedItems != null) && selectedItems.contains(value)) {
209                     isSelected = true;
210                 }
211 
212                 selectList.add(new ListEntry(key, value, isSelected));
213             }
214         }
215 
216         return selectList;
217     }
218 
219     public String htmlEncode(Object obj) {
220         if (obj == null) {
221             return null;
222         }
223 
224         return TextUtils.htmlEncode(obj.toString());
225     }
226 
227     public int toInt(long aLong) {
228         return (int) aLong;
229     }
230 
231     public long toLong(int anInt) {
232         return (long) anInt;
233     }
234 
235     public long toLong(String aLong) {
236         if (aLong == null) {
237             return 0;
238         }
239 
240         return Long.parseLong(aLong);
241     }
242 
243     public String toString(long aLong) {
244         return Long.toString(aLong);
245     }
246 
247     public String toString(int anInt) {
248         return Integer.toString(anInt);
249     }
250 
251 
252     static class ResponseWrapper extends HttpServletResponseWrapper {
253         StringWriter strout;
254         PrintWriter writer;
255         ServletOutputStream sout;
256 
257         ResponseWrapper(HttpServletResponse aResponse) {
258             super(aResponse);
259             strout = new StringWriter();
260             sout = new ServletOutputStreamWrapper(strout);
261             writer = new PrintWriter(strout);
262         }
263 
264         public String getData() {
265             writer.flush();
266 
267             return strout.toString();
268         }
269 
270         public ServletOutputStream getOutputStream() {
271             return sout;
272         }
273 
274         public PrintWriter getWriter() throws IOException {
275             return writer;
276         }
277     }
278 
279     static class ServletOutputStreamWrapper extends ServletOutputStream {
280         StringWriter writer;
281 
282         ServletOutputStreamWrapper(StringWriter aWriter) {
283             writer = aWriter;
284         }
285 
286         public void write(int aByte) {
287             writer.write(aByte);
288         }
289     }
290 }