01: package org.conform.validator;
02:
03: import org.conform.Validator;
04: import org.conform.ValidationException;
05:
06: import java.net.URL;
07: import java.net.MalformedURLException;
08: import java.util.Arrays;
09: import java.util.List;
10: import java.lang.annotation.Annotation;
11:
12: public class URLStringValidator implements Validator {
13: private String message = "validation.url";
14: private String[] protocols;
15: private List<String> protocolsList;
16:
17: public URLStringValidator() {
18: }
19:
20: public URLStringValidator(Annotation annotation) {
21: URLString urlString = (URLString) annotation;
22: setProtocols(urlString.protocols());
23: }
24:
25: public URLStringValidator(String[] protocols) {
26: this .protocols = protocols;
27: if (protocols != null && protocols.length != 0)
28: protocolsList = Arrays.asList(protocols);
29: }
30:
31: public String[] getProtocols() {
32: return protocols;
33: }
34:
35: public void setProtocols(String[] protocols) {
36: this .protocols = protocols;
37: if (protocols != null && protocols.length != 0)
38: protocolsList = Arrays.asList(protocols);
39: else
40: protocolsList = null;
41: }
42:
43: public void setMessage(String message) {
44: this .message = message;
45: }
46:
47: public String getMessage() {
48: return message;
49: }
50:
51: public Object validate(Object value) {
52: if (value == null)
53: return null;
54:
55: try {
56: URL url = new URL((String) value);
57: if (protocolsList != null
58: && protocolsList.contains(url.getProtocol()))
59: throw new ValidationException(
60: new ValidationException.Message(getMessage(),
61: new Object[] { value }));
62:
63: return url.toString();
64: } catch (MalformedURLException e) {
65: throw new ValidationException(
66: new ValidationException.Message(getMessage(),
67: new Object[] { value }));
68: }
69: }
70: }
|