1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.oness.common.webapp.controller.tiles;
17
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.Map;
21
22 import javax.servlet.ServletContext;
23 import javax.servlet.http.HttpServletRequest;
24 import javax.servlet.http.HttpServletResponse;
25
26 import org.apache.struts.tiles.ComponentContext;
27 import org.apache.struts.tiles.ComponentDefinition;
28 import org.apache.struts.tiles.Controller;
29 import org.apache.struts.tiles.ControllerSupport;
30 import org.apache.struts.tiles.TilesUtil;
31
32 /***
33 * <p>
34 * Tiles controller that checks user-agent header in request and overrides tiles
35 * definition attributes.
36 * </p>
37 * <p>
38 * There is a rule Map in which the key is a string and value is a definition
39 * name. If key is contained in user-agent header then all the attributes of the
40 * tiles definition are overridden with those of the definition specified as map
41 * value and the ones that do not exist are added.
42 * </p>
43 * <p>
44 * e.g. map contains an entry with "PalmSource" as key and
45 * ".layout.palmSourceLayout" as value. <br/>When a browser with "PalmSource" in
46 * its user-agent header asks for a page, the definition taken from tiles-defs
47 * file will have its attributes plus those from ".layout.palmSourceLayout"
48 * definition, overriding the ones that already exist.
49 * </p>
50 *
51 * @todo Allow rules Map to be specified in Spring application context files
52 *
53 * @author Carlos Sanchez
54 * @version $Revision: 1.1 $
55 */
56 public class SwitchLayoutController extends ControllerSupport implements Controller {
57
58 private static Map rules;
59
60 static {
61 rules = new HashMap();
62 rules.put("PalmSource", ".layout.palmSourceLayout");
63 }
64
65 /***
66 * @see org.apache.struts.tiles.Controller#execute(org.apache.struts.tiles.ComponentContext,
67 * javax.servlet.http.HttpServletRequest,
68 * javax.servlet.http.HttpServletResponse,
69 * javax.servlet.ServletContext)
70 */
71 public void execute(ComponentContext tileContext,
72 HttpServletRequest request, HttpServletResponse response,
73 ServletContext servletContext) throws Exception {
74
75 String userAgent = (String) request.getHeader("user-agent");
76 if (userAgent == null)
77 return;
78
79 Iterator rulesIter = rules.entrySet().iterator();
80 while (rulesIter.hasNext()) {
81 Map.Entry rule = (Map.Entry) rulesIter.next();
82 if (userAgent.indexOf((String) rule.getKey()) != -1) {
83 ComponentDefinition definition = TilesUtil.getDefinition(
84 (String) rule.getValue(), request, servletContext);
85 Iterator attribIter = definition.getAttributes().entrySet()
86 .iterator();
87 while (attribIter.hasNext()) {
88 Map.Entry attrib = (Map.Entry) attribIter.next();
89 tileContext.putAttribute((String) attrib.getKey(), attrib
90 .getValue());
91 }
92 }
93 }
94 }
95 }