1
2
3
4
5 package net.sf.jmimemagic.detectors;
6
7 import java.io.BufferedInputStream;
8 import java.io.File;
9 import java.io.FileInputStream;
10 import java.io.IOException;
11 import java.util.Map;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15
16 import com.fasterxml.jackson.core.JsonFactory;
17 import com.fasterxml.jackson.core.JsonParser;
18
19 import net.sf.jmimemagic.MagicDetector;
20
21
22
23
24
25
26
27 public class JsonFileDetector implements MagicDetector {
28 private static Log log = LogFactory.getLog(JsonFileDetector.class);
29
30
31
32
33 public JsonFileDetector() {
34 super();
35 }
36
37
38
39
40
41
42 @Override
43 public String getDisplayName() {
44 return "Json File Detector";
45 }
46
47
48
49
50
51
52 @Override
53 public String[] getHandledExtensions() {
54 return new String[] { "js", "json" };
55 }
56
57
58
59
60
61
62 @Override
63 public String[] getHandledTypes() {
64 return new String[] { "application/json" };
65 }
66
67
68
69
70
71
72 @Override
73 public String getName() {
74 return "jsonfiledetector";
75 }
76
77
78
79
80
81
82 @Override
83 public String getVersion() {
84 return "0.1";
85 }
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 @Override
101 public String[] process(final byte[] data, final int offset, final int length,
102 final long bitmask, final char comparator, final String mimeType,
103 final Map<String, String> params) {
104 log.debug("processing stream data");
105 try (JsonParser parser = new JsonFactory()
106 .createParser(new String(data, "UTF-8"))) {
107 while (!parser.isClosed()) {
108 parser.nextToken();
109 }
110 return new String[] { "application/json" };
111 } catch (final IOException e) {
112 log.debug("JsonFileDetector: failed to process data");
113 }
114 return null;
115 }
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130 @Override
131 public String[] process(final File file, final int offset, final int length,
132 final long bitmask, final char comparator, final String mimeType,
133 final Map<String, String> params) {
134 log.debug("processing file data");
135 try (BufferedInputStream is = new BufferedInputStream(
136 new FileInputStream(file))) {
137 final byte[] b = new byte[length];
138 final int n = is.read(b, offset, length);
139 if (n > 0) {
140 return process(b, offset, length, bitmask, comparator, mimeType,
141 params);
142 }
143 } catch (final IOException e) {
144 log.info("JsonFileDetector: file " + file.getName());
145 }
146 return null;
147 }
148 }