Skip to content

Commit 3883e34

Browse files
Issue #265: Prevent JVM crash when wrong datapath given
1 parent c8386ea commit 3883e34

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

src/main/java/net/sourceforge/tess4j/ITesseract.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ default String doOCR(BufferedImage bi, String filename, List<Rectangle> rects) t
136136
* Sets tessdata path.
137137
*
138138
* @param datapath the tessdata path to set
139+
* @throws IllegalArgumentException if the given datapath is not an existing directory
139140
*/
140141
void setDatapath(String datapath);
141142

src/main/java/net/sourceforge/tess4j/Tesseract.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.nio.ByteBuffer;
2525
import java.nio.FloatBuffer;
2626
import java.nio.IntBuffer;
27+
import java.nio.file.Paths;
2728
import java.util.*;
2829
import javax.imageio.IIOImage;
2930
import javax.imageio.ImageIO;
@@ -87,6 +88,10 @@ public Tesseract() {
8788
datapath = "./";
8889
}
8990
}
91+
File datapathFile = new File(datapath);
92+
if (!datapathFile.exists() || !datapathFile.isDirectory()) {
93+
throw new IllegalArgumentException("Given datapath " + datapath + " is not an existing directory.");
94+
}
9095
}
9196

9297
/**
@@ -114,6 +119,10 @@ protected TessBaseAPI getHandle() {
114119
*/
115120
@Override
116121
public void setDatapath(String datapath) {
122+
File datapathFile = new File(datapath);
123+
if (!datapathFile.exists() || !datapathFile.isDirectory()) {
124+
throw new IllegalArgumentException("Given datapath " + datapath + " is not an existing directory.");
125+
}
117126
this.datapath = datapath;
118127
}
119128

src/test/java/net/sourceforge/tess4j/TesseractTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,4 +407,11 @@ public void testGetOSD() {
407407
assertEquals("Latin", result.getScriptName());
408408
assertTrue(result.getScriptConf() > 0);
409409
}
410+
411+
@Test
412+
public void testSetDatapath() {
413+
logger.info("testSetDatapath");
414+
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> instance.setDatapath("non-existent-datapath"));
415+
assertEquals("Given datapath non-existent-datapath is not an existing directory.", e.getMessage());
416+
}
410417
}

0 commit comments

Comments
 (0)