1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.tika.mime;
18
19
20 import java.io.ByteArrayInputStream;
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.net.URL;
27 import java.util.Arrays;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
32
33 import javax.xml.namespace.QName;
34
35 import org.apache.tika.detect.Detector;
36 import org.apache.tika.detect.XmlRootExtractor;
37 import org.apache.tika.metadata.Metadata;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 public final class MimeTypes implements Detector {
54
55
56
57
58 public static final String OCTET_STREAM = "application/octet-stream";
59
60
61
62
63 public static final String PLAIN_TEXT = "text/plain";
64
65
66
67
68 public static final String XML = "application/xml";
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95 private static final boolean[] IS_CONTROL_BYTE = new boolean[0x20];
96 static {
97 Arrays.fill(IS_CONTROL_BYTE, true);
98 IS_CONTROL_BYTE[0x09] = false;
99 IS_CONTROL_BYTE[0x0A] = false;
100 IS_CONTROL_BYTE[0x0C] = false;
101 IS_CONTROL_BYTE[0x0D] = false;
102 IS_CONTROL_BYTE[0x1B] = false;
103 }
104
105
106
107
108 private final MimeType rootMimeType;
109
110
111
112
113 private final MimeType textMimeType;
114
115
116
117
118 private final MimeType xmlMimeType;
119
120
121 private final Map<String, MimeType> types = new HashMap<String, MimeType>();
122
123
124 private Patterns patterns = new Patterns();
125
126
127 private SortedSet<Magic> magics = new TreeSet<Magic>();
128
129
130 private SortedSet<MimeType> xmls = new TreeSet<MimeType>();
131
132 private final XmlRootExtractor xmlRootExtractor;
133
134 public MimeTypes() {
135 rootMimeType = new MimeType(this, OCTET_STREAM);
136 textMimeType = new MimeType(this, PLAIN_TEXT);
137 xmlMimeType = new MimeType(this, XML);
138
139 try {
140 textMimeType.setSuperType(rootMimeType);
141 xmlMimeType.setSuperType(rootMimeType);
142 } catch (MimeTypeException e) {
143 throw new IllegalStateException("Error in MimeType logic", e);
144 }
145
146 types.put(rootMimeType.getName(), rootMimeType);
147 types.put(textMimeType.getName(), textMimeType);
148 types.put(xmlMimeType.getName(), xmlMimeType);
149
150 try {
151 xmlRootExtractor = new XmlRootExtractor();
152 } catch (Exception e) {
153 throw new IllegalStateException(
154 "Unable to create a XmlRootExtractor", e);
155 }
156 }
157
158
159
160
161
162
163
164
165
166 public MimeType getMimeType(File file) {
167 return getMimeType(file.getName());
168 }
169
170
171
172
173
174
175
176
177
178 public MimeType getMimeType(URL url) {
179 return getMimeType(url.getPath());
180 }
181
182
183
184
185
186
187
188
189 public MimeType getMimeType(String name) {
190 MimeType type = patterns.matches(name);
191 if (type != null) {
192 return type;
193 }
194 type = patterns.matches(name.toLowerCase());
195 if (type != null) {
196 return type;
197 } else {
198 return rootMimeType;
199 }
200 }
201
202
203
204
205
206
207
208
209
210
211
212
213 public MimeType getMimeType(byte[] data) {
214 if (data == null) {
215 throw new IllegalArgumentException("Data is missing");
216 }
217
218
219 MimeType result = null;
220 for (Magic magic : magics) {
221 if (magic.eval(data)) {
222 result = magic.getType();
223 break;
224 }
225 }
226
227 if (result != null) {
228
229
230 if ("application/xml".equals(result.getName())
231 || "text/html".equals(result.getName())) {
232 QName rootElement = xmlRootExtractor.extractRootElement(data);
233 if (rootElement != null) {
234 for (MimeType type : xmls) {
235 if (type.matchesXML(
236 rootElement.getNamespaceURI(),
237 rootElement.getLocalPart())) {
238 result = type;
239 break;
240 }
241 }
242 }
243 }
244 return result;
245 }
246
247
248
249 for (int i = 0; i < data.length; i++) {
250 int b = data[i] & 0xFF;
251 if (b < IS_CONTROL_BYTE.length && IS_CONTROL_BYTE[b]) {
252 return rootMimeType;
253 }
254 }
255 return textMimeType;
256 }
257
258
259
260
261
262
263
264
265
266
267 public MimeType getMimeType(InputStream stream) throws IOException {
268 return getMimeType(readMagicHeader(stream));
269 }
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284 private byte[] readMagicHeader(InputStream stream) throws IOException {
285 if (stream == null) {
286 throw new IllegalArgumentException("InputStream is missing");
287 }
288
289 byte[] bytes = new byte[getMinLength()];
290 int totalRead = 0;
291
292 int lastRead = stream.read(bytes);
293 while (lastRead != -1) {
294 totalRead += lastRead;
295 if (totalRead == bytes.length) {
296 return bytes;
297 }
298 lastRead = stream.read(bytes, totalRead, bytes.length - totalRead);
299 }
300
301 byte[] shorter = new byte[totalRead];
302 System.arraycopy(bytes, 0, shorter, 0, totalRead);
303 return shorter;
304 }
305
306 public String getType(String typeName, String url, byte[] data) {
307 try {
308 Metadata metadata = new Metadata();
309 if (url != null) {
310 metadata.set(Metadata.RESOURCE_NAME_KEY, url);
311 }
312 if (typeName != null) {
313 metadata.set(Metadata.CONTENT_TYPE, typeName);
314 }
315 return detect(new ByteArrayInputStream(data), metadata).toString();
316 } catch (IOException e) {
317 throw new IllegalStateException(
318 "ByteArrayInputStream throws an IOException!", e);
319 }
320 }
321
322
323
324
325
326
327
328
329
330
331
332 public String getType(URL url) throws IOException {
333 InputStream stream = url.openStream();
334 try {
335 Metadata metadata = new Metadata();
336 metadata.set(Metadata.RESOURCE_NAME_KEY, url.toString());
337 return detect(stream, metadata).toString();
338 } finally {
339 stream.close();
340 }
341 }
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360 public MimeType getMimeType(String name, byte[] data) {
361
362 MimeType mimeType = getMimeType(data);
363
364
365
366 if (mimeType == null) {
367 mimeType = getMimeType(name);
368 }
369
370 return mimeType;
371 }
372
373
374
375
376
377
378
379
380
381
382
383 public MimeType getMimeType(String name, InputStream stream)
384 throws IOException {
385 return getMimeType(name, readMagicHeader(stream));
386 }
387
388
389
390
391
392
393
394
395
396
397 public synchronized MimeType forName(String name)
398 throws MimeTypeException {
399 if (MimeType.isValid(name)) {
400 name = name.toLowerCase();
401 MimeType type = types.get(name);
402 if (type == null) {
403 type = new MimeType(this, name);
404 if (name.startsWith("text/")) {
405 type.setSuperType(textMimeType);
406 } else if (name.endsWith("+xml")) {
407 type.setSuperType(xmlMimeType);
408 } else {
409 type.setSuperType(rootMimeType);
410 }
411 types.put(name, type);
412 }
413 return type;
414 } else {
415 throw new MimeTypeException("Invalid media type name: " + name);
416 }
417 }
418
419
420
421
422
423
424
425
426
427 synchronized void addAlias(MimeType type, String alias)
428 throws MimeTypeException {
429 if (!types.containsKey(alias)) {
430 types.put(alias, type);
431 } else {
432 throw new MimeTypeException(
433 "Media type alias already exists: " + alias);
434 }
435 }
436
437
438
439
440
441
442
443
444
445
446
447
448 public void addPattern(MimeType type, String pattern)
449 throws MimeTypeException {
450 this.addPattern(type, pattern, false);
451 }
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471 public void addPattern(MimeType type, String pattern, boolean isRegex)
472 throws MimeTypeException {
473 patterns.add(pattern, isRegex, type);
474 }
475
476
477
478
479
480
481
482
483
484 public int getMinLength() {
485
486
487 return 8 * 1024;
488 }
489
490
491
492
493
494
495
496 void add(MimeType type) {
497
498 if (type.hasMagic()) {
499 magics.addAll(Arrays.asList(type.getMagics()));
500 }
501
502
503 if (type.hasRootXML()) {
504 xmls.add(type);
505 }
506 }
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521 public MediaType detect(InputStream input, Metadata metadata)
522 throws IOException {
523 MimeType type = rootMimeType;
524
525
526 if (input != null) {
527 input.mark(getMinLength());
528 try {
529 byte[] prefix = readMagicHeader(input);
530 type = getMimeType(prefix);
531 } finally {
532 input.reset();
533 }
534 }
535
536
537 String resourceName = metadata.get(Metadata.RESOURCE_NAME_KEY);
538 if (resourceName != null) {
539 String name = null;
540
541
542 try {
543 URI uri = new URI(resourceName);
544 String path = uri.getPath();
545 if (path != null) {
546 int slash = path.lastIndexOf('/');
547 if (slash + 1 < path.length()) {
548 name = path.substring(slash + 1);
549 }
550 }
551 } catch (URISyntaxException e) {
552 name = resourceName;
553 }
554
555 if (name != null) {
556 MimeType hint = getMimeType(name);
557 if (hint.isDescendantOf(type)) {
558 type = hint;
559 }
560 }
561 }
562
563
564 String typeName = metadata.get(Metadata.CONTENT_TYPE);
565 if (typeName != null) {
566 try {
567 MimeType hint = forName(typeName);
568 if (hint.isDescendantOf(type)) {
569 type = hint;
570 }
571 } catch (MimeTypeException e) {
572
573 }
574 }
575
576 return MediaType.parse(type.getName());
577 }
578
579 }