I am trying to develop Java web Tesseract OCR application. Following code works perfectly :
public class App {
public String getImgText(String imageLocation) {
ITesseract instance = new Tesseract();
instance.setDatapath(Thread.currentThread().getContextClassLoader().getResource("tessdata").getPath());
System.out.println("Thread.currentThread().getContextClassLoader().getResource(\"tessdata\").getPath() : "+Thread.currentThread().getContextClassLoader().getResource("tessdata").getPath());
instance.setLanguage("eng");
try {
String imgText = instance.doOCR(new File(imageLocation));
return imgText;
} catch (TesseractException e) {
e.getMessage();
return "Error while reading image";
}
}
public static void main(String[] args) {
App app = new App();
System.out.println(app.getImgText("/home/user/Desktop/1.png"));
}
}
But when I trying to use the above code in my Java web(JSF) application after the line
ITesseract instance = new Tesseract();
nothing is printed out. Below is the code of my web application :
public String uploadImage(FileUploadEvent event) {
System.out.println("webcore bean");
//get uploaded file from the event
UploadedFile uploadedFile = (UploadedFile) event.getFile();
//create an InputStream from the uploaded file
InputStream inputStr = null;
try {
inputStr = uploadedFile.getInputstream();
} catch (IOException e) {
//log error
}
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
String directory = externalContext.getInitParameter("uploadDirectory");
String filename = FilenameUtils.getName(uploadedFile.getFileName());
File destFile = new File(directory, "static" + getFileExtension(filename));
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
//log error
}
System.out.println("getImageText(directory) : " + getImageText(directory));
FacesMessage msg = new FacesMessage(event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return null;
}
private String getImageText(String imageLocation) {
try {
System.out.println("Before ");
ITesseract instance = new Tesseract1();
System.out.println("After ");
//instance.setDatapath("/usr/share/tesseract-ocr/4.00/tessdata");
instance.setDatapath(Thread.currentThread().getContextClassLoader().getResource("tessdata").getPath());
instance.setLanguage("eng");
try {
String imgText = instance.doOCR(new File(imageLocation));
return imgText;
} catch (TesseractException e) {
e.getMessage();
return "Error while reading image";
}
} catch (Exception e) {
System.out.println("Before returning null");
e.printStackTrace();
return null;
}
}
The log "Before" is being printed but the log "After" is not being printed. I am using following technologies :
a) Ubuntu 18.04 64 bit OS
b) Netbeans
c) Maven
d) Glassfish 4.1
Related
I want to create a file (outside of the workspace) so that everyone who opens my program has his own Textfile.
Currently I have to following Code:
private static final File m_dataFile = new File("C:\\temp\\MainPlayersLoginData.txt");
private static FileWriter writer;
private static Scanner reader;
public static void setMainPlayersLoginData(String name, String password) {
try {
if (!m_dataFile.exists()) {
createDirectory();
}
writer = new FileWriter(m_dataFile);
writer.write(name + "\n" + password);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void createDirectory() {
System.out.println("creating directory: " + m_dataFile.getName());
boolean result = false;
try {
m_dataFile.mkdirs();
result = true;
} catch (SecurityException se) {
}
if (result) {
System.out.println("DIR created");
}
}
With this code, the program creates a folder temp as planned, but creates a folder named "MainPlayersLoginData.txt" in it instead of a textfile. In addition I get a FileNotFoundException with the message "Access denied" when initialising the FileWriter.
I tried using m_datafile.mkdir() instead of m_datafile.mkdirs() but this time I get a FileNotFoundException with the message "The system cannot find the specified path" and the folder temp isnt created.
Edit: If i create the folder and the Textfile on my own, everything works fine.
I have a JavaFX app where there is an editor. In the editor, the user will be able to write java code and I have a button to compile this code and run the main method. For example the editor will contain this code:
public class Test {
public static void main(String[] args) {
System.out.println("hello");
}
}
The button on click, will run this code:
runButton.setOnAction(e -> {
compiler.set(editor.getText());
try {
compiler.createFile();
} catch (IOException e1) {
e1.printStackTrace();
}
compiler.compile();
compiler.run();
});
In the compiler class, there is the following implementation:
public class CodeCompiler {
public String className;
public String code;
public void set(String code) {
try {
this.className = code.substring(code.indexOf(" class ") + 6, code.indexOf(" {")).trim();
} catch(StringIndexOutOfBoundsException e) {
}
this.code = code;
}
public void createFile() throws IOException {
PrintWriter pw = new PrintWriter("speech2code/src/main/java/" + className + ".java");
pw.close();
FileWriter writer = new FileWriter("speech2code/src/main/java/" + className + ".java", true);
writer.write(code);
writer.flush();
writer.close();
}
public void compile() {
File file = new File("speech2code/src/main/java/" + className + ".java");
File classFile = new File("speech2code/src/main/java/" + className + ".class");
classFile.delete(); // delete class file f it exists
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, file.getPath());
}
public void run() {
Class<?> cls = null;
try {
cls = Class.forName(className);
System.out.println(cls == null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method meth = null;
try {
meth = cls.getMethod("main", String[].class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
String[] params = null;
try {
meth.invoke(null, (Object) params);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Now the code above successfully creates the java file, class file and runs correctly the first time. Now when I change the editor code to print something else, it outputs the result of the first time the code was running. So, in this case, it will still print 'hello' instead of whatever it's current value.
Any problem what might be wrong?
Thanks!
You need to create a new classloader for the new class. The class does not get reloaded just because you compiled it.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {classFile});
Then you can ask this loader for the class:
Class<?> cls = Class.forName(className, true, classLoader);
I developed a little Java Swing application to look up character statistics in World of Warcraft with their developer API using Netbeans in Ubuntu Gnome 14.04. Everything works as I've intended with the exception of a button that calls a method that opens a link in the default browser to the specified character's profile. On Ubuntu, the string I use in the URL renders correctly, but on Windows it does not. If I run the application (in Windows) using a batch file that specifies UTF-8 encoding for the JVM, I do not have this issue. When running it directly from the .jar file, characters such as "â" register as "â" in the URL on Windows despite my attempt at encoding all of my strings as UTF-8. How can I get the URL be properly formatted? I'm assuming there's something I'm missing. If you need to see more of the code, let me know. Thank you in advance.
ArmoryScanner_UI.java
private void openArmoryLink() {
ArmoryScanner_Backend armory = new ArmoryScanner_Backend();
String name;
String realm;
String locale;
try {
name = new String(jTextField_Name.getText().getBytes("UTF-8"));
realm = jComboBox_Realm.getSelectedItem().toString();
locale = jComboBox_Locale.getSelectedItem().toString();
if (!name.trim().isEmpty()) {
name = formatName(name);
realm = formatRealm(realm);
locale = formatLocale(locale);
armory.setPlayerInfo(name, realm, locale);
if (armory.isCharacterFound()) {
armory.setArmoryLink();
} else {
showErrorMessage("Character not found.");
jTextField_Name.setText("");
jTextField_Name.setCaretPosition(0);
jTextField_Name.requestFocus();
}
} else {
showErrorMessage("Please enter a character name.");
jTextField_Name.setText("");
jTextField_Name.setCaretPosition(0);
jTextField_Name.requestFocus();
}
} catch (UnsupportedEncodingException e) {
showErrorMessage("Error converting name to UTF-8\n"
+ e.getMessage());
}
}
private String formatName(String name) {
String result;
try {
result = new String(name.getBytes("UTF-8"), "UTF-8");
} catch (UnsupportedEncodingException e) {
showErrorMessage("Error converting name to UTF-8\n"
+ e.getMessage());
result = "";
}
return result;
}
ArmoryScanner_Backend.java
public void setArmoryLink () {
try {
String baseURL = "https://us.battle.net/wow/en/character/";
String fullURL = (baseURL + realm + "/" + name + "/simple");
System.out.println("Full URL: " + fullURL);
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URL(fullURL).toURI());
} else {
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + fullURL);
} catch (IOException e) {
System.out.println("I/O exception (non-Windows system)");
}
}
} catch (UnsupportedOperationException e) {
System.out.println("Unsupported OS");
} catch (MalformedURLException e) {
System.out.println("Bad URL");
} catch (IOException e) {
System.out.println("I/O exception.");
} catch (URISyntaxException e) {
System.out.println("Bad URI syntax");
}
}
This method works fine:
private void submit() {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
ArmoryScanner_Backend armory = new ArmoryScanner_Backend();
String name;
String realm;
String locale;
try {
name = new String(jTextField_Name.getText().getBytes("UTF-8"));
realm = jComboBox_Realm.getSelectedItem().toString();
locale = jComboBox_Locale.getSelectedItem().toString();
if (!name.trim().isEmpty()) {
name = formatName(name);
realm = formatRealm(realm);
locale = formatLocale(locale);
armory.setPlayerInfo(name, realm, locale);
if (armory.isCharacterFound()) {
setStatistics(armory);
setProgression(armory);
} else {
showErrorMessage("Character not found.");
jTextField_Name.setText("");
jTextField_Name.setCaretPosition(0);
jTextField_Name.requestFocus();
}
} else {
showErrorMessage("Please enter a character name.");
jTextField_Name.setText("");
jTextField_Name.setCaretPosition(0);
jTextField_Name.requestFocus();
}
} catch (UnsupportedEncodingException e) {
showErrorMessage("Error converting name to UTF-8\n"
+ e.getMessage());
}
this.setCursor(Cursor.getDefaultCursor());
}
Java uses Unicode on the inside, so you don't usually need to set the encoding EXCEPT when you read/write outside resources.
There you need to have it explicitly.
In your case you need to encode the elements of the URL with the class URLEncoder.
Have a look at the documentation.
I have a similar problem - i was trying to run this code for IntelliJ Idea 13 and i would like to use rptdesign file to generate the report. The code looks like this:
public class ExecuteBIRTReport {
static void executeReport() throws EngineException {
EngineConfig config = null;
IReportEngine engine = null;
try {
config = new EngineConfig();
config.setLogConfig("/logs", java.util.logging.Level.WARNING);
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
engine = factory.createReportEngine(config);
IReportRunnable report = null;
String reportFilepath = "C://Users//user//workspace//TestProject//Products.rptdesign";
try {
report = engine.openReportDesign(reportFilepath);
} catch (Exception e) {
System.err.println("Report " + reportFilepath + " not found!\n");
engine.destroy();
return;
}
IRunAndRenderTask task = engine.createRunAndRenderTask(report);
PDFRenderOption options = new PDFRenderOption();
options.setOutputFormat("pdf");
options.setOutputFileName("C:/Users/user/workspace/TestProject/REPORT.pdf");
task.setRenderOption(options);
try {
task.run();
} catch (EngineException e1) {
System.err.println("Report " + reportFilepath + " run failed.\n");
System.err.println(e1.toString());
}
engine.destroy();
return;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
executeReport();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I imported the project IntelliJ following jar-files (without them do not eceive a compilation):
com.ibm.icu_54.1.1.v201501272100.jar
org.eclipse.birt.core_4.5.0.v201506092134.jar
org.eclipse.birt.data_4.5.0.v201506092134.jar
org.eclipse.birt.report.data.adapter_4.5.0.v201506092134.jar
org.eclipse.birt.report.engine_4.5.0.v201506092134.jar
org.eclipse.birt.report.model_4.5.0.v201506092134.jar
org.eclipse.core.runtime_3.11.0.v20150405-1723.jar
org.eclipse.datatools.connectivity.oda_3.4.3.v201405301249.jar
org.eclipse.equinox.common_3.7.0.v20150402-1709.jar
org.eclipse.equinox.common_3.7.0.v20150402-1709.jar
org.eclipse.osgi_3.10.100.v20150529-1857.jar
In Eclipse version of BIRT 4.5.0. and a report is created normally. In IntelliJ at the stage of creating a file error message:The output format <...> is not supported. I tried to arrange for the withdrawal of pdf and html formats, but to no avail. Does anyone know a solution?
I used the following code to run an exe I load through my code.
private static String filelocation = "";
.
load_exe.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
JFileChooser file_Choose = new JFileChooser();
file_Choose.showOpenDialog(frame);
JavaSamp.filelocation = file_Choose.getCurrentDirectory()
.toString()
+ "\\" + file_Choose.getSelectedFile().getName();
System.out.println("FileLocation" + JavaSamp.filelocation);
} catch (Exception expobj) {
// TODO Auto-generated catch block
}
Runtime rt = Runtime.getRuntime();
try {
System.out.println("File Run Location" + JavaSamp.filelocation);
proc = rt.exec(JavaSamp.filelocation);
} catch (IOException e4) {
e4.printStackTrace();
} catch (Exception e2) {
}
}
});
My problem is, the above execution of the JavaSamp.filelocation, should have to done many times. First time only I load the exe. Next time I wont. I need to store the exe in a string to run for the successive times.
Any suggestion pls
If you want remember the used file just initialize the filelocation with null and test for it. BTW: Storing it as File makes more sense and your way of constructing the absolute path is a bit intricate - compared to just calling getAbsolutePath()
private static File filelocation = null;
private static void test() {
load_exe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Check if file-name to execute has already been set
if (filelocation != null) {
try {
JFileChooser file_Choose = new JFileChooser();
file_Choose.showOpenDialog(frame);
JavaSamp.filelocation = file_Choose.getSelectedFile();
System.out.println("FileLocation"
+ JavaSamp.filelocation.getAbsolutePath());
} catch (Exception expobj) {
}
}
Runtime rt = Runtime.getRuntime();
try {
System.out.println("File Run Location"
+ JavaSamp.filelocation.getAbsolutePath());
Process proc = rt.exec(JavaSamp.filelocation
.getAbsolutePath());
} catch (IOException e4) {
e4.printStackTrace();
}
}
};
}