Tesseract implementing a web service to trigger OCR actions - java

I am trying to implement a web service which triggers OCR actions of the server side.
Client code:
...
sy = belgeArsivle(testServisIstegi, ab);
...
private static ServisYaniti belgeArsivle(com.ocr.ws.ServiceRequest serviceRequest,com.ocr.ws.Document document) {
com.ocr.ws.ServiceRequest service = new com.ocr.ws.OCRArsivWSService();
com.ocr.ws.OCRArsivWS port = service.getOCRArsivWSPort();
return port.docArchive(serviceRequest, document);
}
When I run the code on the server side there is no problem. But whenever I call the web service method from the client I got this error code:
Exception: javax.xml.ws.soap.SOAPFaultException: Unable to load library 'libtesseract302': The specified module could not be found.
The working server-side code is:
public static void main(String[] args) {
// TODO code application logic here
File imageFile = new File("...OCR\\testTurWithBarcodeScanned.png");
Tesseract instance = Tesseract.getInstance();
try {
String lang = "tur";
instance.setLanguage(lang);
String result = instance.doOCR(imageFile);
System.out.println(result);
// write in a file
try {
File file = new File("...MyOutputWithBarcode.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(result);
out.close();
} catch (IOException ex) {
}
} catch (TesseractException ep) {
System.err.println(ep.getMessage());
}
}
I know that this error code is about Tesseract libraries. I put the corresponding .dll files (liblept168 and libtesseract302) under the client project's folder, added corresponding libraries (jna, jai_imageio, ghost4j_0.3.1), did neccessary changes in classpath but still getting this error.
I run a test code on the server side, it works fine. But the client side code is not working. Do I need to make some extra adjustment on the client side to run this web service?

I found out that the actual problem was with the Tomcat Server. I had to put the jar files to the Tomcat's Sources under Properties, than voila!

Related

"t.data.data is undefined" in grafana

I'm new to micrometer, prometheus and grafana. I'm trying to run my first example with these three things working together. But I'm having a hard time figuring out what I'm doing wrong.
I'm using micrometer's API to create a PrometheusMeterRegistry like this:
new PrometheusMeterRegistry(new PrometheusConfig() {
#Override
public Duration step() {
return Duration.ofSeconds(10);
}
#Override
#Nullable
public String get(String k) {
return null;
}
});
And I'm creating a HttpServer as described here using the following code:
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/prometheus", httpExchange -> {
String response = prometheusMeterRegistry.scrape();
httpExchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes());
}
});
new Thread(server::start).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
I configured Prometheus as my data-source in grafana and set the URL to http://localhost:8080/prometheus. But when I try creating a new dashboard and add a graph to it, I get a red exclamation mark saying t.data.data is undefined. And because of this I'm not able to view the graphs. The complete stack-trace is as follows:
kr</t.prototype.transform#http://localhost:3000/public/build/app.dfabdd44b3be44288eac.js:22:723420
jr</t.prototype.query/</<#http://localhost:3000/public/build/app.dfabdd44b3be44288eac.js:22:736135
qt#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:9:5239
Wa#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:9:40274
jr</t.prototype.query/<#http://localhost:3000/public/build/app.dfabdd44b3be44288eac.js:22:735858
c/</<#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:92198
c/<#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:92043
$digest#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:97575
$apply#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:99590
$applyAsync/r<#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:99735
h#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:33036
ln/this.$get</</i.defer/n<#http://localhost:3000/public/build/vendor.dfabdd44b3be44288eac.js:130:34396
The following is the screenshot of the error in grafana that I'm gettng:
Any suggestions what I might be missing?
Note: I can see timer getting published on native prometheus using URL localhost:8080/prometheus.
8080 is your application server. You need to run a Prometheus server that scrapes this application, then you can use localhost:9090 as a datasource.

Jar file working when running standalone but doesn't work under Windows service

I have a java project, which complied into an executable jar file v-agent-exe.jar. This jar is a log server, log rows is sent to it for processing.
I can execute it by using this command:
`java -jar v-agent-exe.jar -a watch -f config.ini`.
After executed, this jar file will create a ServerSocket at port 1235 and listen for incoming data from clients. After data received, the program will process the data and send the result back to the client. When I execute the jar from CMD windows, the processing is working perfect.
Now I am trying to wrap the Jar file as a Windows service (I am using Windows 10). I created a "Windows service project"
in Visual studio like below:
- Caller class have call() method to execute the jar file using process.
- AgentService is the service, which execute Caller->call() in another thread.
- Program is the main entry to load AgentService.
Caller.cs
public class Caller
{
static Process proc;
public Process GetProcess(){
return proc;
}
public void call() {
try
{
String dir = AppDomain.CurrentDomain.BaseDirectory;
proc = new Process
{
StartInfo = new ProcessStartInfo
{
WorkingDirectory = dir,
FileName = "java.exe",
Arguments = #"-jar v-agent-exe.jar -a watch -f config.ini",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardError.EndOfStream)
{
string line = proc.StandardError.ReadLine();
}
}
catch (Exception ex) {
VAgentService.writeLog("Error when call process: " + ex.Message);
}
}
}
AgentService
public partial class AgentService : ServiceBase
{
private string jarPath;
private string iniPath;
static Process proc;
Caller caller;
public AgentService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
writeLog("On start");
try
{
caller = new Caller();
writeLog("Prepare to launch thread");
Thread t = new Thread(new ThreadStart(caller.call));
t.Start();
}
catch (Exception ex)
{
EventLog.WriteEntry("Demo error: " + ex.Message);
}
}
protected override void OnStop()
{
proc = caller.GetProcess();
if (proc != null && !proc.HasExited)
{
proc.Kill();
}
else
{
...
}
}
}
Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(String[] args)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new AgentService()
};
ServiceBase.Run(ServicesToRun);
}
}
After build the the service project, I have AgentService.exe.
I install it to my system using:
sc create VAgentLogging binpath= %CD%\AgentService.exe depend= lmhosts start= auto
After start the service in service.msc, I can telnet to port "1235" which the java process is listening (I am sure about
only the jar running in this port). According to the
log of java program, it still can received some part of data but seem like it cannot send back to client or something,
which cause the followed process cannot be done.
I think my problem is: the jar file can executed as standalone but somehow it sucks when wrapped under my service project.
I haven't posted the jar's code yet because I think the error is related to the Windows service project. If you need the java code, please tell me and I will update it here.
Any help would be appreciated.

Running jrxlm report with Jasper Server

I have created jrxml report by iReport. Then I have run it with JasperServer and it work perfectly. I have generate pdf report by this URL:
http://localhost:8081/jasperserver/flow.html/flowFile/my_report.pdf
It works well but when I tried to refresh the page I get this error:
An id is required to lookup a FlowDefinition
Also when I try to call this REST service in JasperServer client application I get this error:
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 500
This is the Java client application to call the REST service:
public final static String serverUrl = "http://localhost:8081/jasperserver/flow.html/flowFile/my_report.xls";
public final static String serverUser = "jasperadmin";
public final static String serverPassword = "jasperadmin";
static File outPutDir= new File(System.getProperty("java.io.tmpdir"));
public static void main(String[] args) {
try {
Report report = new Report();
report.setUrl("/reports/samples/Employees");
report.setOutputFolder(outPutDir.getAbsolutePath());
JasperserverRestClient client = JasperserverRestClient.getInstance(serverUrl, serverUser, serverPassword);
File reportFile = client.getReportAsFile(report);
} catch (Exception e) {
e.printStackTrace();
}
}
flowId
When calling flow.html you must provide an action, which is put into the flowId. JasperServer is using the flow.html to provide an interface which can be accessed over the URL. For example if calling a report this would be:
_flowId=viewReportFlow
Also the report and parameters have to be provided. So with this in mind the URL could look like this:
http://localhost:8081/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=/reports/samples/Employees&j_username=the_user&j_password=secret&output=pdf
Server error
When connecting to the server, this URL is used
http://localhost:8081/jasperserver/flow.html/flowFile/my_report.xls
This is not the server URL used by JasperserverRestClient. The server URL should look like this:
http://localhost:8081/jasperserver
NOTE: flow.html is for accessing JasperServer without logging into the UI. It is not an application path where you should put your reports.

Logging exceptions in Windows Service with WinRun4j

I have been trying to get a Windows service running from my JAR file. WinRun4j seems to be able to do the job, but I can't get it to work. I am especially finding it quite difficult to debug. I tried several methods for logging (writing to a .txt file, WinRun4j's EventLog class) but I can't seem to generate any output.
The service installs fine (eventually..) and I can start it. It should start a Jetty server that generates an XML file that can be reached over HTTP. The app works for a stand-alone version, just not for the service. The service is started, but as soon as I call the URL it stops without generating an error.
This is my Service class:
package com.some.package;
import org.boris.winrun4j.AbstractService;
import org.boris.winrun4j.ServiceException;
/**
* A basic service.
*/
public class StockService extends AbstractService {
private StockServer srv;
public int serviceMain(String[] args) throws ServiceException {
while (!shutdown) {
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
}
if(srv == null) {
try {
srv = new StockServer();
srv.start();
} catch (Exception e) {
}
}
}
return 0;
}
}
I found out that the service didn't want to start if I started the Jetty server from the serviceMain class. I had to start a new thread. So StockServer extends Thread:
public class StockServer extends Thread {
private Server server;
public void run() {
if (server == null) {
try {
server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/example");
StockServlet stockServlet = new StockServlet();
context.addServlet(new ServletHolder(stockServlet), "/stock/*");
server.setHandler(context);
server.setStopAtShutdown(true);
server.start();
server.join();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
Since it runs perfectly fine as Java application I just don't know how to get this thing debugged. I hope one of you can point me in the right direction :).
I ended up using the Java Service Wrapper (JSW). This seemed a lot more complex but ended up to be quite easy. It also provides logging by default so I could easily fix the errors. The JSW had problems finding the correct JDK, since JSW is 32bit and I installed JDK1.7 64 bit (and 1.6 32bit). Installing JDK1.7 32bit fixed it. That might have been the problem with WinRun4j as well, but that is something I will never know :).

Uploading file as stream in play framework 2.0

I'm writing a play 2.0 java application that allows users to upload files. Those files are stored on a third-party service I access using a Java library, the method I use in this API has the following signature:
void store(InputStream stream, String path, String contentType)
I've managed to make uploads working using the following simple controller:
public static Result uploadFile(String path) {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart = body.getFile("files[]");
InputStream is = new FileInputStream(filePart.getFile())
myApi.store(is,path,filePart.getContentType());
return ok();
}
My concern is that this solution is not efficient because by default the play framework stores all the data uploaded by the client in a temporary file on the server then calls my uploadFile() method in the controller.
In a traditional servlet application I would have written a servlet behaving this way:
myApi.store(request.getInputStream(), ...)
I have been searching everywhere and didn't find any solution. The closest example I found is Why makes calling error or done in a BodyParser's Iteratee the request hang in Play Framework 2.0? but I didn't found how to modify it to fit my needs.
Is there a way in play2 to achieve this behavior, i.e. having the data uploaded by the client to go "through" the web-application directly to another system ?
Thanks.
I've been able to stream data to my third-party API using the following Scala controller code:
def uploadFile() =
Action( parse.multipartFormData(myPartHandler) )
{
request => Ok("Done")
}
def myPartHandler: BodyParsers.parse.Multipart.PartHandler[MultipartFormData.FilePart[Result]] = {
parse.Multipart.handleFilePart {
case parse.Multipart.FileInfo(partName, filename, contentType) =>
//Still dirty: the path of the file is in the partName...
String path = partName;
//Set up the PipedOutputStream here, give the input stream to a worker thread
val pos:PipedOutputStream = new PipedOutputStream();
val pis:PipedInputStream = new PipedInputStream(pos);
val worker:UploadFileWorker = new UploadFileWorker(path,pis);
worker.contentType = contentType.get;
worker.start();
//Read content to the POS
Iteratee.fold[Array[Byte], PipedOutputStream](pos) { (os, data) =>
os.write(data)
os
}.mapDone { os =>
os.close()
Ok("upload done")
}
}
}
The UploadFileWorker is a really simple Java class that contains the call to the thrid-party API.
public class UploadFileWorker extends Thread {
String path;
PipedInputStream pis;
public String contentType = "";
public UploadFileWorker(String path, PipedInputStream pis) {
super();
this.path = path;
this.pis = pis;
}
public void run() {
try {
myApi.store(pis, path, contentType);
pis.close();
} catch (Exception ex) {
ex.printStackTrace();
try {pis.close();} catch (Exception ex2) {}
}
}
}
It's not completely perfect because I would have preferred to recover the path as a parameter to the Action but I haven't been able to do so. I thus have added a piece of javascript that updates the name of the input field (and thus the partName) and it does the trick.

Categories

Resources