"DatabaseIOException: File system error (12)" when using database? - java

I have created a tab bar which appears when I enter first time in database screen, this code is working fine. But when we go on another tab and again go on database screen tab it throws an exception
net.rim.device.api.database.DatabaseIOException: File system error (12)
I have closed database properly.
I Have close database in finally block.Database is closing each time when I am moving the tab
This is my code:
Database d = null;
URI _uri = null;
Statement st = null;
Cursor c = null;
try
{
_uri=URI.create("file:///SDCard/MyBudgetTracker.db");
if (DatabaseFactory.exists(_uri)) {
d=DatabaseFactory.openOrCreate(_uri,new DatabaseSecurityOptions(false));
st = d.createStatement("SELECT * FROM "+Globalvalue.planCategoryTable);
st.prepare();
c = st.getCursor();
Row r;
int i = 0;
while(c.next()) {
r = c.getRow();
r.getString(0);
i++;
}
if (i==0)
{
add(new RichTextField("No data in the User table."));
}
}
}catch (Exception e)
{
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();// TODO: handle exception
} finally {
try {
if (DatabaseFactory.exists(_uri)) {
if (c != null) {
c.close();
}if (st != null) {
st.close();
} if (d != null) {
d.close();
}
}
} catch (Exception e2) {
// TODO: handle exception
}
}

You are retrieving values onto your selected tab from database?
You can think of this alternative method of opening and closing database.It always yields lesser errors.
try
{
//Open or create the database
Database db = DatabaseFactory.openOrCreate("MyBudgetTracker.db");
//Retrieve Data from db
Statement statement1 = db.createStatement("SELECT * FROM "+Globalvalue.planCategoryTable);
statement1.prepare();
statement1.execute();
statement1.close();
db.close();
}
catch(DatabaseException dbe)
{
System.err.println(dbe.toString());
}
Else you can include a db open statement on each of ur tabs before u fetch the value albeit it wud increase ur programming code lines.

Related

Continue the program execution in multiple try-catch statements scenario after catching exception

I have the following code running in my project:
HashMap<String, DeviceData> deviceMap = getAllDevices();
int status = 0;
DeviceHandle devHandle = null;
for (LicenseData licenseData:listLicenses) {
Map<String, String> licenseMap = licenseData.getLicenseKeyValues();
if ((licenseMap != null && !licenseMap.isEmpty())) {
String keyDecrypt = licenseMap.get("key");
Date expiryDate = new Date(Long.parseLong(licenseMap.get("expiryDate")));
boolean allowForeign = Boolean.parseBoolean(licenseMap.get("allowForeign"));
String ipDecrypt = licenseMap.get("ipAddress");
if (expiryDate.compareTo(new Date()) > 0 || keyDecrypt.equals(licenseData.getKey().getCurrentValueAsString()))
{
try {
DeviceData device = deviceMap.get(ipDecrypt);
devHandle = (DeviceHandle)device.getHandle();
if(device != null && devHandle != null) {
deviceMap.remove(ipDecrypt, device);
System.out.println("After deletion device map.");
System.out.println(deviceMap);
createUser(devHandle);
try {
if (allowForeign) {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statemnt
deleteUser(devHandle);
}
else {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statement
deleteUser(devHandle);
}
} catch(Exception e) {
//Exception statement
deleteUser(devHandle);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Explanation: I have a list of licenses for my application in listLicenses. All the devices present in the server are in deviceMap. For each license, I am decrypting it and getting the values. If license for a device is present, I get a handle on that device and doing some operations.
The issue is:
If I am not able to get a handle on device(getHandle()), or if I am not able to create a user after getting the device handle(createUser()), an exception is thrown. These methods are very hierarchical, i.e I am calling them from here, they are in another class throwing own exceptions and for their operation, they call other methods.
If there are three devices in the map, and three licenses, and if for the first one I am not able to get a handle or create a user, device is removed from deviceMap but no further execution happens i.e. for the next two devices.
If exception occurs for on device, I want to continue the exception for other two devices. I tried using return but couldn't get it to work.
Please help.Also, please forgive for the syntax and if any mismatch is there in the code.
Make use of first try's catch block.
This is how I handled when I faced same kind of situation.
catch (Exception exp) {
if (exp instanceof NullPointerException) {
log.info"Invalid/ Inactive ");
} else if (exp instanceof NonUniqueResultException) {
log.info("Multiple records existed");
} else {
exp.printStackTrace();
errorMsgs.append("Unexpected Error Occured. Please contact Admin.");
}
}

GeoTools getFeatures takes forever

I wrote the following method as an onClick handler. First and second click, I got result from DB. By the third time, the code stopped in the "getFeatures(trgtFilter)" line and didn't return. In debug mode, I saw that it is waiting for DB connection. Can someone tell me what I did wrong? I'm using GeoTools 15 and Oracle 12.
private Geometry getNewGeometry(String refID) throws Exception {
if (trgLayer != null) {
Connection con = null;
OracleConnection oraCon=null;
FeatureIterator<SimpleFeature> itr = null;
try {
con = ((JDBCDataStore) srcLayer.getFeatureSource().getDataStore()).getConnection(Transaction.AUTO_COMMIT);
oraCon = (OracleConnection) new DelegatingConnection(con).getInnermostDelegate();
Filter trgtFilter = editTask.getConfiguration().getReferenceFilter(trgLayer, refID);
FeatureCollection fc = trgLayer.getFeatureSource().getFeatures(trgtFilter);
itr = fc.features();
if (!itr.hasNext())
return null;
...
} catch (Exception e) {
throw e;
} finally {
if (itr != null)
itr.close();
if (oraCon != null) {
try {
oraCon.close();
if (con != null && !con.isClosed())
con.close();
} catch (SQLException e) {
LOGGER.error("", e);
}
}
}
}
}
If the filter is an 'id' filter, it could be that there is no index on that column in the Oracle table. If that's the case, the database will do a full-table scan.
Assuming you have a geospatial index and assuming the user is 'zoomed-in' on a given area, you could add the user viewport's geo-bounds to the query. With that query, the database can use the geo-index.
Alternatively, you can create an index on the fid/id column for the table if look-ups by feature id are going to be common.

Where to put the try catch blocks [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a button which gets a list of files into an array then calls a WwritefiletoDB function for each file:
private void BtnImportActionPerformed(java.awt.event.ActionEvent evt) {
// Create array to store filenames
List<String> filenames = new ArrayList<String>();
JTextFiles.append("*** Current Files Processing ***\n");
File dir = new File(TextFieldDirectory.getText());
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".pdf");
}
});
for (File file : files) {
if (file.isFile()) {
JTextFiles.append(file.getAbsolutePath() + "\n");
try {
writefiletoDB(file.getAbsolutePath());
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JTextFiles.append("*** Finished Processing ***\n");
}
Note the try catchblocks.
The writefiletoDB method has this code:
public void writefiletoDB(String currentfile) throws SQLException, IOException {
//System.out.println("This is current file:" + currentfile);
PDDocument pdfDocument = PDDocument.load(new File(currentfile));
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
List fields = acroForm.getFields();
PDField EventNo = acroForm.getField("EventNo");
System.out.println("Event String Length: " + EventNo.getValueAsString().length());
// If event number too short - then skip record
if (EventNo.getValueAsString().length() != 10) {
//JOptionPane.showMessageDialog(null, currentfile +" record was skipped - invalid EventNo = " +EventNo.getValueAsString());
JTextFiles.append("The above file skipped - the event number was incorrect length\n");
pdfDocument.close();
return;
};
Iterator fieldsIter = fields.iterator();
// Create Hashmap "pdf" storing PDF field names & values
Map<String, String> pdf = new HashMap<String, String>();
while (fieldsIter.hasNext()) {
PDField field = (PDField) fieldsIter.next();
// Next line removes braces for dropdowns and any leading whitespace
pdf.put(field.getPartialName(), field.getValueAsString().replaceAll("[\\[\\]]", "").trim());
}
//Create list "columns" to store field names from Database
List<String> columns = new ArrayList<String>();
Connection conn = null;
Statement stmnt = null;
try {
//Connect to DB
conn = DriverManager.getConnection("jdbc:ucanaccess://" + TextFieldDatabase.getText());
stmnt = conn.createStatement();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, "A SQL Error: " +se, "SQL ERROR", JOptionPane.ERROR_MESSAGE);
return;
}
// Check If Event Number already exists in DB - if so then exit
System.out.println("Checking if event exists");
PreparedStatement psEvent = conn.prepareStatement("SELECT EventNo FROM test WHERE EventNo = ?");
psEvent.setString(1, EventNo.getValueAsString());
ResultSet rsEvent = psEvent.executeQuery();
if (!rsEvent.next()) {
System.out.println("Result set is empty");
} else {
JTextFiles.append("The above record already exists - skipping\n");
pdfDocument.close();
return;
}
// Get a list of column names from database
ResultSet rs = stmnt.executeQuery("SELECT * FROM test WHERE False");
ResultSetMetaData rsmd = rs.getMetaData();
//System.out.println("Column names as reported by ResultSetMetaData:");
// Add the column names from database to List columns
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.println(rsmd.getColumnName(i));
// Store the column names from DB in list columns (via result set rsmd)
columns.add(rsmd.getColumnName(i));
}
// col and val strings to be built colname,colname and ?,?,?,? etc
// for sql prepared statement into DB
StringBuilder col = new StringBuilder();
StringBuilder val = new StringBuilder();
String separator = "";
for (String c : columns) {
if (pdf.containsKey(c)) {
col.append(separator).append(c);
val.append(separator).append("?");
separator = ",";
}
}
// Insert into DB SQL Statement
String sql = String.format("INSERT INTO test (%s) VALUES (%s)", col.toString(), val.toString());
System.out.println(
"This is sql statement: " + sql);
try (PreparedStatement insert = conn.prepareStatement(sql)) {
//Insert position in statement
int pos = 0;
//Second iterations: Bind the values to the statement *** colums is names of cols fromDB
for (String c : columns) {
//Your PDF has a matching formfield ** pdf is hashmap <string,string>
if (c.toLowerCase().contains("date")) {
System.out.println("A Date field has been found: " +c);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy kk:mm");
DateTime startdt = formatter.parseDateTime(pdf.get("DateStart") +" " +pdf.get("TimeStart"));
long millis = formatter.parseMillis(pdf.get("DateStart") +" " +pdf.get("TimeStart"));
Timestamp timeStamp = new Timestamp(millis);
insert.setTimestamp(++pos, timeStamp);
}
if (pdf.containsKey(c) && !c.toLowerCase().contains("date")) {
insert.setString(++pos, pdf.get(c));
}
}
insert.executeUpdate();
} catch (SQLException e) {
//JFrame frame;
JOptionPane.showMessageDialog(null, "A SQL Error: " +e, "SQL ERROR", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
pdfDocument.close();
}
Note the try catch block, about line 30. If it generates a error the return statement breaks and it returns to the calling method BtnImportActionPerformed and that loops calls the next file generating another error.
I need a way to break out of both writefiletoDB and also stop BtnImportActionPreformed.
Is there a way to handle writefiletoDB exceptions in BtnImportActionPreformed? or break out of both.
What is the best way to do this - I want to make the code more robust.
Thanks
Al
Simplifying your example to the relevant structure, the code is doing this:
void BtnImportActionPerformed() {
for(int i = 0l i < 10; i++) {
writefiletoDB();
}
}
void writefiletoDB() {
try {
doSomething();
} catch (SomeException e) {
return;
}
}
Since the exception is being caught and handled in the inner method, there's no way for the outer method to know that anything went wrong. If you want the outer method to know that an exception has occurred, use the same pattern as the inner method. Catch a thrown exception. Something like this:
void BtnImportActionPerformed() {
for(int i = 0l i < 10; i++) {
try {
writefiletoDB();
} catch (SomeException e) {
// do anything else?
return;
}
}
}
void writefiletoDB() throws SomeException {
try {
doSomething();
} catch (SomeException e) {
// log it? something else?
throw e;
}
}
You might even be able to skip the inner try/catch entirely if the outer method can do all of the exception handling. You'd simply have to declare the possible exceptions on the writefiletoDB method.
There are multiple ways to solve this, I would choose depending upon what is right for your logic.
Do not catch any exception and let the caller of BtnImportActionPerformed catch.
Put try catch around the for loop of BtnImportActionPerformed that way once exception is raised you are out of the loop. Do remove the try/catch inside the for loop.
From the writefiletoDB return success/failure instead of exception. In BtnImportActionPerformed based on the success/failure you can exit the loop.

Global cursor in Dropbox API v2

I use dropbox /delta endpoint to track changes inside Dropbox.
More precisely, the following piece of code allow me to track changes in "/superfolder" recursively (I'm using here DbxClientV1):
List<String> listOfResults = new ArrayList<String>();
String path = "/superfolder";
String cursor = null;
while (true) {
DbxDelta<DbxEntry> deltaWithPathPrefix = client.getDeltaWithPathPrefix(cursor, path);
cursor = deltaWithPathPrefix.cursor;
if (deltaWithPathPrefix.reset) {
System.out.println("Reset!");
}
for (DbxDelta.Entry entry : deltaWithPathPrefix.entries) {
if (entry.metadata == null) {
System.out.println("Deleted: " + entry.lcPath);
listOfResults.add(entry.lcPath);
} else {
System.out.println("Added or modified: " + entry.lcPath);
}
}
if (!deltaWithPathPrefix.hasMore) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(MainSearchV1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Now, I've switched to DbxClientV2 client. To track changes on dropbox I use client.files.listFolder() in the following form:
TreeMap<String, Metadata> children = new TreeMap<String, Metadata>();
Files.ListFolderResult result;
String cursor = null;
while (true) {
if (cursor == null) {
result = client.files.listFolder("/superfolder");
} else {
result = client.files.listFolderContinue(cursor);
}
cursor = result.cursor;
for (Metadata md : result.entries) {
if (md instanceof DeletedMetadata) {
children.remove(md.pathLower);
System.out.println("Deleted: " + md.pathLower);
} else {
children.put(md.pathLower, md);
System.out.println("State: " + md.pathLower);
System.out.println(md.toString());
}
}
if (!result.hasMore) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
Regretably, I've discovered that I can only track changes only of "superfolder" folder.
Is there a way to get a "global cursor" that tracks changes recursively in Dropbox API v2?
The Java SDK uses the builder pattern for pretty much all calls with multiple optional arguments. If I understand your question correctly, I think you're looking for this:
result = client.files.listFolderBuilder("/superfolder")
.recursive(true)
.start();
EDIT: You asked about a "global" cursor. I think you actually meant recursive, but in case you really meant global, you can pass an empty string ("") as a path to represent the root.

Java ResultSet already closed exception while querying user data

As I've started in the title, while I'm querying for user data in my java application, I get following message: "Operation not allowed after ResultSet closed".
I know that this is happens if you try to have more ResultSets opened at the same time.
Here is my current code:
App calls getProject("..."), other 2 methods are there just for help. I'm using 2 classes because there is much more code, this is just one example of exception I get.
Please note that I've translated variable names, etc. for better understanding, I hope I didn't miss anything.
/* Class which reads project data */
public Project getProject(String name) {
ResultSet result = null;
try {
// executing query for project data
// SELECT * FROM Project WHERE name=name
result = statement.executeQuery(generateSelect(tProject.tableName,
"*", tProject.name, name));
// if cursor can't move to first place,
// that means that project was not found
if (!result.first())
return null;
return user.usersInProject(new Project(result.getInt(1), result
.getString(2)));
} catch (SQLException e) {
e.printStackTrace();
return null;
} catch (BadAttributeValueExpException e) {
e.printStackTrace();
return null;
} finally {
// closing the ResultSet
try {
if (result != null)
result.close();
} catch (SQLException e) {
}
}
}
/* End of class */
/* Class which reads user data */
public Project usersInProject(Project p) {
ResultSet result = null;
try {
// executing query for users in project
// SELECT ID_User FROM Project_User WHERE ID_Project=p.getID()
result = statement.executeQuery(generateSelect(
tProject_User.tableName, tProject_User.id_user,
tProject_User.id_project, String.valueOf(p.getID())));
ArrayList<User> alUsers = new ArrayList<User>();
// looping through all results and adding them to array
while (result.next()) { // here java gets ResultSet closed exception
int id = result.getInt(1);
if (id > 0)
alUsers.add(getUser(id));
}
// if no user data was read, project from parameter is returned
// without any new user data
if (alUsers.size() == 0)
return p;
// array of users is added to the object,
// then whole object is returned
p.addUsers(alUsers.toArray(new User[alUsers.size()]));
return p;
} catch (SQLException e) {
e.printStackTrace();
return p;
} finally {
// closing the ResultSet
try {
if (result != null)
result.close();
} catch (SQLException e) {
}
}
}
public User getUser(int id) {
ResultSet result = null;
try {
// executing query for user:
// SELECT * FROM User WHERE ID=id
result = statement.executeQuery(generateSelect(tUser.tableName,
"*", tUser.id, String.valueOf(id)));
if (!result.first())
return null;
// new user is constructed (ID, username, email, password)
User usr = new user(result.getInt(1), result.getString(2),
result.getString(3), result.getString(4));
return usr;
} catch (SQLException e) {
e.printStackTrace();
return null;
} catch (BadAttributeValueExpException e) {
e.printStackTrace();
return null;
} finally {
// closing the ResultSet
try {
if (result != null)
result.close();
} catch (SQLException e) {
}
}
}
/* End of class */
Statements from both classes are added in constructor, calling connection.getStatement() when constructing each of the classes.
tProject and tProject_User are my enums, I'm using it for easier name handling. generateSelect is my method and should work as expected. I'm using this because I've found out about prepared statements after I have written most of my code, so I left it as it is.
I am using latest java MySQL connector (5.1.21).
I don't know what else to try. Any advice will be appreciated.
Quoting from #aroth's answer:
There are many situations in which a ResultSet will be automatically closed for you. To quote the official documentation:
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
A ResultSet object is automatically closed when the Statement object that generated
it is closed, re-executed, or used to retrieve the next result from a sequence of
multiple results.
Here in your code , You are creating new ResultSet in the method getUser using the same Statement object which created result set in the usersInProject method which results in closing your resultset object in the method usersInProject.
Solution:
Create another statement object and use it in getUser to create resultset.
It's not really possible to say definitively what is going wrong without seeing your code. However note that there are many situations in which a ResultSet will be automatically closed for you. To quote the official documentation:
A ResultSet object is automatically closed when the Statement object
that generated it is closed, re-executed, or used to retrieve the next
result from a sequence of multiple results.
Probably you've got one of those things happening. Or you're explicitly closing the ResultSet somewhere before you're actually done with it.
Also, have you considered using an ORM framework like Hibernate? In general something like that is much more pleasant to work with than the low-level JDBC API.

Categories

Resources