1 9 10 package com.opensymphony.module.sitemesh.mapper; 11 12 import com.opensymphony.module.sitemesh.Config; 13 import com.opensymphony.module.sitemesh.Decorator; 14 import com.opensymphony.module.sitemesh.DecoratorMapper; 15 import com.opensymphony.module.sitemesh.Page; 16 17 import javax.servlet.http.HttpServletRequest ; 18 import java.io.File ; 19 import java.util.HashMap ; 20 import java.util.Iterator ; 21 import java.util.Map ; 22 import java.util.Properties ; 23 24 50 public final class AgentDecoratorMapper extends AbstractDecoratorMapper { 51 private Map map = null; 52 53 public void init(Config config, Properties properties, DecoratorMapper parent) throws InstantiationException { 54 super.init(config, properties, parent); 55 map = new HashMap (); 56 initMap(properties); 57 } 58 59 public Decorator getDecorator(HttpServletRequest request, Page page) { 60 try { 61 Decorator result = null; 62 final Decorator d = super.getDecorator(request, page); 63 String path = modifyPath(d.getPage(), getExt(request.getHeader("User-Agent"))); 64 65 File decFile = new File (config.getServletContext().getRealPath(path)); 66 67 if (decFile.isFile()) { 68 result = new DefaultDecorator(d.getName(), path, null) { 69 public String getInitParameter(String paramName) { 70 return d.getInitParameter(paramName); 71 } 72 }; 73 } 74 return result == null ? super.getDecorator(request, page) : result; 75 } 76 catch (NullPointerException e) { 77 return super.getDecorator(request, page); 78 } 79 } 80 81 82 private String getExt(String userAgent) { 83 Iterator i = map.entrySet().iterator(); 84 while (i.hasNext()) { 85 Map.Entry entry = (Map.Entry ) i.next(); 86 String curr = (String ) entry.getKey(); 87 if (userAgent.indexOf(curr) > -1) return (String ) entry.getValue(); 88 } 89 return null; 90 } 91 92 93 private static String modifyPath(String path, String ext) { 94 int dot = path.indexOf('.'); 95 if (dot > -1) { 96 return path.substring(0, dot) + '-' + ext + path.substring(dot); 97 } 98 else { 99 return path + '-' + ext; 100 } 101 } 102 103 104 private void initMap(Properties props) { 105 Iterator i = props.entrySet().iterator(); 106 while (i.hasNext()) { 107 Map.Entry entry = (Map.Entry ) i.next(); 108 String key = (String ) entry.getKey(); 109 if (key.startsWith("match.")) { 110 String match = key.substring(6); 111 String ext = (String ) entry.getValue(); 112 map.put(match, ext); 113 } 114 } 115 } 116 } | Popular Tags |