I try to do an ocr application for Mirth with Java and Tesseract.I export the project in jar file and call in Mirth with Javascript that did a hello world application.I believe that I add the jar files right way.However I have a problem in Java OCR,so I get this error,
ERROR (com.mirth.connect.connectors.js.JavaScriptDispatcher:193): Error evaluating JavaScript Writer (JavaScript Writer "RTF>DCM" on channel b469e5af-a78d-41ca-86a0-a7b507799a4d).
java.lang.NoClassDefFoundError: net/sourceforge/tess4j/TesseractException
Project Screenshot
package com.imagerad.ocr;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class JavaOCRTest {
static String Tc;
static String phone;
static String date;
public static void main(String[] args) throws IOException{
}
public String returnText(String fileName) throws IOException{
Files.walk(Paths.get(fileName)).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
File imageFile = filePath.toFile();
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(imageFile);
int i=result.indexOf("Numarasn: ");
int j=result.indexOf("Tel No:");
int k=result.indexOf("Bilgllendirme Tarihl:");
Tc = result.substring(i+10, i+22);
phone = result.substring(j+8,j+23);
date = result.substring(k+22,k+32);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
});
return Tc+""+phone+""+date;
}
public String returnTC() throws IOException{
return Tc;
}
public String returnPhone() throws IOException{
return phone;
}
public String returnDate() throws IOException{
return date;
}
}
Thank you so much for your helps.
You have to download the Tess4J.jar and add it to the classpath. This jar contains the missing class net/sourceforge/tess4j/TesseractException
Related
I ve been working on JAVA FX application which uploads certain file on remote computer and then executing mentioned file via cmd. It's working with all platforms Windows, Linux and Mac but I have one problem.
Problem: when file is bigger GUI totally crashes resulting in unable to click or do anything (App Not responding) eventhough file is uploaded and run via CMD after I check it.
I've been reading that JAVA FX is using single thread for GUI and all operations so basicly I need to create separate thread for GUI and separate thread for other code. I ve been trying to figure this out for pass 3 days and couldnt come up with solution. My program consists of more classes which depends on each other resulting to be harder to come up with solution. Will anybody be kind to help me with this problem?
Please bare in mind I m not a programmer this is kind of my hobby I know this programm does not fullfill coding standards.
Code:
Main:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class App extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("GUI.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 600, 420);
stage.setTitle("App name");
stage.setScene(scene);
stage.setResizable(false);
Image icon = new Image("icon.png");
stage.getIcons().add(icon);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Class Uploader:
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import java.io.IOException;
public class Uploader {
public String remoteHost;
public String username;
public String password;
public String path;
public String filename;
public Uploader(String remoteHost,String username,String password, String path, String filename){
this.remoteHost = remoteHost;
this.username = username;
this.password = password;
this.path = path;
this.filename = filename;
}
public SSHClient setupSshj() throws IOException {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(remoteHost);
client.authPassword(username, password);
return client;
}
public void whenUploadFileUsingSshj_thenSuccess(String osType) throws IOException {
String localFilePath = "";
String remoteDirPath = "";
SSHClient sshClient = setupSshj();
System.out.println("Connection established...");
SFTPClient sftpClient = sshClient.newSFTPClient();
if (osType.equals("win")){
remoteDirPath = "C:\\"+filename;
localFilePath = path+filename;
}
else if (osType.equals("lin")) {
remoteDirPath = "//tmp//" + filename;
localFilePath = path+filename;
}
else{
remoteDirPath = "Downloads//" + filename;
localFilePath = path+filename;
}
sftpClient.put(localFilePath, remoteDirPath);
System.out.println("File uploaded successfully...");
sftpClient.close();
sshClient.disconnect();
}
}
class Cmdrunner:
import com.jcraft.jsch.JSchException;
import com.pastdev.jsch.DefaultSessionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CommandRunner {
public CommandRunner(String username, String hostname, String password, String cmd) throws JSchException, IOException {
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(username, hostname, 22);
Map props = new HashMap<String, String>();
props.put("StrictHostKeyChecking", "no");
sessionFactory.setConfig(props);
sessionFactory.setPassword(password);
com.pastdev.jsch.command.CommandRunner runner = new com.pastdev.jsch.command.CommandRunner(sessionFactory);
com.pastdev.jsch.command.CommandRunner.ExecuteResult result = runner.execute(cmd);
System.out.println("cmd successfully executed...");
runner.close();
}
}
class Controler:
import com.jcraft.jsch.JSchException;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import java.io.IOException;
public class Controller {
String osType = "win";
#FXML
public TextField host_input;
public TextField user_input;
public TextField pass_input;
public TextField path_input;
public TextField file_name;
//public Label state_id;
#FXML
public void winOs() { osType = "win";
file_name.setText("File name");
}
public void linOs() {
osType = "lin";
file_name.setText("Filename");
}
public void macOs() { osType = "mac"; }
public void upload() throws IOException, JSchException {
//state_id.setText("");
Uploader upload = new Uploader(host_input.getText(),user_input.getText(),pass_input.getText(),
path_input.getText(), file_name.getText());
upload.whenUploadFileUsingSshj_thenSuccess(osType);
if (osType.equals("win")){
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
String.format("C:\\%s --silent --accepteula",file_name.getText()));
//state_id.setText("Installer uploaded and run successfully!");
}
if (osType.equals("lin")){
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
"chmod 777 //tmp//"+file_name.getText());
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
String.format("echo %s | sudo -S //tmp//%s", pass_input.getText(), file_name.getText()));
}
else {
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
"chmod 777 Downloads//"+file_name.getText());
new CommandRunner(user_input.getText(),host_input.getText(),pass_input.getText(),
"Downloads//"+file_name.getText());
}
}
public void exit() {
Platform.exit();
}
}
I would like to obtain the most accurate File typed representation of a String that is supposed to refer to a local (existing) file in one of several forms like:
String file0 = "/home/my_user/file.txt"
String file1 = "file:///home/my_user/file.txt"
String file2 = "file.txt"; // assuming that the working dir is /home/my_user.
Is there a (quasy) single liner using the standard library or perhaps a common third party like apache-commons that would do the trick?
Thanks.
You can define your own function for this purpose. Given below is the function definition and test code:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String file0 = "/Users/arvind.avinash/file.txt";
String file1 = "file:///Users/arvind.avinash/file.txt";
String file2 = "file.txt"; // assuming that the working dir is /Users/arvind.avinash.
System.out.println(getFile(file0).exists());
System.out.println(getFile(file1).exists());
System.out.println(getFile(file2).exists());
}
static File getFile(String pathOrUri) {
URI uri;
File file = null;
try {
uri = new URL(pathOrUri).toURI();
} catch (MalformedURLException e) {
return new File(pathOrUri);
} catch (URISyntaxException e) {
return new File(pathOrUri);
}
if (uri != null) {
file = new File(uri);
}
return file;
}
}
Output:
true
true
true
[Update]
Given below is a more simplified version:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String file0 = "/Users/arvind.avinash/file.txt";
String file1 = "file:///Users/arvind.avinash/file.txt";
String file2 = "file.txt"; // assuming that the working dir is /Users/arvind.avinash.
System.out.println(getFile(file0).exists());
System.out.println(getFile(file1).exists());
System.out.println(getFile(file2).exists());
}
static File getFile(String pathOrUri) {
URI uri;
try {
uri = new URL(pathOrUri).toURI();
} catch (MalformedURLException | URISyntaxException e) {
return new File(pathOrUri);
}
return new File(uri);
}
}
You be able to call new File(x) on examples 1 and 3 and it should work.
As for #2, you can create a URI, and then create File from that. In fact I think they all probably will work using URI
String fileStr = "file:///home/my_user/file.txt";
try {
URI uri = new URI(fileStr);
File f = new File(uri);
} catch (URISyntaxException ex) { ...}
Im trying to use relative path to read a file but the path cant be found.
maxSuccession is the name of my project
This is my workspace path: C:\Programming
This is my project's path C:\Programming\MaxSuccessions\maxSuccessions
This is my filepath C:\Programming\MaxSuccessions\Tests\test1\00.in.txt
package test1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) throws IOException {
String myPath="..\\MaxSuccessions\\Tests\\test1\\";
Scanner sc = new Scanner(new File(myPath+"00.in.txt"));
System.out.println(sc.nextInt());
}
}
If your class file and required file are in the same directory, you can try this code:
public static void main(String[] args) {
String fileName = "00.in.txt"; //relative path from the path of your class.
try {
Scanner sc = new Scanner(Test.class.getResource(fileName).openStream());
System.out.println(sc.nextInt());
} catch (IOException e) {
e.printStackTrace();
}
}
I have a very different situation to deal with. Something never seen before.
I have a codebase which is not a maven based project. It basically is set of Pig Script that are executed on Hadoop Cluster.
Now there is requirement to test these scripts using PigUnit, so I created a maven based project with all dependencies needed for the project.
Visually it looks like
user_mapper/
src/main/
user.pig
other.pig
test/
pom.xml
src/java/
/UserTest.java
/OtherTest.java
As you could see, test is a maven based project in itself.
What I need
In UserTest.java I want to refer to relative path of user.pig
How can I provide a relative path in UserTest.java?
Try the following code (internally uses commons-io jar)
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileReader {
Logger logger = Logger.getLogger(FileReader.class.getName());
static String webAppPath;
private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );
private InputStream inputStream;
private static FileReader fileReader;
public String getAbsolutePath(Class appClass, String relativePath) {
try {
String parentPath = "";
if (StringUtils.isNotBlank(webAppPath)) {
parentPath = webAppPath;
} else {
parentPath = appClass.getProtectionDomain().getCodeSource().getLocation().getPath();
}
String osAppropriatePath = IS_WINDOWS ? parentPath.substring(1) : parentPath;
String absolutePath = osAppropriatePath + relativePath;
File file = new File(absolutePath);
if (!file.exists()) {
FileUtils.writeStringToFile(file, IOUtils.toString(readFile(relativePath), "UTF-8"));
}
return absolutePath;
} catch (IOException ioe) {
logger.log(Level.SEVERE, null, ioe);
return relativePath;
}
}
public void closeFileReader() {
synchronized (this) {
try {
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(FileReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private FileReader() {
}
public static FileReader getInstance() {
return new FileReader();
}
public static String getWebAppPath() {
return webAppPath;
}
public static void setWebAppPath(String webAppPath) {
FileReader.webAppPath = webAppPath;
}
}
And call the class to get the relative path as follows
FileReader.getInstance().getAbsolutePath(user.pig, "user.pig");
I solved this issue by using java.io.File as
final String filePath = new File("../src/user.pig").getAbsolutePath();
package com.teamsite.client;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Hashtable;
import com.interwoven.cssdk.common.CSClient;
import org.apache.commons.lang.StringUtils;
import com.interwoven.cssdk.access.CSUser;
import com.interwoven.cssdk.common.CSClient;
import com.interwoven.cssdk.common.CSException;
import com.interwoven.cssdk.filesys.CSAreaRelativePath;
import com.interwoven.cssdk.workflow.CSExternalTask;
import com.interwoven.cssdk.workflow.CSTask;
import com.interwoven.cssdk.workflow.CSURLExternalTask;
import com.interwoven.cssdk.workflow.CSWorkflow;
import java.util.logging.*;
public class ApplicationEdition implements CSURLExternalTask{
private static String userid;
private static String cssdkconfigfile;
private String applicationName;
private String applicationEditionPath;
private static CSClient csClient;
public static final String KEY_TARGET_TASK_NAME = "target_task_name";
private String transitionComment = "Auditing for deployed files ";
private String transition = "";
public static String getCssdkconfigfile() {
return cssdkconfigfile;
}
public static void setCssdkconfigfile(String cssdkconfigfile) {
ApplicationEdition.cssdkconfigfile = cssdkconfigfile;
}
private static CSClient getCsClient() {
return csClient;
}
private static void setCsClient(CSClient csClient) {
ApplicationEdition.csClient = csClient;
}
private static String getUserid() {
return userid;
}
private static void setUserid(String userid) {
ApplicationEdition.userid = userid;
}
private String getApplicationName() {
return applicationName;
}
private void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
private String getApplicationEditionPath() {
return applicationEditionPath;
}
private void setApplicationEditionPath(String applicationEditionPath) {
this.applicationEditionPath = applicationEditionPath;
}
#Override
public void execute(CSClient client, CSExternalTask currentTask, Hashtable params) throws CSException {
String userId = client.toString();
String cssdkconfigfile = "D:\\iw-home\\TeamSite\\cssdk\\cssdk.cfg";
setUserid(userId);
setCssdkconfigfile(cssdkconfigfile);
String targetTaskName = currentTask.getVariable(KEY_TARGET_TASK_NAME);
CSUser thisTaskOwner = currentTask.getOwner();
String thisTaskOwnerAddress = thisTaskOwner.getEmailAddress();
String branchName = currentTask.getArea().getBranch().getName();
CSAreaRelativePath[] files = currentTask.getFiles();
String Area = currentTask.getArea().getName();
System.err.println("*********************************************************");
System.err.println("Target task name"+targetTaskName);
System.err.println("Task owner's address"+thisTaskOwnerAddress);
System.err.println("Area name"+Area);
System.err.println("*********************************************************");
} private static CSTask getTaskByName(CSWorkflow job, String name) throws CSException {
if (name == null) {
return null;
}
CSTask[] tasks = job.getTasks();
for (int i=0; i<tasks.length; i++) {
if (name.equals(tasks[i].getName())) {
return tasks[i];
}
}
return null;
}
public static void showFiles(String string1,String string2,String string3 ) {
try {
File filename = new File ("C:\\temp\\ApplicationEditions_dynamic.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(filename,true));
writer.write(string1+"\n");
writer.write(string2+"\n");
writer.write(string3+"\n");
writer.newLine();
writer.close();
}
catch (Exception e)
{
System.out.println("Error occurred due to branch, refer output file");
}
finally {
}
} }
In this code, following files are imported in this source file
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Hashtable;
import com.interwoven.cssdk.common.CSClient;
import org.apache.commons.lang.StringUtils;
import com.interwoven.cssdk.access.CSUser;
import com.interwoven.cssdk.common.CSClient;
import com.interwoven.cssdk.common.CSException;
import com.interwoven.cssdk.filesys.CSAreaRelativePath;
import com.interwoven.cssdk.workflow.CSExternalTask;
import com.interwoven.cssdk.workflow.CSTask;
import com.interwoven.cssdk.workflow.CSURLExternalTask;
import com.interwoven.cssdk.workflow.CSWorkflow;
Here source file is in location "package com.teamsite.client". So other files that are being imported from location com.interwoven.cssdk.common.CSClient, should have common path upto "com" folder and within "com" dir there should be dir "interwoven" and within this dir there should be other dir.
But when I check dir on server, I don't see any other dir than teamsite. This code workd fine without any problem.
So, how are these other files are getting imported in here ? Our environment is bit complex, but still files need to be in the path for being imported. We have repositories where jar is kept.
Thanks
When the class loader looks for a class e.g. com.interwoven.cssdk.workflow.CSExternalTask, it scans the entire classpath, looking for a directory branch like com/intervowen/cssdk/workflow. The above statement covers also the exploded jars that may be on the classpath.
The classpath usually contains more directories than your runnable jar file. Obviously, your jar is not expected to contain all classes contained in packages starting with com.*, so these can be imported from any location on the classpath.
You probably have a .jar file with the com.interwoven.cssdk. packages on your classpath somewhere.
.jar files behave like a zip file with it's own directory structure in it.