Problem using the Tess4J OCR, i try to work on a screenshot .jpeg - tess4j

ITesseract instance = new Tesseract();
try {
BufferedImage img = null;
img = ImageIO.read(new File("C:\\Users\\nicol\\eclipse-workspace2\\Read\\images\\text.jpeg"));
instance.setDatapath("C:\\Users\\nicol\\eclipse-workspace2\\Read\\tessdata");
String result = instance.doOCR(img);
System.out.println(result);}
catch(TesseractException e){
e.printStackTrace();
}
}
}
And here i have the output :
00:27:23.450 [main] ERROR net.sourceforge.tess4j.Tesseract - Input not set!
java.lang.IllegalStateException: Input not set!
at jai.imageio.core#1.4.0/com.github.jaiimageio.impl.plugins.tiff.TIFFImageReader.getNumImages(TIFFImageReader.java:259)
at tess4j#3.4.8/net.sourceforge.tess4j.util.ImageIOHelper.getIIOImageList(Unknown Source)
at tess4j#3.4.8/net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at tess4j#3.4.8/net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at read.test.main(test.java:18)
I've made sure the file path is correct like i could have seen in some other posts (1st time stackoverflowing, sorry of the editioning that might not be correct)

Related

Locating fxml file from a different package

I am having "tare your hair out" type difficulties while trying to open an fxml file from a controller which is in a different package. the package structure is as follows:
Controller name = LocationController
Controller package = src/com/yas/prayertimeconfig/location/java
FXML file name = AvailableAddresses.fxml
FXML file package = src/com/yas/prayertimeconfig/availableaddresses/java
The code I am using to open up the fxml file from with in LocationController is as follows:
#FXML void btnFindAddress_Click(ActionEvent event) throws IOException {
try{
Parent root1 = FXMLLoader.load(getClass().getResource("/src/com/yas/prayertimeconfig/availableaddresses/java/AvailableAddresses.fxml"));
Stage stage = new Stage();
stage.setTitle("Available Addresses");
stage.setScene(new Scene(root1));
stage.show();
} catch (Exception e) {
System.out.println(e);
}
}
I keep getting:
java.lang.NullPointerException: Location is required.
I have tried every using:
getClass().getResource()
and
getClass().getClassLoader().getResource()
and no joy.
Please help!
Here's how I recreated that error, how I troubleshooted it, and how I ultimately fixed it, in that order.
Full Error Message: 
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3324)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3287)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3255)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3227)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3203)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3196)
at com.company.Main.start(Main.java:29)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
at javafx.graphics#18.0.1/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at javafx.graphics#18.0.1/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics#18.0.1/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at javafx.graphics#18.0.1/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics#18.0.1/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#18.0.1/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
... 1 more
Here's my Start function code that caused the error:
#Override
public void start(Stage stage) throws Exception {
System.out.println("Start()");
Parent root = FXMLLoader.load(getClass().getResource("login-form.fxml"));
stage.setTitle("Login");
Scene scene = new Scene(root, 200, 150);
stage.setScene(scene);
stage.show();
}
The code above basically is trying to load an fxml file on program entry and we can't load it for some reason. (stay tuned)
Basically what that error message is telling me is that it can't load login-form.fxml
For a quick and dirty test, Copy that fxml file that you are trying to load into the same project dir as the the file that has the function that is loading. Just put everything in the same folder. I use copy/paste in IntelliJ's project viewer to do this.
Just make sure that your project "sees" the file. You may have to import your fxml project into the file. 
It will load now for me and I can see my login form on program launch.
Now, let's fix this the "correct" ie. "less hacky" way. 
As another poster commented, relative paths are not a good idea since navigating "up" only works as long as the app is not deployed as jar. You need to start the path at the classpath root starting with /
You can see in my screencap that I have the fxml file I want to import in a different package called "view". In Java projects a "package" is basically a "folder", so I can use "/view/login-form.xml" as a path I can pass to
 
FXMLLoader.load(getClass().getResource("/view/login-form.fxml"))
Remember that "/" in this case is the root of your project, not the root directory of your entire hard drive.

How to deal with RedisMessageListenerContainer death

I've encountered a case where the redis pubsub RedisMessageListenerContainer in my spring boot application died with
ERROR .RedisMessageListenerContainer: SubscriptionTask aborted with exception:
org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is com.lambdaworks.redis.RedisCommandTimeoutException: Command timed out
at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:66)
at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:41)
at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:37)
at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:37)
at org.springframework.data.redis.connection.lettuce.LettuceConnection.convertLettuceAccessException(LettuceConnection.java:330)
at org.springframework.data.redis.connection.lettuce.LettuceConnection.subscribe(LettuceConnection.java:3179)
at org.springframework.data.redis.listener.RedisMessageListenerContainer$SubscriptionTask.eventuallyPerformSubscription(RedisMessageListenerContainer.java:790)
at org.springframework.data.redis.listener.RedisMessageListenerContainer$SubscriptionTask.run(RedisMessageListenerContainer.java:746)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.lambdaworks.redis.RedisCommandTimeoutException: Command timed out
at com.lambdaworks.redis.LettuceFutures.await(LettuceFutures.java:113)
at com.lambdaworks.redis.LettuceFutures.awaitOrCancel(LettuceFutures.java:92)
at com.lambdaworks.redis.FutureSyncInvocationHandler.handleInvocation(FutureSyncInvocationHandler.java:63)
at com.lambdaworks.redis.internal.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:80)
at com.sun.proxy.$Proxy156.subscribe(Unknown Source)
at org.springframework.data.redis.connection.lettuce.LettuceSubscription.doSubscribe(LettuceSubscription.java:63)
at org.springframework.data.redis.connection.util.AbstractSubscription.subscribe(AbstractSubscription.java:142)
at org.springframework.data.redis.connection.lettuce.LettuceConnection.subscribe(LettuceConnection.java:3176)
... 3 common frames omitted
..
I think that shouldn't be an unrecoverable error in the first place because it's a temporary connection issue (and a TransientDataAccessException) but the application apparently needs to deal with exceptions in those case.
Currently this leaves the application in a state that is not acceptable. It merely logs the error but I would either need to kill the application so it gets replaced or better try to restart that container and ideally report via /health that the application is impacted as long as it's not all good.
Is there anything I'm overlooking that is less awkward than either trying to start() the container every x seconds or subclass it and overwrite handleSubscriptionException() and try to act from there? The latter needs much deeper integration with internals than I'd like to have in my code but it's what I so far went with:
RedisMessageListenerContainer container = new RedisMessageListenerContainer() {
#Override
protected void handleSubscriptionException(Throwable ex) {
super.handleSubscriptionException(ex); // don't know what actually happened in here and no way to find out :/
if (ex instanceof RedisConnectionFailureException) {
// handled by super hopefully, don't care
} else if (ex instanceof InterruptedException){
// can ignore those I guess
} else if (ex instanceof TransientDataAccessException || ex instanceof RecoverableDataAccessException) {
// try to restart in those cases?
if (isRunning()) {
logger.error("Connection failure occurred. Restarting subscription task manually due to " + ex, ex);
sleepBeforeRecoveryAttempt();
start(); // best we can do
}
} else {
// otherwise shutdown and hope for the best next time
if (isRunning()) {
logger.warn("Shutting down application due to unknown exception " + ex, ex);
context.close();
}
}
}
};

FileReference.download() works for .jpg .txt but not .dgn files in flex

In downloading files using the following codes, it surprised me that it succeeded in downloading .jpg .txt files BUT .dgn format file return IO Error #2038
Could somebody give me any advice? Thanks in advance.
protected function init(event:FlexEvent):void
{
fileRef = new FileReference();
fileRef.addEventListener(Event.COMPLETE, doEvent);
fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
}
private function doEvent(evt:Event):void
{
var fr:FileReference = evt.currentTarget as FileReference;
switch (evt.type)
{
case "complete":
Alert.show("File : " + fr.name + " download succeed");
break;
default :
Alert.show("Error occur during downloading !!!");
break;
}
protected function downLoadLICMap(event:MouseEvent):void
{
urlReq = new URLRequest("http://svygis/viewphoto/ceddphoto/20130916 raw/1se19d.dgn");
fileRef.download(urlReq);
}
I suspect Flex is not at fault here. It would rather be a server setting issue.
Have you tried opening that URL directly in the browser? You probably will not be able to download the file like that either.
If that's the case, you only need to configure a mime type for the .dgn extension on your web server.

JSoup randomly throws java.io.IOException: stream is closed when running from browser

I'm having some weird JSoup problem when running my JavaFX application from the browser (or as web-start).
When I run from inside the IDE (Eclipse or Netbeans) or as a standalone app, it runs normally. When I try to run as a web-start or from the browser (Chrome), JSoup randomly throws a "java.io.IOException: stream is closed".
The site I'm trying to parse is thepiratebay.sx. When I first run the application (from browser), I get this error. With the application running, if I try to parse again, than it works... sometimes.
The JSoup code:
try {
//TODO: Change to HttpFetcher. This method is reporting "stream is closed" when running on browser
Connection con = Jsoup.connect(url)
.timeout(HTTP_TIMEOUT)
.userAgent(UserAgentGenerator.getUserAgent())
.followRedirects(false);
doc = con.get();
System.out.println("Fetching... " + url);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Parser connect must have timed out, no results. " + url);
fetchFailed[i] = true;
continue;
}
finally {
i++;
if (CommonTFUtils.isAllTrue(fetchFailed)) {
throw new HttpException("Fetcher failed on every URL of " + response.getSite_name());
}
}
And the exception thrown:
CacheEntry[http://thepiratebay.sx/browse/207/0/7]: updateAvailable=true,lastModified=Tue May 14 14:28:16 BRT 2013,length=-1
java.io.IOException: stream is closed
at sun.net.www.http.ChunkedInputStream.ensureOpen(Unknown Source)
at sun.net.www.http.ChunkedInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.close(Unknown Source)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:468)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:410)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:164)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:153)
at com.package.torrent.parser.GenericParser.search(GenericParser.java:147)
at com.package.torrent.parser.GenericParser.browse(GenericParser.java:82)
at com.package.search.TrackerSearch.searchTracker(TrackerSearch.java:69)
at com.package.search.TrackerSearch.searchAllTrackers(TrackerSearch.java:40)
at com.package.search.TrackerSearch.searchAllTrackers(TrackerSearch.java:23)
at com.package.search.MovieBrowser.browseTrackers(MovieBrowser.java:49)
at com.package.ui.browse.BrowseController$MovieBrowserTask.call(BrowseController.java:237)
at com.package.ui.browse.BrowseController$MovieBrowserTask.call(BrowseController.java:213)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1259)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Does anyone have an idea of what might be causing this?
Thanks in advance.
I think I found a solution. Place this code before you ever call JSoup. Apparently, applets and web start set this value to true. Now, I wonder why Sun forces you to access a static variable non-statically.
new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
JSoup doesn't handle well when the URL is cached and treats it as an exception.

jpedal jpg2000 error

I convert pdfs to images using jpedal. This works fine for most of the pdfs but some containing jpeg2000 i continue receiving the following error:
java.lang.RuntimeException: JPeg 2000 Images needs the VM parameter -Dorg.jpedal.jai=true switch turned on
at org.jpedal.parser.PdfStreamDecoder.decodeStreamIntoObjects(Unknown Source)
at org.jpedal.parser.PdfStreamDecoder.decodePageContent(Unknown Source)
at org.jpedal.PDFtoImageConvertor.convert(Unknown Source)
at org.jpedal.PdfDecoder.getPageAsImage(Unknown Source)
at org.jpedal.PdfDecoder.getPageAsImage(Unknown Source)
at com.....
I already set the JVM Parameter in the JAVA_OPTS, the run configuration of my tomcat and also in program code using:
System.setProperty("org.jpedal.jai", "true");
PdfDecoder decode_pdf = new PdfDecoder(true);
FontMappings.setFontReplacements();
decode_pdf.openPdfArray(pdf_file);
also the 3 JAI libs are on my build path.
So I don't know what else I have to do?
My complete code for the conversion is:
List<BufferedImage> images = new LinkedList<BufferedImage>();
System.setProperty("org.jpedal.jai", "true");
PdfDecoder decode_pdf = new PdfDecoder(true);
FontMappings.setFontReplacements();
decode_pdf.openPdfArray(pdf_file);
decode_pdf.setExtractionMode(0, 1f); //do not save images
for (int i = 1; i<= decode_pdf.getPageCount(); i++)
{
images.add(decode_pdf.getPageAsImage(i));
}
decode_pdf.closePdfFile();
Any sugestions?
Activate jai for jpedal
System.setProperty("org.jpedal.jai", "true");
A better solution (than the article from Mark Stephens blog) is to re-register the
provider, because this only has to be done once:
IIORegistry registry = IIORegistry.getDefaultInstance();
registry.registerServiceProvider(new com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi());
registry.registerServiceProvider(new com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi());
Of course JAI libs need to be in the classpath to work correctly.
I found the answer to this problem here.
When in a Tomcat environment you have to disable the JreLeakPreventionListener in server.xml then it works just fine.

Resources