View Javadoc

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