I'm trying to do url rewriting from "beautiful" human-readable urls to webcenter internal representation and vice versa. I'm using AssetDataManager to map asset id to asset description, which I use in the URL, and the other way around. This is what I have with url assembly:
Session ses = SessionFactory.getSession();
AssetDataManager mgr = (AssetDataManager) ses
.getManager(AssetDataManager.class.getName());
List<AssetId> assets = new ArrayList<AssetId>();
assets.add(new AssetId()
{
private long id = assetId;
private String type = "Page";
#Override
public String getType()
{
return type;
}
#Override
public long getId()
{
return id;
}
});
Iterable<AssetData> assetDataItems = mgr.read(assets);
And this is for url disassembly:
Session ses = SessionFactory.getSession();
AssetDataManager mgr = (AssetDataManager) ses
.getManager(AssetDataManager.class.getName());
final String assetType = "Page";
final String subType = null;
final Condition condition = ConditionFactory.createCondition(
"description", OpTypeEnum.EQUALS, pageName);
final List<String> desiredAttributes = Arrays.asList("id");
Query query = new SimpleQuery(assetType, subType, condition,
desiredAttributes);
query.getProperties().setIsBasicSearch(true);
Iterable<AssetData> assetDataItems = mgr.read(query);
Both are used in the context of my custom assembler, which extends QueryAssembler.
Assembly works fine, reusing existing session, but disassembly fails with:
COM.FutureTense.Common.ContentServerException: ContentServerException: (Unexpected runtime exception) Error code:GENERIC SERVER ERROR
at com.openmarket.Satellite.servlet.BaseServlet.doGet(BaseServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.fatwire.wem.sso.cas.filter.CASFilter.doFilter(CASFilter.java:554)
at com.fatwire.wem.sso.SSOFilter.doFilter(SSOFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Caused by: com.openmarket.Satellite.RequestContext$RequestContextInitializationException: Co-resident Satellite Server failed to capture ICS
at com.openmarket.Satellite.RequestContext.getICS(RequestContext.java:1030)
at com.openmarket.Satellite.RequestContext.captureInputCoResident(RequestContext.java:518)
at com.openmarket.Satellite.RequestContext.<init>(RequestContext.java:428)
at com.openmarket.Satellite.servlet.BaseServlet.doGet(BaseServlet.java:112)
... 18 more
Caused by: java.lang.NullPointerException
at COM.FutureTense.Common.CS.PushVars(CS.java:217)
at com.openmarket.framework.objects.ContentCatalog.Lookup(ContentCatalog.java:305)
at com.openmarket.framework.objects.AbstractContent.Read(AbstractContent.java:510)
at com.openmarket.framework.objects.AbstractObject.Read(AbstractObject.java:460)
at com.openmarket.framework.objects.AbstractObject.Read(AbstractObject.java:446)
at com.openmarket.xcelerate.asset.AssetType.Load(AssetType.java:499)
at com.fatwire.assetapi.util.AssetUtil.isComplexAsset(AssetUtil.java:125)
at com.fatwire.assetapi.util.AssetUtil.isFlexAsset(AssetUtil.java:274)
at com.fatwire.assetapi.data.AssetDataManagerImpl.read(AssetDataManagerImpl.java:79)
at mypackage.urlassembler.ComplexDisassemblyData.getAssetIdFromPageName(ComplexDisassemblyData.java:189)
at mypackage.urlassembler.ComplexDisassemblyData.valueOf(ComplexDisassemblyData.java:145)
at mypackage.urlassembler.MyCustomURLAssembler.getDisassemblyContext(MyCustomURLAssembler.java:79)
at com.fatwire.cs.core.uri.AbstractAssembler.disassemble(AbstractAssembler.java:418)
at com.fatwire.cs.core.uri.AssemblerEngine.disassemble(AssemblerEngine.java:242)
at COM.FutureTense.Servlet.ServletRequest.disassembleURI(ServletRequest.java:852)
at COM.FutureTense.Servlet.ServletRequest.initializeParameters(ServletRequest.java:1023)
at COM.FutureTense.Servlet.ServletRequest.getParameters(ServletRequest.java:786)
at COM.FutureTense.Servlet.FRequestObj.prepInput(FRequestObj.java:1090)
at COM.FutureTense.Servlet.FRequestObj.init(FRequestObj.java:973)
at COM.FutureTense.Servlet.FRequestObj.<init>(FRequestObj.java:271)
at COM.FutureTense.Servlet.FRequestObj.newInstance(FRequestObj.java:231)
at COM.FutureTense.Servlet.FRequestObj.newInstance(FRequestObj.java:218)
at COM.FutureTense.CS.Factory.newCS(Factory.java:66)
at com.openmarket.Satellite.RequestContext.getICS(RequestContext.java:1026)
... 21 more
Which seems very strange. For some reason it is unable to use the existing session. If I change disassembly session retrieval to this, it works fine:
Session ses = SessionFactory.newSession(userName, pass);
However, I certainly would not want to create another session every time I want to resolve an url. Why do I get the exception? What would be a good way to handle this?
Ok, so apparently URL disassembly can't do anything related to DB content, as it is meant to be executed on a satellite server where it doesn't have the connectivity. For URL assembly using the DB is fine though...
So based on this, I figured out that I need to move my Asset API code to a helper class that is called from an uncached wrapper. From there it works fine.
Related
I am asking this question because I was unable to find a similar question. I recently completed this college project where I made a console application that connected to the database and everything seemed perfectly fine. The method I used to connect to the database is this:
private static Connection getConnection()
{
Connection connection = null;
try
{
String dbDirectory = "c:/murach/java/db";
System.setProperty("derby.system.home", dbDirectory);
String dbURL = "jdbc:derby:MurachDB2";
String username = "";
String password = "";
connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("connect works");
return connection;
} //end try connection statement
catch (SQLException e)
{
for (Throwable t : e)
{
e.printStackTrace();
System.out.println("something went wrong on connection method");
} //end for loop for errors
} // end catch statement for connection error
return connection;
}
As I said before I created the console application and everything seemed fine and I turned it in. However, I wanted to experiment with something, I wanted to make another version of this application but instead a GUI application using Jform. I used all of the same classes as before, except that instead of a main class, I used a jform. The method and class is exactly the same, because the database didn't change locations in my folder, however when I run it in the Jform application I get a runtime error.
What it was a null point error and I knew it had something to do with connecting to the database because I wrote a System.out.Println in the catch SQL Exception to notify that something went wrong with the method. The connect to the database is fine with the console application, but my question is if there is any further measures I need to take when it comes to working with a JFrame application. Is there anything I am missing or is there any extra step I need to do. For further measures I will display the whole class that works with the database, and I will also use the event handlers in the Jframe.
I want to make this clear in which that I am not required to do this. I am just playing around with Java, and I could easily leave this alone without consequences, but I feel I really want to learn this so this is why I am asking for help. Any kind of advice or if any of you can let you know what I am missing I would really appreciate it.
Edit
adding error information
>java.sql.SQLException: No suitable driver found for jdbc:derby:MurachDB2
something went wrong on connection method
java.lang.NullPointerException
something went from with dislay part
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at CustomerInvoiceDB.getConnection(CustomerInvoiceDB.java:38)
at CustomerInvoiceDB.getCustomers(CustomerInvoiceDB.java:67)
at CutomerInvoice.displayButtonActionPerformed(CutomerInvoice.java:111)
at CutomerInvoice.access$000(CutomerInvoice.java:24)
at CutomerInvoice$1.actionPerformed(CutomerInvoice.java:57)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Note: i'm using an experimental pre-release of microsoft's latest adal
I'm trying to get my identity providers to work on the mobile applications. So far I've been able to load my identity providers and managed to get the login page to show (except for facebook).
The problem is that whenever i actually try to login i'm getting some error in the form off "invalid redirect uri".
Google, for instance, will say: "The redirect URI in the request: https://login.microsoftonline.com/... did not match a registered redirect URI.
Facebook will show: "Given URL is not allowed by the application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains."
As far as I understand you don't actually need to register the mobile application anymore with the different identity providers because Azure sits in between you and them. Azure handles the connection, gets your token and uses it to identify you. It should then return a set of "azure tokens" to you.
To my knowledge the used redirect URI is registered on the portal since I'm able to load the identity providers in the first place?
Not to mention it seems to be a default URL that's used by many applications: urn:ietf:wg:oauth:2.0:oob which simply tells it to return it to some none-browser based application?
This is the code i'm using to actually do the login/signup:
private static String AUTHORITY_URL = "https://login.microsoftonline.com/<directory>/oauth2/authorize/";
private static String CLIENT_ID = "my_client_id";
private static String[] SCOPES = { "my_client_id" };
private static String[] ADDITIONAL_SCOPES = { "" };
private static String REDIRECT_URL = "urn:ietf:wg:oauth:2.0:oob";
private static String CORRELATION_ID = "";
private static String USER_HINT = "";
private static String EXTRA_QP = "nux=1";
private static String FB_POLICY = "B2C_1_<your policy>";
private static String EMAIL_SIGNIN_POLICY = "B2C_1_SignIn";
private static String EMAIL_SIGNUP_POLICY = "B2C_1_SignUp";
public async Task<AuthenticationResult> Login(IPlatformParameters parameters, bool isSignIn)
{
var authContext = new AuthenticationContext(AUTHORITY_URL, new TokenCache());
if (CORRELATION_ID != null &&
CORRELATION_ID.Trim().Length != 0)
{
authContext.CorrelationId = Guid.Parse(CORRELATION_ID);
}
String policy = "";
if (isSignIn)
policy = EMAIL_SIGNIN_POLICY;
else
policy = EMAIL_SIGNUP_POLICY;
return await authContext.AcquireTokenAsync(SCOPES, ADDITIONAL_SCOPES, CLIENT_ID, new Uri(REDIRECT_URL), parameters, UserIdentifier.AnyUser, EXTRA_QP, policy);
}
microsoft's documentation isn't really helping because most are either empty (they're literally not yet typed out) or it's some help topic from over a year ago. This stuff is pretty new so documentation seems to be hard to come by.
So, dear people of stackoverflow, what am I missing? Why is it saying that the redirect urI is invalid when it's been registered on the azure web portal? And if the redirect URI is invalid why can I retrieve the identity providers in the first place?
why is it that i can't seem to find solutions after hours of searching, yet when i post a question here i somehow find the answer within minutes...
It was quite a stupid mistake at that, one of my collegues had sent me the wrong authority url.
The funny thing is that it was correct "enough" to load the identity providers we had installed on the portal but not correct enough to handle actually signing in or up.
I initially used:
https://login.microsoftonline.com/<tenant_id>/oauth2/authorize/
where it should have been:
https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/authorize
You see that little "v2.0"? yeah that little bastard is what caused all the pain...
OTAClient.dll version 10.0.0.2532
The following is the code I have used to connect to qc, apply filter and fetch qcpath and a field data. It is working fine with java 32 bit version 1.7.
import com.oracle.qcTasks.ClassFactory;
import com.oracle.qcTasks.IList;
import com.oracle.qcTasks.ISubjectNode;
import com.oracle.qcTasks.ITDConnection;
import com.oracle.qcTasks.ITDFilter;
import com.oracle.qcTasks.ITest;
import com.oracle.qcTasks.ITestFactory;
import com4j.Com4jObject;
public class qcClient {
public static void main(String[] args) {
ITest qcTestCase;
ISubjectNode qcTestCasePath;
Com4jObject SubjectField;
//QC url
String url = "http://fusionqc.us.oracle.com/";
//username for login
String username = "username";
//password for login
String password = "";
//domain
String domain = "domain";
//project
String project = "project";
ITDConnection itdc = ClassFactory.createTDConnection();
itdc.initConnectionEx(url);
itdc.connectProjectEx(domain, project, username, password);
boolean flag = itdc.connected();
System.out.println(itdc.projectName());
ITestFactory qcTestFactory = itdc.testFactory().queryInterface(ITestFactory.class);
ITDFilter qcFilter=qcTestFactory.filter().queryInterface(ITDFilter.class);
String query="^Subject\\path^";
qcFilter.clear();
qcFilter.filter("TS_SUBJECT", query);
IList qcTestList = qcFilter.newList();
for (Com4jObject com4jObject : qcTestList) {
qcTestCase = com4jObject.queryInterface(ITest.class);
System.out.println(qcTestCase.name());
System.out.println(qcTestCase.field("TS_USER_09"));
SubjectField = (Com4jObject)qcTestCase.field("TS_SUBJECT");
qcTestCasePath = SubjectField.queryInterface(ISubjectNode.class);
System.out.println(qcTestCasePath.path());
break;
}
System.out.println("command output :: "+flag);
System.out.println("OUT");
itdc.disconnectProject();
}
}
To the project requirement, I've downgraded the version of java to 64 bit version of 1.6. Post the downgrade, I'm receiving the following error.
Exception in thread "main" com4j.ExecutionException: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.ComThread.execute(ComThread.java:203)
at com4j.Task.execute(Task.java:25)
at com4j.COM4J.createInstance(COM4J.java:97)
at com4j.COM4J.createInstance(COM4J.java:72)
at com.oracle.qcTasks.ClassFactory.createTDConnection(ClassFactory.java:16)
at com.oracle.qcCode.qcClient.main(qcClient.java:32)
Caused by: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.Native.createInstance(Native Method)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:117)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:104)
at com4j.Task.invoke(Task.java:51)
at com4j.ComThread.run0(ComThread.java:153)
at com4j.ComThread.run(ComThread.java:134)
I've found similar threads but didn't found any particular solution for the same. Please help. Is there any impact wrt java versions
What version of com4j do you use? See this post for using com4j on a 64 bit Windows machine. Are there any COM objects you can use from your 64 bit environment?
According to this blog entry you will get a Class not Registered Exception when you try to access a 32 bit COM object in a 64 bit environment. It even contains a workaround using some registry hacks. Maybe it works?
I have tried tess4j as a standalone java program and it worked properly giving the text output.
Now i am trying to create a spring mvc web project adding the dependencies for tess4j in pom and i have added the tess4j source inside my project.
File imageFile = new File("D:/Data/jars/tess/eurotext.tif");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try {
result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
The above code works properly when i tried to run a standalone java program inside the project.so its clear that the jar files are added to build path properly.
but when i call the code in a controller mapping or service it throws a run time exception.
SEVERE: Unsupported image format. May need to install JAI Image I/O package.
https://java.net/projects/jai-imageio/
java.lang.RuntimeException: Unsupported image format. May need to install JAI Image I/O package.
https://java.net/projects/jai-imageio/
at net.sourceforge.vietocr.ImageIOHelper.getIIOImageList(ImageIOHelper.java:324)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:173)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:158)
at com.ocr.tesseract.TesseractExample.getTextFromImage(TesseractExample.java:27)
at com.cogz.tp.controller.HomeController.view(HomeController.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
java.lang.RuntimeException: Unsupported image format. May need to install JAI Image I/O package.
https://java.net/projects/jai-imageio/
Please let me know what am missing.Thanks in advance.
Even I faced the similar problem of using tess4j for DynamicWebProject. But thanks to comment by #nguyenq that helped me I got it working.
Mostly tess4j uses TIFF handler for optical recognition. The dependencies required for it are not available with default ImageIO.
So, jai-imageio.jar is required. All I did was added line ImageIO.scanForPlugins() before I called the wrapper class that performed doOCR.
I had following jars in my lib:-
tess4j.jar
jai_imageio.jar
ghost4j-0.3.1.jar
jna.jar
junit-4.10.jar
Here's the sample code:
TessractOCR tessocr = new TessractOCR();
ImageIO.scanForPlugins();
String extractedString = tessocr.extractTextFromImage(binarizrImage);
The function
public static String extractTextFromImage(BufferedImage image){
RenderedImage img = image;
String result =null;
try {
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
instance.setDatapath("E:\\OCR-data\\Tess4J-1.2-src\\Tess4J");
result = instance.doOCR(outputfile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
return result;
}
It works 100% :)
Below is the working code sharing for all:
public static String doOCR(File pdfInvoice) {
String result = "";
long totalTime = 0;
long endTime = 0;
long startTime = System.currentTimeMillis();
File imageFile = new File("D:\\docfolder\\9011121584.pdf");
Tesseract instance = Tesseract.getInstance(); //
try {
ImageIO.scanForPlugins();
result = instance.doOCR(imageFile);
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
System.out.println("Total Time Taken For OCR: " + (totalTime / 1000));
return result;
} catch (Exception e) {
System.err.println(e.getMessage());
result = "";
return result;
}
}
I have inserted the following java code in the body part of my jsp page to retrieve the records of the table FLIGHTDATA from a Oracle 10g database. But after the execution of the Class.forName(...) line the program directly goes to finally block and closing the connection without returning any data. Any suggestions on what I am doing wrong ? Thanks - Somnath
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%
out.println("<table border='1'><tr>");
Connection connection = null;
Statement statement = null;
ResultSet rs_1hop = null;
ResultSetMetaData rsm_1hop = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String connectionURL = "jdbc:oracle:thin:#localhost:1521:xe";
connection = DriverManager.getConnection(connectionURL, "system", "system");
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from FLIGHTDATA";
rs_1hop = statement.executeQuery(QueryString);
rsm_1hop = rs_1hop.getMetaData();
int colCnt = rsm_1hop.getColumnCount();
for (int i=1; i<=colCnt; ++i) {
out.println("<th>" + rsm_1hop.getColumnName(i) + "</th>");
}
out.println("</tr>");
while (rs_1hop.next()) {
out.println("<tr>");
for (int i=1; i<=colCnt; ++i)
out.println("<td>" + rs_1hop.getString(i) + "</td>");
out.println("</tr>");
}
} catch (Exception e) {
} finally {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
out.println("</table><br><br>");
%>
After adding the ServletException in the catch block as commented by BalusC, and adding the odbc6.jar files under /WEB-INF/lib, I am getting the following error message which I suppose is due to the jdbc driver not found.
I also tried adding the jar files under Apache Tomcat installation dir /ROOT/web-apps/WEB_INF/lib so that they are available for all web-apps but the problem persists.
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: javax.servlet.ServletException: DB interaction failed! org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:500)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:410)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
javax.servlet.ServletException: DB interaction failed!
org.apache.jsp.retrievePossibleRoutes_jsp._jspService(retrievePossibleRoutes_jsp.java:96)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:128)
org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:66)
java.lang.Class.forName0(Native Method)
java.lang.Class.forName(Unknown Source)
org.apache.jsp.retrievePossibleRoutes_jsp._jspService(retrievePossibleRoutes_jsp.java:73)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
But after the execution of the Class.forName(...) line the program directly goes to finally block
That can only happen if a ClassNotFoundException was been thrown. This means that concrete class as specified by the given class name is not in the webapp's runtime classpath at all. That class is part of the Oracle JDBC driver. Putting the Oracle JDBC driver JAR file in /WEB-INF/lib folder of the webapp should fix that problem.
Further I strongly recommend you to do something in that empty catch (Exception e) {} block to indicate that an exception has occurred. Right now you're stabbing clueless around in the dark as to what really happened. If you have rethrown it as a ServletException, then you'd have gotten a much more self-explaining error page instead of a halfbaked JSP result.
} catch (Exception e) {
throw new ServletException(e);
}
Last but not least, writing Java code in a JSP file is a bad practice. How to salvage this properly, check this answer: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern.
Update as per your update:
After adding the ServletException in the catch block as commented by BalusC, and adding the odbc6.jar files under /WEB-INF/lib, I am getting the following error message which I suppose is due to the jdbc driver not found.
Then it's the wrong JAR file (i.e. it's not the one containing the oracle.jdbc.driver.OracleDriver class), or you didn't rebuild/redeploy/restart the webapp properly. Make sure that you've downloaded the right JDBC driver for your Oracle database version as listed here. Make sure that you've properly rebuilt/redeployed/restarted the webapp.
I also tried adding the jar files under Apache Tomcat installation dir /ROOT/web-apps/WEB_INF/lib so that they are available for all web-apps but the problem persists.
This is nonsense. Undo this change. To make a JAR available to all deployed webapps, put it in Tomcat's own /lib folder (the one straight in Tomcat installation folder). But that won't solve your problem if it's the wrong JAR file.