1 package org.apache.fulcrum.intake.validator;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.nio.charset.Charset;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import javax.servlet.http.Part;
30
31
32
33
34
35
36
37
38
39
40
41
42 public class FileValidator
43 extends DefaultValidator<Part>
44 {
45 private final static Pattern charsetPattern = Pattern.compile(".+charset\\s*=\\s*(.+)");
46
47
48
49
50 public FileValidator()
51 {
52 super();
53 }
54
55
56
57
58
59
60
61
62
63 public void assertValidity(Part testValue)
64 throws ValidationException
65 {
66 byte[] fileData = new byte[(int) testValue.getSize()];
67 String contentType = testValue.getContentType();
68 String charset = Charset.defaultCharset().name();
69
70 if (contentType.contains("charset"))
71 {
72 Matcher matcher = charsetPattern.matcher(contentType);
73 if (matcher.matches())
74 {
75 charset = matcher.group(1);
76 }
77 }
78
79 try (InputStream fis = testValue.getInputStream())
80 {
81 int byteSize = fis.read(fileData);
82 if ( fileData.length != byteSize )
83 {
84 throw new ValidationException("Byte length mismatch found");
85 }
86
87 }
88 catch (IOException e)
89 {
90 fileData = null;
91 }
92
93 String content = null;
94 try
95 {
96 if ( fileData != null )
97 {
98 content = new String(fileData, charset);
99 }
100 }
101 catch (UnsupportedEncodingException e)
102 {
103 throw new ValidationException("Invalid charset " + charset);
104 }
105
106 super.assertValidity(content);
107 }
108 }