Use ikvm to use Tika in. Net Environment

Source: Internet
Author: User
Document directory
  • Compiling a jar into an assembly
  • Using Tika from. net
  • Using Tika
  • One important Cavet
  • Demo
  • Conclusion

Original address: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/07/02/using-the-tika-java-library-in-your-net-application-with-ikvm? Utm_source = feedburner & utm_medium = feed & utm_campaign = feed: + kevinmiller + (Kevin + Miller)

Using the tika Java library in your. NET application with ikvm

This may sound scary and heretical but did you know it is possible to leverage Java libraries from. Net Applications with no TCP sockets or web services getting caught in the crossfire? Let me introduce you to ikvm, which is frankly magic:

Ikvm. NET is an implementation of Java for mono and the Microsoft. NET Framework. It implements des the following components:

  • A Java Virtual Machine implemented in. net
  • A. Net Implementation of the Java class libraries
  • Tools that enable Java and. Net interoperability

Using ikvm we have been able to successfully integrate our dovetail seeker search application with the tika Text Extraction library implemented in Java. with Tika we can easily pull text out of rich documents from many orted formats. why Tika? Because there is nothing comparable in the. NET world as Tika.

This post will review how we integrated with Tika. If you like code you can find this example in a repo up on GitHub.

Compiling a jar into an assembly

First thing, we need to get our hands on the latest version of Tika. I downloaded and built the tika source using Maven as instructed. the result of this was a few jar files. the one we are interested in isTika-app-x.x.jarWhich has everything we need bundled into one useful container.

Next up we need to convert this jar we 've built to A. Net assembly. Do this using ikvmc.exe.

Tika \ build> ikvmc.exe-target: Library tika-app-0.7.jar

Unfortunately, you will see tons of troublesome looking warnings but the end result is a. Net Assembly wrapping the Java jar which you can reference in your projects.

Using Tika from. net

Ikvm is pretty transparent. you simply reference the tika app assembly and your. net code is talking to Java types. it is a bit weird at first as you have Java versions of types and. net versions. next you'll want to make sure that all the dependent ikvm runtime assemblies are stored with your project. using reflector I found that the tika app Assembly referenced A Lot Of ikvm assemblies which do not appear to be used. I had to figure out through trial and error which assemblies where not being touched by the rich document extractions being done. if need be you cocould simple include all of the referenced ikvm assemblies with your application. below I have done the work for you and eliminated all references to all the ikvm assemblies which appear to be in play.

16 assemblies down to 5. A much smaller deployment.

Using Tika

To do some text extraction we'll ask Tika, very nicely, to parse the files we throw at it. for my purposes this involved having Tika automatically determine how to parse the stream and extract the text and metadata about the document.

public TextExtractionResult Extract(string filePath) {     var parser = new AutoDetectParser();     var metadata = new Metadata();     var parseContext = new ParseContext();     java.lang.Class parserClass = parser.GetType();     parseContext.set(parserClass, parser);       try    {         var file = new File(filePath);         var url = file.toURI().toURL();         using (var inputStream = MetadataHelper.getInputStream(url, metadata))         {             parser.parse(inputStream, getTransformerHandler(), metadata, parseContext);             inputStream.close();         }           return assembleExtractionResult(_outputWriter.toString(), metadata);     }     catch (Exception ex)     {         throw new ApplicationException("Extraction of text from the file '{0}' failed.".ToFormat(filePath), ex);     } }
One important Cavet

Java has a concept calledClassloaderWhich has something to do with how Java types are found and loaded. there is probably a better way around this but for some reason if you do not implement a custom classloader and also set an application setting Cueing the ikvm runtime about which. net type to use as the classloader.

public class MySystemClassLoader : ClassLoader {     public MySystemClassLoader(ClassLoader parent)         : base(new AppDomainAssemblyClassLoader(typeof(MySystemClassLoader).Assembly))     {     } }

Here is an exampleApp. configTelling ikvm where the classloader is found.

<?xml version="1.0" encoding="utf-8" ?> <configuration>     <appSettings>         <add key="ikvm:java.system.class.loader" value="TikaOnDotNet.MySystemClassLoader, TikaOnDotNet" />     </appSettings> </configuration>

This step is very important.If ikvm cannot find a class loader, for some horrible reason, Tika will work fine but extract only empty documents with no metadata. the main reason this is troubling is that no exception is raised. for this reason we actually have a validation step in our application ensuring that the app setting is present and that it resolves to a valid type.

Demo

Here is a test demonstrating an extraction and the result.

[Test] public void should_extract_from_pdf() {     var textExtractionResult = new TextExtractor().Extract("Tika.pdf");      textExtractionResult.Text.ShouldContain("pack of pickled almonds");      Console.WriteLine(textExtractionResult); }

Put simply rich documents like this go in.

AndTextextractionresultComes out:

public class TextExtractionResult {     public string Text { get; set; }     public string ContentType { get; set; }     public IDictionary<string, string> Metadata { get; set; }      //toString() override }

Here is the raw output from TIKA:

Conclusion

I hope this helps boost your confidence that you can use Java libraries in your. net code and I hope my example repo will be of balance ance if you need to do some work with tika on. NET platform. enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.