I am using Jackcess API in my Eclipse plugin project. I added jackcess-2.1.0.jar file under resources/lib. I included the jar under my Binary build and in build.properties. I successfully make a connection using connection string but my DatabaseBuilder.open() call is not executing. My code is
public void run() {
try {
File tempTarget = File.createTempFile("eap-mirror", "eap");
try {
this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
this.source.setReadOnly(true);
try {
FileUtils.copyFile(new File(templateFileString), tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
// Changes
try {
this.target = DatabaseBuilder.open(tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
Collection<String> tables = selectTables(source);
long time = System.currentTimeMillis();
for (String tableName : tables) {
long tTime = System.currentTimeMillis();
Table table = target.getTable(tableName);
System.out.print("Mirroring table " + tableName + "...");
table.setOverrideAutonumber(true);
copyTable(table, source, target);
System.out.println(" took "+ (System.currentTimeMillis() - tTime));
}
System.out.println("Done. Overall time: "+ (System.currentTimeMillis() - time));
System.out.println("done");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// More Code here
} catch (IOException e1) {
}
}
When I run the class in debug mode and I reach DatabaseBuilder.open call it fails.
Here is my project structure:
Can anyone tell me the possible reason for it ?
The .open method of DatabaseBuilder expects to open an existing well-formed Access database file. The .createTempFile method of java.io.File creates a 0-byte file. So, the code
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", "eap");
try (Database db = DatabaseBuilder.open(dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
will cause Jackcess to throw
java.io.IOException: Empty database file
when it tries to do DatabaseBuilder.open(dbFile).
Instead, you should DatabaseBuilder.create to convert the 0-byte file into a real Access database file like this
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", ".accdb");
dbFile.deleteOnExit();
try (Database db = DatabaseBuilder.create(Database.FileFormat.V2010, dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
Related
I'm trying to connect to my FTP server in Java SE 1.8. To do so I use this method :
private void connectFTP() {
String server = "ftp.XXXXXXXXXX.site";
int port = 21;
String user = "XXXX";
String pass = "XXXX";
if(!ftpConnexionSuccess.get())
{
client = new FTPClient();
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
try {
client.connect(server, port);
ftpConnexionSuccess.set(client.login(user, pass));
if (!ftpConnexionSuccess.get()) {
System.out.println("Could not login to the server");
return;
}
else
{
System.out.println("LOGGED IN SERVER");
client.changeWorkingDirectory("/crypto");
listenedFile = getListenedFile();
System.out.println(listenedFile.getName());
if(listenedFile != null)
{
baseFileTimeStamp.set(listenedFile.getTimestamp().getTimeInMillis());
}
System.out.println(baseFileTimeStamp);
}
} catch (Exception ex) {
System.err.println("FTP connection error : Sleeping for 5 seconds before trying again (" + ex.getMessage() + ")");
ex.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();}
try {
client.disconnect();
} catch (IOException e) {e.printStackTrace();}
connectFTP();
}
}
}
It works great when I'm on Eclipse and when I export the app on my Windows 10.
Nonetheless, when I try to launch the app on my AWS Webmachine I get a null pointer exception at "listenedFile". The method to listen to this file is the one below.
private FTPFile getListenedFile() {
FTPFile returnedFile = null;
try {
for(FTPFile file : client.listFiles())
{
if(file.getName().contains("filetolisten.txt"))
returnedFile = file;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
try {
client.disconnect();
} catch (IOException e1) {e1.printStackTrace();}
connectFTP();
return getListenedFile();
}
return returnedFile;
}
I thought it was because of the line
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked.
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked. Also updated Java, updated the common-nets library. Nothing worked
I am bit curious to know in the below code snippet, is there any chances of database connection not being closed. I am getting an issue in the SonarQube telling "Method may fail to close database resource"
try {
con = OracleUtil.getConnection();
pstmtInsert = con.prepareStatement(insertUpdateQuery);
pstmtInsert.setString(++k, categoryCode);
pstmtInsert.clearParameters();
pstmtInsert = con.prepareStatement(updateQuery);
for (i = 0; i < userList.size(); i++) {
pstmtInsert.setString(1, p_setId);
addCount = pstmtInsert.executeUpdate();
if (addCount == 1) {
con.commit();
usercount++;
} else {
con.rollback();
}
}
}
catch (SQLException sqle) {
_log.error(methodName, "SQLException " + sqle.getMessage());
sqle.printStackTrace();
EventHandler.handle();//calling event handler
throw new BTSLBaseException(this, "addInterfaceDetails", "error.general.sql.processing");
}
catch (Exception e) {
_log.error(methodName, " Exception " + e.getMessage());
e.printStackTrace();
EventHandler.handle();//calling event handler
throw new BTSLBaseException(this, "addInterfaceDetails", "error.general.processing");
}
finally {
try {
if (pstmtInsert != null) {
pstmtInsert.close();
}
} catch (Exception e) {
_log.errorTrace(methodName, e);
}
try {
if (con != null) {
con.close();
}
} catch (Exception e) {
_log.errorTrace(methodName, e);
}
if (_log.isDebugEnabled()) {
_log.debug("addRewardDetails", " Exiting addCount " + addCount);
}
}
Thanks in advance
If you are using Java 7+, I suggest you use try-with-resources. It ensures the resources are closed after the operation is completed.
Issue has been resolved when I closed the first prepare statement before starting the another one.
added below code snippet after the line pstmtInsert.clearParameters();
try {
if (pstmtInsert != null) {
pstmtInsert.close();
}
} catch (Exception e) {
_log.errorTrace(methodName, e);
}
So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.
I am using org.apache.commons.net.ftp.FTPClient for downloading files from ftp server.
It downloads all the files from my ftp server except those files with names like test.xml test.txt west.xml etc., The files with these names are getting downloaded with no data inside the file. retrieveFile() method is returning boolean false for these files.
I tried to download the same file by renaming its name manually on ftp server. It worked well with other names.
Please let me know how to solve this problem.
EDIT- Adding sample code
public static boolean downloadFTPDir(String localDir, FTPClient ftpClient) {
OutputStream output = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
/*
* Use passive mode as default because most of us are behind
* firewalls these days.
*/
ftpClient.enterLocalPassiveMode();
FTPFile[] fileList = ftpClient.listFiles();
for (FTPFile ftpFile : fileList) {
if(ftpFile.isDirectory()){
String tempDir = localDir + File.separatorChar+ftpFile.getName();
try {
File temp = new File(tempDir);
temp.mkdirs();
} catch (Exception e) {
System.out.println("Could not create local directory "+tempDir);
return false;
}
if(ftpClient.changeWorkingDirectory(ftpFile.getName())) {
downloadFTPDir(tempDir, ftpClient);
} else {
System.out.println("Could change directory to "+ftpFile.getName()+" on FTP server");
return false;
}
} else {
output = new FileOutputStream(localDir + File.separatorChar + ftpFile.getName());
if (!ftpClient.retrieveFile(ftpFile.getName(), output)) {
System.out.println("Unable to download file from FTP server : " + ftpFile.getName());
File tmp = null;
try {
output.close();
/*tmp = new File(localDir + File.separatorChar + ftpFile.getName());
tmp.delete();
logger.info("Deleted corrupt downloaded file : " + tmp.getAbsolutePath());*/
} catch (FTPConnectionClosedException e) {
System.out.println("Connection to FTP server is closed ");
return false;
} catch (Exception e1) {
System.out.println("Unable to delete corrupt file from local directory : " + tmp.getAbsolutePath());
return false;
}
}
output.close();
System.out.println("FTP file download successful : " + ftpFile.getName());
}
}
} catch (FTPConnectionClosedException e) {
e.printStackTrace();
return false;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return false;
} catch (IOException e2) {
e2.printStackTrace();
return false;
} catch (Exception e3) {
try {
output.close();
} catch (Exception e4) {
e3.printStackTrace();
}
return false;
} finally{
try {
if(output!=null)
output.close();
} catch (Exception e5) {
e5.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("FTP IP", 21);
System.out.println("connecting");
if(FTPReply.isPositiveCompletion(ftpClient.getReply())) {
System.out.println("connected");
if(!ftpClient.login("FTP username", "FTP Password")) {
System.out.println("could not login");
ftpClient.disconnect();
return;
}
System.out.println("logged in");
String remotePath = "FTP directory Path";
StringTokenizer st = new StringTokenizer(remotePath, "/");
String dir = null;
boolean status = false;
while (st.hasMoreTokens()) {
dir = st.nextToken();
status = ftpClient.changeWorkingDirectory(dir);
if (!status) {
System.out.println("FTP client is not able to change the current directory to " + dir);
return ;
}
}
System.out.println("connected");
downloadFTPDir("local path", ftpClient);
} else {
ftpClient.disconnect();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have two arrays that I want to print to separate files. Here's my code:
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Edges.txt"));
for (i = 0; i < bcount; i++) {
out.println(b[i][0] + " " + b[i][1]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Nodes.txt"));
for (i = 0; i < bigbIter; i++) {
out.println(bigb[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
If I only use the first set of try / catch / catch, it works perfectly. But when I use both it doesn't work, giving me the errors "illegal start of type ... } catch" and "error: class, interface, or enum expected". What am I doing wrong?
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
You have an extra }, which throws off the parser and gives you lots of errors.
You should write a method to write to the file. Just pass the file name and data. You should see that you have too many closing brackets, get your IDE to highlight brackets.
Lesson is just don't copy/paste and then edit the catch block when you want it again!
Edit: Also in java 7 you can have multiple catches in one block, it is better to do this:
catch (FileNotFoundException | IOException e)
{
}