【问题标题】:Correct use of Apache Tika MediaType正确使用 Apache Tika MediaType
【发布时间】:2014-06-04 10:51:58
【问题描述】:

我想使用 APache Tika 的 MediaType 类来比较 mediaTypes。

我首先使用 Tika 来检测 MediaType。 然后我想根据MediaType开始一个动作。

所以如果 MediaType 来自 XML 类型,我想做一些动作,如果它是一个压缩文件,我想开始另一个动作。

我的问题是 XML 类型很多,那么如何使用 MediaType 检查它是否是 XML?

这是我之前(在 Tika 之前)的实现:

if (contentType.contains("text/xml") || 
    contentType.contains("application/xml") || 
    contentType.contains("application/x-xml") || 
    contentType.contains("application/atom+xml") || 
    contentType.contains("application/rss+xml")) {
        processXML();
}

else if (contentType.contains("application/gzip") || 
    contentType.contains("application/x-gzip") || 
    contentType.contains("application/x-gunzip") || 
    contentType.contains("application/gzipped") || 
    contentType.contains("application/gzip-compressed") || 
    contentType.contains("application/x-compress") || 
    contentType.contains("gzip/document") || 
    contentType.contains("application/octet-stream")) {
        processGzip();
}

我想将其切换为使用 Tika,如下所示:

MediaType mediaType = MediaType.parse(contentType);
if (mediaType == APPLICATION_XML) {
    return processXml();
} else if (mediaType == APPLICATION_ZIP || mediaType == OCTET_STREAM) {
    return processGzip();
}

但问题是 Tika.detect(...) 返回许多没有 MediaType 常量的不同类型。

如果 MediaType 是 XML 类型,我如何才能识别它?或者如果它是类型 Compress ? 我需要一个包含所有孩子的“父亲”类型,也许是一种方法: “boolean isXML()”,包括 application/xml 和 text/xml 和 application/x-xml 或“boolean isCompress()”,包括所有 zip + gzip 类型等

【问题讨论】:

  • 你能澄清你的问题是什么吗?匹配媒体类型?创建媒体类型对象?找出哪些类型可以回来?处理类型的父/子关系?还有什么?
  • 我已经编辑了问题并在问题中添加了以下(最后一部分):如果 MediaType 是 XML 类型,我如何才能识别它?或者如果它是类型 compress ?我需要一个包含所有子项的“父亲”类型,可能是一种方法:“boolean isXML()”,其中包括 application/xml 和 text/xml 以及 application/x-xml 或“boolean isCompress()”,其中包括所有 zip + gzip 类型等

标签: content-type apache-tika media-type


【解决方案1】:

您需要做的是遍历类型层次结构,直到找到所需的内容,或者用完要检查的内容。这可以通过递归来完成,也可以通过循环来完成

你需要的关键方法是MediaTypeRegistry.getSupertype(MediaType)

你的代码应该是这样的:

// Define your media type constants here
MediaType FOO = MediaType.parse("application/foo");

// Work out the file's type
MediaType type = detector.detect(stream, metadata);

// Is it one we want in the tree?
while (type != null && !type.equals(MediaType.OCTET_STREAM)) {
   if (type.equals(MediaType.Application_XML)) {
       doThingForXML();
   } else if (type.equals(MediaType.APPLICATION_ZIP)) { 
       doThingForZip();
   } else if (type.equals(FOO)) {
       doThingForFoo();
   } else {
       // Check parent
       type = registry.getSuperType(type);
   }
}

【讨论】:

猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
相关资源
最近更新 更多