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 public class UserAgentVoter extends AbstractBoolVoter {
50 private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UserAgentVoter.class);
51
52 private final List<String> allowed = new ArrayList<String>();
53 private final List<String> rejected = new ArrayList<String>();
54
55 public List<String> getAllowed() {
56 return allowed;
57 }
58
59 public void setAllowed(List<String> allowed) {
60 this.allowed.addAll(allowed);
61 }
62
63 public void addAllowed(String contentType) {
64 allowed.add(contentType);
65 }
66
67 public List<String> getRejected() {
68 return rejected;
69 }
70
71 public void setRejected(List<String> rejected) {
72 this.rejected.addAll(rejected);
73 }
74
75 public void addRejected(String contentType) {
76 rejected.add(contentType);
77 }
78
79 @Override
80 protected boolean boolVote(Object value) {
81 final HttpServletRequest request;
82 if (value instanceof HttpServletRequest) {
83 request = (HttpServletRequest) value;
84 } else {
85 final Context ctx = MgnlContext.getInstance();
86 if (ctx instanceof WebContext) {
87 request = ((WebContext) ctx).getRequest();
88 } else {
89 return false;
90 }
91 }
92
93 final String userAgent = request.getHeader("User-Agent");
94
95
96 if (userAgent == null) {
97 log.warn("No user agent on the request, can't vote.");
98 return false;
99 }
100 if (allowed.size() > 0 && !matches(allowed, userAgent)) {
101 return false;
102 }
103 if (rejected.size() > 0 && matches(rejected, userAgent)) {
104 return false;
105 }
106 return true;
107 }
108
109
110
111
112
113
114
115 private boolean matches(List patterns, String userAgent) {
116 for (int i = 0; i < patterns.size(); i++) {
117 if (userAgent.matches((String) patterns.get(i))) {
118 return true;
119 }
120 }
121 return false;
122 }
123 }