View Javadoc

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