Java JDBC-ODBC cannot load driver for Excel - java

import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionExample {
public static void main(String args[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
System.out.println("JDBC-ODBC driver failed to load.");
return;
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:abcdefg", "", "");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
This code always prints
"JDBC-ODBC driver failed to load."
I can't understand what the problem is.. I follow these steps:
go to c:\windows\sysWOW64\odbcad32.exe
system dsn tab - add -> Microsoft Excel Driver (*xls, *xlsx, *xlsm, *xlsb)
give Data Source Name abcdefg
Select Workbook -> go to myFile excel path and add it -> OK
and then run my code... where is the mistake?

The JDBC-ODBC Bridge is obsolete and has been removed from Java 8. If you need to manipulate an Excel document and you are unable (or unwilling) to downgrade your environment to Java 7 then you might want to investigate Apache POI.

Related

Connecting mongodb to java project in Eclipse IDE (MacOS)

I'm trying to connect mongodb to my java project in eclipse. I've mentioned the code I've written following some instructions on youtube and the official mongodb documentation.
Below are the .jar files I've added to the project build path.
Project Properties/Build Path/JRE Files
package mongoConnect;
import com.mongodb.*;
import com.mongodb.client.MongoClients;
#SuppressWarnings("unused")
public class MongoDatabase {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
com.mongodb.client.MongoClient client = MongoClients.create("mongodb://localhost:27017");
DB db1 = mongo.getDB("collegemanagementsystem");
//error saying "mongo cannot be resolved" in mongo.getDB
DBCollection col1 = db1.getCollection("Student");
BasicDBObject d1 = new BasicDBObject("name", "Sabiha").append("age", "23");
BasicDBObject d2 = new BasicDBObject("name", "Abdullah").append("age", "25");
col1.insert(d1);
col1.insert(d2);
DBCursor cur = col1.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
The Code
I do have mongodb compass installed if that helps. I also have a local database created in mongodb.
Mongodb Connection in Mongodb Compass
My questions are:
Is this method different to connecting by jdbc or is this the jdbc method for connecting database to java project?
How can I resolve this issue?
If this is not the jdbc method how can I connect mongodb to my java project with the jdbc method?
Error Message

Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.io

I am a beginner to java, and right now start learning Java IO API. However when I run this simple BufferedWriter program, I got this error
"A JNI error has occurred, please check your installation and try
again"
package java.io.demo;
public class BufferedWriterDemo {
public static void main(String[] args) {
String directory =System.getProperty("user.home");
String fileName ="sample.txt";
String absolutePath =directory + File.separator + fileName;
String text ="This is a text sample";
try {
BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter(absolutePath));
bufferedWriter.write(text);
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am using eclipse photon and java 8
JRE Screenshoot
Any help?
import java.io.* would work. But as per the error, you are showing shows you have an issue in your jdk installation. Please check your java version and JAVA_HOME path.

Error using gecko driver script for Selenium 3.11

I am using Selenium version 3.11, gecko driver v0.20 and Firefox version 59. I used the system.setproperty script but I'm still getting this error:
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property
I also tried this with Firefox v40.
Please help me sort out this issue. Thanks.
The syntax i used is as follows :
System.setProperty("webdriver. gecko.driver","C:\geckodriver.exe");
Try to do something like that:
public void loadSystemProperties() {
try {
InputStream in = getClass().getResourceAsStream("/geckodriver");
File file = stream2file(in);
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());
LOGGER.info("Geckdriver found at {}", file.getAbsoluteFile());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
static File stream2file(InputStream in) throws IOException {
String PREFIX = "stream2file";
String SUFFIX = ".tmp";
final File tempFile = File.createTempFile(PREFIX, SUFFIX);
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
tempFile.setExecutable(true);
return tempFile;
}
I'm using commons-io, version 2.6. In addition, my geckodriver is in my resource folder.
Thanks for your response.My issue stands resolved after setting the geckodriver path in the environment variable settings.
But can anyone help me with one question: which latest firefox version will support firebug and xpath addons?

JDBC - csv file Error

I have a simple question, somehow I can't see where my problem is.
I've got a csv file in my C:/Temp folder. I would like to connect to the csv to get some data (depending on specific row data, different rows,...).
So I downloaded the csvjdbc-1.0-28.jar file and added it to the build path.
I wrote the code as shown below but always get the error:
"java.sql.SQLException: No suitable driver found for"
I have seen some people got also problems with it but I did not get the problem behind the issue I have. I know it has something to do with the Connection conn. Do I need to do some additional JDBC settings or how can I add the path for the connection?
Thanks in advance!
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.relique.jdbc.csv.CsvDriver;
public class Main_Class {
public static void main(String[] args) {
try {
try {
Class.forName("org.relique.jdbc.csv.CsvDriver");
Connection conn = DriverManager
.getConnection("c:\\temp\\Spieltage_log.txt");
Statement stmt = conn.createStatement();
ResultSet results = stmt
.executeQuery("select * from Offensiver_Zweikampf");
boolean append = true;
CsvDriver.writeToCsv(results, System.out, append);
conn.close();
System.out.println(results);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// JFrame fenster = new Main_Menue();
}
}
According to the example at (http://csvjdbc.sourceforge.net/)-
// Create a connection. The first command line parameter is
// the directory containing the .csv files.
// A single connection is thread-safe for use by several threads.
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + directoryName);
In your case it should be -
Properties props = new Properties();
props.put("fileExtension", ".txt");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:C:\\temp", props);
Also you've put the content in a txt file, so you'll need to specify a custom property with the fileExtension as '.txt' in it.
Your resultSet object than can query the file using the below syntax -
ResultSet results = stmt.executeQuery("select * from Spieltage_log");
The URL string passed to DriverManager.getConnection() needs to specify the driver name:
Connection conn = DriverManager
.getConnection("jdbc:relique:csv:c:\\temp");
Besides, you need to pass the directory of the csv file and not the file itself. See answer of Sachin who in the meantime posted detailed instructions.
Sorry my fault: I saved the file as a xlsx file and not csv file. So solved it now and it worked! Thanks a lot guys! Appreciate your help

Converting a PDF to text using Tesseract OCR

AIM: convert a PDF to base64 where PDF can be a general PDF or a scanned one.
I am using Tesseract OCR for converting scanned PDFs to text files. Since I am working in Java, I am using terr4j library for this.
The flow of program as I have thought would be as follows:
Get PDF file ---> Convert each page to image using Ghost4j ---> Pass each image to tess4f for OCR ---> convert whole text to base64.
I have been able to convert a PDF file to Images using following code:
package helpers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.awt.Image;
import java.awt.image.RenderedImage;
import java.util.List;
import javax.imageio.ImageIO;
import org.ghost4j.document.DocumentException;
import org.ghost4j.document.PDFDocument;
import org.ghost4j.analyzer.FontAnalyzer;
import org.ghost4j.renderer.RendererException;
import org.ghost4j.renderer.SimpleRenderer;
import net.sourceforge.tess4j.*;
class encoder {
public static byte[] createByteArray(File pCurrentFolder, String pNameOfBinaryFile) {
String pathToBinaryData = pCurrentFolder.getAbsolutePath()+"/"+pNameOfBinaryFile;
File file = new File(pathToBinaryData);
if (!file.exists()) {
System.out.println(pNameOfBinaryFile+" could not be found in folder "+pCurrentFolder.getName());
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte fileContent[] = new byte[(int) file.length()];
try {
if (fin != null)
fin.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
public void covertToImage(File pdfDoc) {
PDFDocument document = new PDFDocument();
try {
document.load(pdfDoc);
} catch (IOException e) {
e.printStackTrace();
}
SimpleRenderer renderer = new SimpleRenderer();
renderer.setResolution(300);
List<Image> images = null;
try {
images = renderer.render(document);
} catch (IOException e) {
e.printStackTrace();
} catch (RendererException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
try {
if (images != null) {
// for testing only 1 page
ImageIO.write((RenderedImage) images.get(10), "png", new File("/home/cloudera/Downloads/1.png"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class encodeFile {
public static void main(String[] args) {
/* This part is for pure PDF files i.e. not scanned */
//byte[] arr = encoder.createByteArray(new File("/home/cloudera/Downloads/"), "test.pdf");
//String result = javax.xml.bind.DatatypeConverter.printBase64Binary(arr);
//System.out.println(result);
/* This part create the image for a page of scanned PDF file */
new encoder().covertToImage(new File("/home/cloudera/Downloads/isl99201.pdf")); // results in 1.png
/* This part is for OCR */
Tesseract instance = new Tesseract();
String res = instance.doOCR(new File("/home/cloudera/Downloads/1.png"));
System.out.println(res);
}
}
Running this produces these errors:
This occurs when I try to create an image from the PDF. I have seen that if I remove tess4j from build.sbt, image is created with out any errors but I have to use it with that.
Connected to the target VM, address: '127.0.0.1:46698', transport: 'socket'
Exception in thread "main" java.lang.AbstractMethodError: com.sun.jna.Structure.getFieldOrder()Ljava/util/List;
at com.sun.jna.Structure.fieldOrder(Structure.java:884)
at com.sun.jna.Structure.getFields(Structure.java:910)
at com.sun.jna.Structure.deriveLayout(Structure.java:1058)
at com.sun.jna.Structure.calculateSize(Structure.java:982)
at com.sun.jna.Structure.calculateSize(Structure.java:949)
at com.sun.jna.Structure.allocateMemory(Structure.java:375)
at com.sun.jna.Structure.<init>(Structure.java:184)
at com.sun.jna.Structure.<init>(Structure.java:172)
at com.sun.jna.Structure.<init>(Structure.java:159)
at com.sun.jna.Structure.<init>(Structure.java:151)
at org.ghost4j.GhostscriptLibrary$display_callback_s.<init>(GhostscriptLibrary.java:63)
at org.ghost4j.Ghostscript.buildNativeDisplayCallback(Ghostscript.java:381)
at org.ghost4j.Ghostscript.initialize(Ghostscript.java:336)
at org.ghost4j.renderer.SimpleRenderer.run(SimpleRenderer.java:105)
at org.ghost4j.renderer.AbstractRemoteRenderer.render(AbstractRemoteRenderer.java:86)
at org.ghost4j.renderer.AbstractRemoteRenderer.render(AbstractRemoteRenderer.java:70)
at helpers.encoder.covertToImage(encodeFile.java:62)
at helpers.encodeFile.main(encodeFile.java:86)
Disconnected from the target VM, address: '127.0.0.1:46698', transport: 'socket'
Process finished with exit code 1
This error occurs while passing any image to tess4j:
Connected to the target VM, address: '127.0.0.1:46133', transport: 'socket'
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'tesseract': Native library (linux-x86-64/libtesseract.so) not found in resource path (....)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:271)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:398)
at com.sun.jna.Library$Handler.<init>(Library.java:147)
at com.sun.jna.Native.loadLibrary(Native.java:412)
at com.sun.jna.Native.loadLibrary(Native.java:391)
at net.sourceforge.tess4j.util.LoadLibs.getTessAPIInstance(LoadLibs.java:78)
at net.sourceforge.tess4j.TessAPI.<clinit>(TessAPI.java:40)
at net.sourceforge.tess4j.Tesseract.init(Tesseract.java:360)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:273)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:205)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:189)
at helpers.encodeFile.main(encodeFile.java:89)
Disconnected from the target VM, address: '127.0.0.1:46133', transport: 'socket'
Process finished with exit code 1
I am working on Intellij using SBT on 64 bit CentOS 6.6. By some internet search I have able to understand the issues above but I am facing two constraints:
The JNA library that is being used is by default of the latest version i.e. 4.1.0. I read on the internet about the incompatibility between JNA and other libraries this can occur. So I tried to specify the older version of 3.4.0. But build.sbt keeps rejecting that.
I am on a 64 Bit system and tessearct would work with a 32 Bit system. How should I integrate it in the project?
Following is the part from build.sbt which handles all the required libraries:
"org.ghost4j" % "ghost4j" % "0.5.1",
"org.bouncycastle" % "bctsp-jdk14" % "1.46",
"net.sourceforge.tess4j" % "tess4j" % "2.0.0",
"com.github.jai-imageio" % "jai-imageio-core" % "1.3.0"
"net.java.dev.jna" % "jna" % "3.4.0", // does not make any difference as only 4.1.0 is installed.
Please help me out in this problem.
UPDATE: I added "net.java.dev.jna" % "jna" % "3.4.0" force() to build.sbt and it solved my first problem.
The solution to this issue lies in the Tesseract-API that I found on github. I forked it into my Github account and added a test for a scanned image and did some code refactoring. This way to library started to function properly. The scanned doc I used for testing is here.
I built it successfully on Travis and now it working fine on 32 as well as 64 bit systems.

Categories