Java OCR program using tesseract in Windows - java

I just started trying to write a simple java code to do some simple OCR, using the code and advice found here.
I have installed libraries, and the project in the IDE (NetBeans) looks like the picture I have attached.
I'm getting these errors:
10:47:30.099 [main] WARN net.sourceforge.tess4j.util.LoadLibs - Source 'C:\Users\Simon%20Bothner\Documents\NetBeansProjects\OCRTest\build\classes\win32-x86-64' does not exist
java.io.FileNotFoundException: Source
'C:\Users\Simon%20Bothner\Documents\NetBeansProjects\OCRTest\build\classes\win32-x86-64' does not exist
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1074)
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:1038)
at net.sourceforge.tess4j.util.LoadLibs.copyResources(LoadLibs.java:138)
at net.sourceforge.tess4j.util.LoadLibs.extractTessResources(LoadLibs.java:105)
at net.sourceforge.tess4j.util.LoadLibs.<clinit>(LoadLibs.java:59)
at net.sourceforge.tess4j.TessAPI.<clinit>(TessAPI.java:42)
at net.sourceforge.tess4j.Tesseract.init(Tesseract.java:367)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:280)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:212)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:196)
at Main.main(Main.java:15)
Exception in thread "main" java.lang.UnsatisfiedLinkError: The specified module could not be found.
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:263)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:403)
at com.sun.jna.Library$Handler.<init>(Library.java:147)
at com.sun.jna.Native.loadLibrary(Native.java:502)
at com.sun.jna.Native.loadLibrary(Native.java:481)
at net.sourceforge.tess4j.util.LoadLibs.getTessAPIInstance(LoadLibs.java:77)
at net.sourceforge.tess4j.TessAPI.<clinit>(TessAPI.java:42)
at net.sourceforge.tess4j.Tesseract.init(Tesseract.java:367)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:280)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:212)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:196)
at Main.main(Main.java:15)
C:\Users\Simon Bothner\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I tried to use this tutorial, but I seemed to be missing a .dll, the liblept168.dll...
Can someone help me with this? I'm quite new at this and can't seem to get this to work...
Thanks a lot! :)

Step 1: http://tphangout.com/how-to-use-the-tesseract-api-to-perform-ocr-in-your-java-code/
Open the link above and see how to install Tesseract in Java properly.
Step 2: After reading it, if you still get the error like "library not open", download Microsoft Visual Studio >12.0, and also update your JDK version (I also get the same error).
Step 3:
public class tesserct
{
public static void main(String[] args)
{
//System.setProperty("jna.library.path", "64".equals(System.getProperty("sun.arch.data.model")) ? "lib/win32-x86" : "lib/win32-x86-64");
System.setProperty("jna.library.path", "32".equals(System.getProperty("sun.arch.data.model")) ? "lib/win32-x86" : "lib/win32-x86-64");
File imageFile = new File("F:\\Wallpaper & photo\\wallpaper\\holi wollpepar\\happy-holi-2013-hd-wallpaper1.jpg");
ITesseract instance = new Tesseract(); // JNA Interface Mapping
// ITesseract instance = new Tesseract1(); // JNA Direct Mapping
File tessDataFolder = LoadLibs.extractTessResources("tessdata"); // Maven build bundles English data
instance.setDatapath(tessDataFolder.getParent());
try {
String result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
run the code above on your NetBeans, and try it.

Related

Compiling JD2XX for Raspberry Pi

For Openhab2 there is a binding add-on called RFXCOM. The problem however is that this add-on uses JD2XX which is not compatible with the ARM architecture of the Raspberry Pi.
I have found a Github repository with the source that you can use to compile a *.so file: https://github.com/0x6a77/JD2XX
A little change to the Makefile to use the correct Java path (zulu-8-armhf-embedded instead of (oracle-7).
Running sudo make jni creates a *.so file which I copied to /usr/lib (inside the java library path). However I still get the error that the Raspberry Pi can't open the shared library due to it being 32-bit. How can you compile a shared library that works for ARM with the source provided by the Github repository.
Error message:
java.lang.UnsatisfiedLinkError:
/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so:
/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so: cannot open shared object file:
No such file or directory (Possible cause: can't load IA 32-bit .so on a ARM-bit platform)
The Raspberry Pi has a fresh installation of Openhabian.
Link to the issue on Github: https://github.com/openhab/openhab2-addons/issues/2316#issuecomment-304795652
EDIT:
11:00:52.291 [ERROR] [rnal.discovery.RFXComBridgeDiscovery] - Error occurred during discovery
java.io.IOException: device not found (2)
at jd2xx.JD2XX.listDevices(Native Method)
at jd2xx.JD2XX.listDevicesByDescription(JD2XX.java:785)
at org.openhab.binding.rfxcom.internal.discovery.RFXComBridgeDiscovery.discoverRfxcom(RFXComBridgeDiscovery.java:89)
at org.openhab.binding.rfxcom.internal.discovery.RFXComBridgeDiscovery.startScan(RFXComBridgeDiscovery.java:66)
at org.eclipse.smarthome.config.discovery.AbstractDiscoveryService.startScan(AbstractDiscoveryService.java:199)
at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScan(DiscoveryServiceRegistryImpl.java:382)
at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScans(DiscoveryServiceRegistryImpl.java:358)
at org.eclipse.smarthome.config.discovery.internal.DiscoveryServiceRegistryImpl.startScan(DiscoveryServiceRegistryImpl.java:216)
at org.eclipse.smarthome.io.rest.core.discovery.DiscoveryResource.scan(DiscoveryResource.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)[:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)[:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498)[:1.8.0_121]
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)[157:org.glassfish.jersey.core.jersey-common:2.22.2]
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)[158:org.glassfish.jersey.core.jersey-server:2.22.2]
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)[155:org.glassfish.jersey.containers.jersey-container-servlet-core:2.22.2]
at com.eclipsesource.jaxrs.publisher.internal.ServletContainerBridge.service(ServletContainerBridge.java:76)[10:com.eclipsesource.jaxrs.publisher:5.3.1.201602281253]
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
at org.ops4j.pax.web.service.jetty.internal.HttpServiceServletHandler.doHandle(HttpServiceServletHandler.java:71)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)[79:org.eclipse.jetty.security:9.2.19.v20160908]
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.doHandle(HttpServiceContext.java:287)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)[81:org.eclipse.jetty.servlet:9.2.19.v20160908]
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.ops4j.pax.web.service.jetty.internal.JettyServerHandlerCollection.handle(JettyServerHandlerCollection.java:80)[172:org.ops4j.pax.web.pax-web-jetty:4.3.0]
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.server.Server.handle(Server.java:499)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)[80:org.eclipse.jetty.server:9.2.19.v20160908]
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)[72:org.eclipse.jetty.io:9.2.19.v20160908]
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)[83:org.eclipse.jetty.util:9.2.19.v20160908]
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)[83:org.eclipse.jetty.util:9.2.19.v20160908]
at java.lang.Thread.run(Thread.java:745)[:1.8.0_121]
11:01:02.868 [WARN ] [e.sshd.server.channel.ChannelSession] - Unknown pty opcode value: 42
In the JD2XX.java file, you can see the mechanism how to load a dll, so or some other type of library depending on OS.
static {
String dataModel = System.getProperty("sun.arch.data.model");
String osName = System.getProperty("os.name").toLowerCase();;
StringBuilder lib = new StringBuilder("/jni/");
if (osName.contains("win"))
lib.append("win/");
else if (osName.contains("linux"))
lib.append("linux/");
else if (osName.contains("mac"))
lib.append("mac/");
else
throw new UnsatisfiedLinkError("Loading JD2XX JNI: Unsupported operating system ("+osName+")");
if (dataModel.equals("32"))
lib.append("x86_32/");
else if (dataModel.equals("64"))
lib.append("x86_64/");
else
throw new UnsatisfiedLinkError("Loading JD2XX JNI: Unknown runtime data model ("+dataModel+")");
if (osName.contains("win"))
lib.append("jd2xx.dll");
else if (osName.contains("linux"))
lib.append("libjd2xx.so");
else if (osName.contains("mac"))
lib.append("libjd2xx.jnilib");
try {
NativeUtils.loadLibraryFromJar(lib.toString());
} catch (IOException e) {
throw new UnsatisfiedLinkError(e.getMessage());
}
}
The loadLibraryFromJar method from NativeUtils creates temp directory and copy the right library for OS to temp directory then call the System.load method eventually.
So, I think you should modify this part of source code like the code as follows, if possible.
static
{
System.load("/var/lib/openhab2/tmp/libjd2xx5892592723514582617.so");
}
or
static
{
System.load("/usr/lib/libjd2xx5892592723514582617.so");
}
There are several ways to make this job work re-setting the 'java.library.path' order to indicate the /usr/lib directory first then use the code below.
Or you can rename the library name, libjd2xx5892592723514582617.so to libjd2xx.so in the /usr/lib which is usually in the 'LD_LIBRARY_PATH' variable.
then, our code in the JD2XX.java can be used instead,
static
{
System.loadLibrary("jd2xx");
}
I think it works..

StanfordNLP OpenIE 4 error

I've been encountering this error:
I ran the OpenIE 4.1 binary but got the following error:
Exception in thread "main" java.lang.NullPointerException at
com.googlecode.clearnlp.tokenization.EnglishTokenizer.protec‌​tEmoticons
(EnglishTokenizer.java:335) at
com.googlecode.clearnlp.tokenization.EnglishTokenizer.getTok‌​enList(En
glishTokenizer.java:109) at
com.googlecode.clearnlp.tokenization.AbstractTokenizer.getTo‌​kens(AbstractTokenizer.java:58) at
edu.knowitall.tool.tokenize.ClearTokenizer.tokenize(ClearTok‌​enizer.sc ala:22)
I've looked up a few sources and found a comment by Yangrui who also had this problem in the past. But there are no solutions. I've checked my openie.4.1.jar file and the com.googlecode.clearnlp.tokenization.EnglishTokenizer.protectEmoticon exists.
Hope someone can help shed some light on this. Thank you in advance.
I've managed to solve this error. The issue lies with the compilation of the OpenIE 4.0 JAR and OpenIE 4.1 JAR files I downloaded from the official website. (http://knowitall.github.io/openie/).
How to solve? Compile the classes yourself.
Go to https://github.com/knowitall/openie/releases
Choose a release. (I chose 4.1.3)
Download the zip file and unzip the file.
Use terminal and redirect to the folder directory.
Run 'sbt package' and it will start compiling.
Your final JAR file will be found in the target folder/scala-2.10/{openie-assembly-VERSION.jar}
Note: There could be some changes you need to make to your code if you are running OpenIE as a dependency. The code for test is as follows:
OpenIE openIE = new OpenIE(new ClearParser(new ClearPostagger(new ClearTokenizer())), new ClearSrl(), false, false);
Seq<Instance> extractions = openIE.extract("Obama is the president of the United States");
Iterator<Instance> iterator = extractions.iterator();
while (iterator.hasNext()) {
Instance inst = iterator.next();
StringBuilder sb = new StringBuilder();
sb.append(inst.confidence()).append("\t\t")
.append(inst.extr().arg1().text()).append("\t\t")
.append(inst.extr().rel().text()).append("\t\t");
Iterator<Argument> argIter = inst.extr().arg2s().iterator();
while (argIter.hasNext()) {
Part arg = argIter.next();
sb.append(arg.text()).append("; ");
}
System.out.println(sb.toString());
}
I hope this will help someone in the future.

Alloy API resulting in java.lang.UnsatisfiedLinkError

I'm currently using the Alloy Analyzer API to build a program, and getting some peculiar behavior. Specifically, if I open a file and parse it (using CompUtil.parseEverything), then make a new Command and call TranslateAlloyToKodkod.execute_command on the parsed file and newly created command using MiniSat with UNSAT core, it runs fine. However, later in execution, my program parses a second input file (also using CompUtil.parseEverything), gets another world, makes a new command, and then I try to call TranslateAlloyToKodkod.execute_command again, it throws the following error:
ERROR: class edu.mit.csail.sdg.alloy4.ErrorFatal: The required JNI library cannot be found:
java.lang.UnsatisfiedLinkError: no minisatproverx5 in java.library.path
edu.mit.csail.sdg.alloy4compiler.translator.TranslateAlloyToKodkod.execute_command(TranslateAlloyToKodkod.java:390)
Does anyone have any idea why this is thrown the second time, but not the first?
To summarize, I have something similar to the following:
Module someWorld = CompUtil.parseEverything_fromFile(rep, null, "someFile.als");
//For the following, "sig" is a sig in someWorld.getAllReachableSigs();
Command command = sig.not();
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.MiniSatProverJNI;
A4Solution ans =
TranslateAlloyToKodkod.execute_command(rep, someWorld, command, options);
//No thrown error
Module someOtherWorld = CompUtil.parseEverything_fromFile(rep, null, "someOtherFile.als");
//For the following, "sig" is a sig in someOtherWorld.getAllReachableSigs();
Command commandTwo = sig.not();
A4Solution ansTwo =
TranslateAlloyToKodkod.execute_command(rep, someOtherWorld, commandTwo, options);
//Thrown error above. Why?
I tried to reproduce this behavior, but I couldn't. If I don't add MiniSat binaries to the LD_LIBRARY_PATH environment variable, I get the exception you mentioned the very first time I invoke execute_command. After configuring LD_LIBRARY_PATH, the exception doesn't happen.
To configure LD_LIBRARY_PATH:
(1) if using Eclipse, you can right-click on one of your source folders, choose Build Path -> Configure Build Path, then on the "Source" tab make sure that "Native library location" points to a folder in which MiniSat binaries reside.
(2) if running from the shell, just add the path to a folder with MiniSat binaries to LD_LIBRARY_PATH, e.g., something like export LD_LIBRARY_PATH=alloy/extra/x86-linux:$LD_LIBRARY_PATH.
Here is the exact code that I was running, and everything worked
public static void main(String[] args) throws Exception {
A4Reporter rep = new A4Reporter();
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.MiniSatProverJNI;
Module someWorld = CompUtil.parseEverything_fromFile(rep, null, "someFile.als");
Command command = someWorld.getAllCommands().get(0);
A4Solution ans = TranslateAlloyToKodkod.execute_command(rep, someWorld.getAllReachableSigs(), command, options);
System.out.println(ans);
Module someOtherWorld = CompUtil.parseEverything_fromFile(rep, null, "someOtherFile.als");
Command commandTwo = someOtherWorld.getAllCommands().get(0);
A4Solution ansTwo = TranslateAlloyToKodkod.execute_command(rep, someOtherWorld.getAllReachableSigs(), commandTwo, options);
System.out.println(ansTwo);
}
with "someFile.als" being
sig A {}
run { some A } for 4
and "someOtherFile.als"
sig A {}
run { no A } for 4
I use alloy4.2.jar as a library in my eclipse plugin project.
A4Reporter rep = new A4Reporter();
Module world = CompUtil.parseEverything_fromFile(rep, null, "civi.als");
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.SAT4J;
options.skolemDepth = 1;
When I use SAT4J, the default solver, the problem mentioned here will not show up. But another exception comes out. The reason is that my civi.als file need Integer model, which located in alloy4.2.jar under the folder /models/util/. But when I run the application, it tries to find the file util/Integer.als directly. That causes the exception. Is it possible to fix that problem?
Besides, I also tried to put the alloy4.2.jar in eclipse plugin project and run my application as an eclipse application (running my application as a plugin). With the default solver, the application has no problem at all. But when I switch to MiniSatProverJNI, the problem mentioned here comes out (I have set the alloy4.2.jar as classpath).

How to use kyotocabinet(JNI) in playframework?

I'm tackling to use kyotocabinet in Playframework.
and following error occurred.
I'm using Eclipse and playframework-1.2.3.
and kyotocabinet is native library so I'm using its Java-Binding.
the reproduce code is simple.
in controller:
public static void somePage() {
DB db = new DB();//error occurred
render();
}
Internal Server Error (500) for request GET /
Execution exception (In /app/controllers/TestApp.java around line 45)
NoClassDefFoundError occured : Could not initialize class kyotocabinet.DB
play.exceptions.JavaExecutionException: Could not initialize class kyotocabinet.DB
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:229)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class kyotocabinet.DB
at controllers.TestApp.somePage(TestApp.java:45)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:546)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:500)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:476)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:471)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:159)
... 1 more
build in Eclipse was completed but error occured at runtime.
I guess it is because kyotocabinet.dll is missing.(only jkyotocabinet.jar was found)
I configured the location of kyotocabinet.dll to Java Build Path > Source > Native Library Location of my playframework project.
and it was good in other projects.
How to use native library in playframework?
any example or tutorial?
Play.getFile and System.load didn't work.
package controllers;
import play.Play;
import play.jobs.*;
#OnApplicationStart
public class Bootstrap extends Job {
public void doJob() {
String path = "D:/MyProject/lib/jkyotocabinet.dll";
Play.getFile(path);
//System.load(path); if this was enabled, following error occurred: "Native Library D:\MyProject\lib\jkyotocabinet.dll already loaded in another classloader". so I guess the dll was loaded.
System.out.println("bootstrap loaded");//this is displayed.
}
}
UnsatisfiedLinkError occured : no jkyotocabinet in java.library.path
this Japanese blog tells Play!Framework cannot load native library.
http://d.hatena.ne.jp/hjym_u/20110702/1309609277
I already tried these: Absolute path, Relative path, System.load, System.loadLibrary, Play.getFile.
as conclusive approach, I put jkyotocabinet.dll to current directory(D:/MyProejct/), and wrote this code.
public static void somePage(){
File f = Play.getFile("jkyotocabinet.dll");
if(f != null && f.isFile() && f.canRead() && f.canExecute()){//true
DB db = new DB();//error occured. it reached here.
}
render();
}
Execution exception
NoClassDefFoundError occured : Could not initialize class kyotocabinet.DB
Play.getFile found the path "jkyotocabinet.dll" so jkyotocabinet.dll is in current directory so jvm should find it automatically.
anyone can use JNI in playframework?
finally, I could use kyotocabinet as PROD mode but not DEV mode.
Project/conf/application.conf
#application.mode=dev
application.mode=prod
I assume you just need to load the dll into Java via System.load
If you place the ddl on your project, you may load it via Play.getFile inside your #OnApplicationStart controller. This should make it available to your application while the JVM is alive.
EDIT:
#KenichiYamamoto Play.getFile gets files from the application path. You are trying to use a full path in there.
Read this about loading the file in a container. It may be that (due to Play compile-reload system) you are hitting the "already loaded" error. Try to follow the example by adding the System.load inside a static block in your #OnApplicationStart
Do as pere says but use the relative path from your application root. Not the absolute path. I.e. Play.getFile("lib\myfile.dll")

java.awt.Desktop.open doesn’t work with PDF files?

It looks like I cannot use Desktop.open() on PDF files regardless of location. Here's a small test program:
package com.example.bugs;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class DesktopOpenBug {
static public void main(String[] args)
{
try {
Desktop desktop = null;
// Before more Desktop API is used, first check
// whether the API is supported by this particular
// virtual machine (VM) on this particular host.
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
for (String path : args)
{
File file = new File(path);
System.out.println("Opening "+file);
desktop.open(file);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If I run DesktopOpenBug with arguments c:\tmp\zz1.txt c:\tmp\zz.xml c:\tmp\ss.pdf (3 files I happen to have lying around) I get this result: (the .txt and .xml files open up fine)
Opening c:\tmp\zz1.txt
Opening c:\tmp\zz.xml
Opening c:\tmp\ss.pdf
java.io.IOException: Failed to open file:/c:/tmp/ss.pdf. Error message:
The parameter is incorrect.
at sun.awt.windows.WDesktopPeer.ShellExecute(Unknown Source)
at sun.awt.windows.WDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
at com.example.bugs.DesktopOpenBug.main(DesktopOpenBug.java:21)
What the heck is going on? I'm running WinXP, I can type "c:\tmp\ss.pdf" at the command prompt and it opens up just fine.
edit: if this is an example of Sun Java bug #6764271 please help by voting for it. What a pain. >:(
I never knew about this Desktop command, untill recently through this post:
would Java's Runtime.getRuntime().exec() run on windows 7?
Previously i have been using:
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL "+ myfile);
And it has always worked for me. If your method does not work, may be you can think about try this command.
If you switch the order of your arugments does that cause one of the other files to get that same error. I wonder if you need to trim the end of the path before calling the File constructor.
umm...yeah ignore that... check the documentation of Desktop.open. open throws an IO exception "if the specified file has no associated application or the associated application fails to be launched " ... also from the top of the page... "The mechanism of registereing, accessing, and launching the associated application is platform-dependent. "
code for the Desktop class: http://fuseyism.com/classpath/doc/java/awt/Desktop-source.html
The open method calls DesktopPeer.open.
DesktopPeer source: http://www.jdocs.com/javase/7.b12/java/awt/peer/DesktopPeer.html
DesktopPeer is implementation specific.
Here is source for a Windows-specific implementation:
http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Platform/windows/sun/awt/windows/WDesktopPeer.java.htm
open->ShellExecute->(Native)ShellExecute
Native ShellExecute is a wrapper for Win32 ShellExecute. Here is info on the function.
http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx
My suggestion for a work around would be to write your own implmentation of the ShellExecute function. Here is source from someone who did it. http://www.heimetli.ch/shellexec.html

Categories

Resources