View Javadoc

1   /*
2    * $Id: StrutsUtil.java 758258 2009-03-25 13:50:03Z musachy $
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.commons.lang.StringEscapeUtils;
44  
45  import org.apache.struts2.views.jsp.ui.OgnlTool;
46  import org.apache.struts2.views.util.UrlHelper;
47  
48  import com.opensymphony.xwork2.ActionContext;
49  import com.opensymphony.xwork2.ObjectFactory;
50  import com.opensymphony.xwork2.inject.Container;
51  import com.opensymphony.xwork2.util.ValueStack;
52  import com.opensymphony.xwork2.util.logging.Logger;
53  import com.opensymphony.xwork2.util.logging.LoggerFactory;
54  
55  
56  /***
57   * Struts base utility class, for use in Velocity and Freemarker templates
58   *
59   */
60  public class StrutsUtil {
61  
62      protected static final Logger LOG = LoggerFactory.getLogger(StrutsUtil.class);
63  
64  
65      protected HttpServletRequest request;
66      protected HttpServletResponse response;
67      protected Map classes = new Hashtable();
68      protected OgnlTool ognl;
69      protected ValueStack stack;
70  
71  
72      public StrutsUtil(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
73          this.stack = stack;
74          this.request = request;
75          this.response = response;
76          this.ognl = ((Container)stack.getContext().get(ActionContext.CONTAINER)).getInstance(OgnlTool.class);
77      }
78  
79  
80      public Object bean(Object aName) throws Exception {
81          String name = aName.toString();
82          Class c = (Class) classes.get(name);
83  
84          if (c == null) {
85              c = ClassLoaderUtils.loadClass(name, StrutsUtil.class);
86              classes.put(name, c);
87          }
88  
89          return ObjectFactory.getObjectFactory().buildBean(c, stack.getContext());
90      }
91  
92      public boolean isTrue(String expression) {
93          Boolean retVal = (Boolean) stack.findValue(expression, Boolean.class);
94          if (retVal == null) {
95              return false;
96          }
97          return retVal.booleanValue();
98      }
99  
100     public Object findString(String name) {
101         return stack.findValue(name, String.class);
102     }
103 
104     public String include(Object aName) throws Exception {
105         return include(aName, request, response);
106     }
107 
108     /***
109      * @deprecated the request and response are stored in this util class, please use include(string)
110      */
111     public String include(Object aName, HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception {
112         try {
113             RequestDispatcher dispatcher = aRequest.getRequestDispatcher(aName.toString());
114 
115             if (dispatcher == null) {
116                 throw new IllegalArgumentException("Cannot find included file " + aName);
117             }
118 
119             ResponseWrapper responseWrapper = new ResponseWrapper(aResponse);
120 
121             dispatcher.include(aRequest, responseWrapper);
122 
123             return responseWrapper.getData();
124         }
125         catch (Exception e) {
126             e.printStackTrace();
127             throw e;
128         }
129     }
130 
131     public String urlEncode(String s) {
132         try {
133             return URLEncoder.encode(s, "UTF-8");
134         } catch (UnsupportedEncodingException e) {
135             return s;
136         }
137     }
138 
139     public String buildUrl(String url) {
140         return UrlHelper.buildUrl(url, request, response, null);
141     }
142 
143     public Object findValue(String expression, String className) throws ClassNotFoundException {
144         return stack.findValue(expression, Class.forName(className));
145     }
146 
147     public String getText(String text) {
148         return (String) stack.findValue("getText('" + text + "')");
149     }
150 
151     /*
152      * @return the url ContextPath. An empty string if one does not exist.
153      */
154     public String getContext() {
155         return (request == null)? "" : request.getContextPath();
156     }
157 
158     /***
159      * the selectedList objects are matched to the list.listValue
160      * <p/>
161      * listKey and listValue are optional, and if not provided, the list item is used
162      *
163      * @param selectedList the name of the action property
164      *                     that contains the list of selected items
165      *                     or single item if its not an array or list
166      * @param list         the name of the action property
167      *                     that contains the list of selectable items
168      * @param listKey      an ognl expression that is exaluated relative to the list item
169      *                     to use as the key of the ListEntry
170      * @param listValue    an ognl expression that is exaluated relative to the list item
171      *                     to use as the value of the ListEntry
172      * @return a List of ListEntry
173      */
174     public List makeSelectList(String selectedList, String list, String listKey, String listValue) {
175         List selectList = new ArrayList();
176 
177         Collection selectedItems = null;
178 
179         Object i = stack.findValue(selectedList);
180 
181         if (i != null) {
182             if (i.getClass().isArray()) {
183                 selectedItems = Arrays.asList((Object[]) i);
184             } else if (i instanceof Collection) {
185                 selectedItems = (Collection) i;
186             } else {
187                 // treat it is a single item
188                 selectedItems = new ArrayList();
189                 selectedItems.add(i);
190             }
191         }
192 
193         Collection items = (Collection) stack.findValue(list);
194 
195         if (items != null) {
196             for (Iterator iter = items.iterator(); iter.hasNext();) {
197                 Object element = (Object) iter.next();
198                 Object key = null;
199 
200                 if ((listKey == null) || (listKey.length() == 0)) {
201                     key = element;
202                 } else {
203                     key = ognl.findValue(listKey, element);
204                 }
205 
206                 Object value = null;
207 
208                 if ((listValue == null) || (listValue.length() == 0)) {
209                     value = element;
210                 } else {
211                     value = ognl.findValue(listValue, element);
212                 }
213 
214                 boolean isSelected = false;
215 
216                 if ((value != null) && (selectedItems != null) && selectedItems.contains(value)) {
217                     isSelected = true;
218                 }
219 
220                 selectList.add(new ListEntry(key, value, isSelected));
221             }
222         }
223 
224         return selectList;
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 }