1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.voting.voters;
35
36 import info.magnolia.context.Context;
37 import info.magnolia.context.MgnlContext;
38 import info.magnolia.context.WebContext;
39
40 import java.util.ArrayList;
41 import java.util.List;
42
43 import javax.servlet.http.HttpServletRequest;
44
45
46
47
48
49
50
51 public class UserAgentVoter extends AbstractBoolVoter {
52 private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UserAgentVoter.class);
53
54 private final List<String> allowed = new ArrayList<String>();
55 private final List<String> rejected = new ArrayList<String>();
56
57 public List<String> getAllowed() {
58 return allowed;
59 }
60
61 public void setAllowed(List<String> allowed) {
62 this.allowed.addAll(allowed);
63 }
64
65 public void addAllowed(String contentType) {
66 allowed.add(contentType);
67 }
68
69 public List<String> getRejected() {
70 return rejected;
71 }
72
73 public void setRejected(List<String> rejected) {
74 this.rejected.addAll(rejected);
75 }
76
77 public void addRejected(String contentType) {
78 rejected.add(contentType);
79 }
80
81 @Override
82 protected boolean boolVote(Object value) {
83 final HttpServletRequest request;
84 if (value instanceof HttpServletRequest) {
85 request = (HttpServletRequest) value;
86 } else {
87 final Context ctx = MgnlContext.getInstance();
88 if (ctx instanceof WebContext) {
89 request = ((WebContext) ctx).getRequest();
90 } else {
91 return false;
92 }
93 }
94
95 final String userAgent = request.getHeader("User-Agent");
96
97
98 if (userAgent == null) {
99 log.warn("No user agent on the request, can't vote.");
100 return false;
101 }
102 if (allowed.size() > 0 && !matches(allowed, userAgent)) {
103 return false;
104 }
105 if (rejected.size() > 0 && matches(rejected, userAgent)) {
106 return false;
107 }
108 return true;
109 }
110
111
112
113
114
115
116
117
118 private boolean matches(List patterns, String userAgent) {
119 for (int i = 0; i < patterns.size(); i++) {
120 if (userAgent.matches((String) patterns.get(i))) {
121 return true;
122 }
123 }
124 return false;
125 }
126 }