Oracle Connection close issue with oracle 12c - java-8

I am using java 1.8 and oracle 12c versions in my application. As part of this I have below code to close the statement.
protected static void close(Statement p_stmt)
throws DAOException
{
if (p_stmt != null) {
try {
p_stmt.close();
} catch (SQLException sqle) {
m_logger.error("Error closing statement", sqle);
throw new DAOException("Error closing statement", sqle);
}
}
}
When this method executes, I am facing the below error but it is not happening consistently.
Error closing statement
java.sql.SQLRecoverableException: Closed Connection
at oracle.jdbc.driver.PhysicalConnection.needLine(PhysicalConnection.java:4220)
at oracle.jdbc.driver.OracleStatement.closeOrCache(OracleStatement.java:1431)
at oracle.jdbc.driver.OracleStatement.close(OracleStatement.java:1410)
at oracle.jdbc.driver.OracleStatementWrapper.close(OracleStatementWrapper.java:102)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.close(OraclePreparedStatementWrapper.java:82)
Could I get some help to figure out the root cause of this issue?
My calling code is:
finally
{
// do not close the connection here
close(result);
close(stmt);
}
Please let me know for more information

Use try-with-resource statement instead of manually closing statement, resultset and connection like that:
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setxxx();
try (ResultSet rs = ps.executeQuery()) {
<your code to process results>
}
} catch (SQLException e) {
e.printStackTrace();
}

Related

How to use RemoteFileTemplate<SmbFile> in Spring integration?

I've got a Spring #Component where a SmbSessionFactory is injected to create a RemoteFileTemplate<SmbFile>. When my application runs, this piece of code is called multiple times:
public void process(Message myMessage, String filename) {
StopWatch stopWatch = StopWatch.createStarted();
byte[] bytes = marshallMessage(myMessage);
String destination = smbConfig.getDir() + filename + ".xml";
if (log.isDebugEnabled()) {
log.debug("Result: {}", new String(bytes));
}
Optional<IOException> optionalEx =
remoteFileTemplate.execute(
session -> {
try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
session.write(inputStream, destination);
} catch (IOException e1) {
return Optional.of(e1);
}
return Optional.empty();
});
log.info("processed Message in {}", stopWatch.formatTime());
optionalEx.ifPresent(
ioe -> {
throw new UncheckedIOException(ioe);
});
}
this works (i.e. the file is written) and all is fine. Except that I see warnings appearing in my log:
DEBUG my.package.MyClass Result: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>....
INFO org.springframework.integration.smb.session.SmbSessionFactory SMB share init: XXX
WARN jcifs.smb.SmbResourceLocatorImpl Path consumed out of range 15
WARN jcifs.smb.SmbTreeImpl Disconnected tree while still in use SmbTree[share=XXX,service=null,tid=1,inDfs=true,inDomainDfs=true,connectionState=3,usage=2]
INFO org.springframework.integration.smb.session.SmbSession Successfully wrote remote file [path\to\myfile.xml].
WARN jcifs.smb.SmbSessionImpl Logging off session while still in use SmbSession[credentials=XXX,targetHost=XXX,targetDomain=XXX,uid=0,connectionState=3,usage=1]:[SmbTree[share=XXX,service=null,tid=1,inDfs=false,inDomainDfs=false,connectionState=0,usage=1], SmbTree[share=XXX,service=null,tid=5,inDfs=false,inDomainDfs=false,connectionState=2,usage=0]]
jcifs.smb.SmbTransportImpl Disconnecting transport while still in use Transport746[XXX/999.999.999.999:445,state=5,signingEnforced=false,usage=1]: [SmbSession[credentials=XXX,targetHost=XXX,targetDomain=XXX,uid=0,connectionState=2,usage=1], SmbSession[credentials=XXX,targetHost=XXX,targetDomain=null,uid=0,connectionState=2,usage=0]]
INFO my.package.MyClass processed Message in 00:00:00.268
The process method is called from a Rest method, which does little else.
What am I doing wrong here?

Spocking the JDBC

I have some Groovy 2.4.x code that uses some JDBC:
class WidgetPersistor {
#Inject // Gets injected correctly by Guice, don't worry about it!
DataSource dataSource
Fizz getFizzByWidgetName(String name) {
Connection conn
PreparedStatement ps
ResultSet rs
try {
// JDBC code here
} catch(SQLException sqlExc) {
if(conn) {
try {
// NOTE: At the end of the day, I just want to verify
// that, given the 'name' arg to this method, the rollback
// doesn't fire!
conn.rollback()
} catch(SQLException rollBackExc) {
throw rollBackExc
}
}
throw sqlExc
} finally {
if(conn) {
try {
rs.close()
ps.close()
conn.close()
} catch(SQLException closingExc) {
throw closingExc
}
}
}
}
}
I am trying to write a Spock test that will execute this getFizzByWidgetName method and verify that the conn.rollback() method never executed (meaning we never tried to rollback).
Here's my best attempt:
def "getFizzByWidgetName succeeds without rollback"() {
given: "data client with db connections"
// Don't worry about how I get this for my test, but its a legit JDBC connection
DataSource ds = provideDataSource()
Connection mockConn = Mock(Connection)
PreparedStatement mockPS = Mock(PreparedStatement)
ResultSet mockRS = Mock(ResultSet)
mockPS.executeQuery() >> mockRS
mockConn.prepareStatement(_) >> mockPS
ds.connection >> mockConn // ??? Its like I want the DataSource half-mocked...
WidgetPersistor client = new WidgetPersistor(mockDS)
when: "we try to query something"
client.getFizzByWidgetName('fizzbuzz')
then: "we dont get any errors"
0 * mockConn.rollback()
}
Any ideas where I'm going awry?
If you are using a DataSource from a real database, and your code under test is written in Groovy (which looks like the case), you can use the metaclass to test this kind of things:
DataSource ds = provideDataSource()
def connection = ds.connection
connection.metaClass.rollback = { throw new AssertionError("rollback called") }
ds.metaClass.connection = connection
But it's not really pretty. You should probably call your method without using mocks, and test the state of the database (ie, data have been committed, not rollbacked)

Realm throw catch swift 2.0

does anyone know the syntax for the try-catch of the following realm function is?
realm.write() {
realm.add(whatever)
}
I'm getting the following error:
call can throw but it is not marked with 'try' and the error is not
handled
From what I imagine realm.write() can throw an exception. In Swift 2 you handle exceptions with do/catch and try.
I suspect that you should do something like this:
do {
try realm.write() {
realm.add(whatever)
}
} catch {
print("Something went wrong!")
}
If realm.write() throws an exception, print statement will be invoked immediately.
It looks like an NSError gets thrown. See the Swift 2.0 source
Adding on to #tgebarowski's answer:
do {
try self.realm.write {
realm.add(whatever)
}
} catch let error as NSError {
print("Something went wrong!")
// use the error object such as error.localizedDescription
}
You can also try
try! realm.write {
realm.add(whatever)
}

Error processing GroovyPageView: getOutputStream() has already been called for this response

I have an action that writes directly to the output stream. Sometimes I get the following to errors:
Error processing GroovyPageView: getOutputStream() has already been called for this response
Caused by getOutputStream() has already been called for this response
and this one:
Executing action [getImage] of controller [buddyis.ItemController] caused exception: Runtime error executing action
Caused by Broken pipe
How can I solve these problems? The action I use is listed below.
NOTE: I use Tomcat 7.0.42, if this is important!
def getImage() {
byte [] imageByteArray = // some image bytes
response.setHeader 'Content-disposition', "attachment; filename=\"${imageName}${imageExtension}\""
response.setContentType("image/pjpeg; charset=UTF-8")
response.contentLength = imageByteArray.size()
response.outputStream.write(imageByteArray)
response.outputStream.flush()
response.outputStream.close()
return
}
I don't know why you are getting that error, however here is what I do that works everytime.
I don't call .flush() or .close()
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=\"${name}\"")
response.setContentLength(imageByteArray.size())
response.outputStream << imageByteArray
Using the above it was working fine, until I found out a user can cancel a download, which caused an exception. This is the full code I use instead of response.outputStream << imageByteArray:
def outputStream = null
try {
outputStream = response.outputStream
outputStream << imageByteArray
} catch (IOException e){
log.debug('Canceled download?', e)
} finally {
if (outputStream != null){
try {
outputStream.close()
} catch (IOException e) {
log.debug('Exception on close', e)
}
}
}
I had this issue whilst running grails 2.5 on tomcat:7.0.55.3 and with the java-melody grails plugin installed. After uninstalling java-melody it worked just fine

h2 mixed mode connection problem

I start h2 database in a servlet context listener:
public void contextInitialized(ServletContextEvent sce) {
org.h2.Driver.load();
String apprealPath = sce.getServletContext().getRealPath("\\");
String h2Url = "jdbc:h2:file:" + apprealPath + "DB\\cdb;AUTO_SERVER=true";
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
StatusPrinter.print(lc);
logger.debug("h2 url : " + h2Url);
try {
conn = DriverManager.getConnection(h2Url, "sa", "sa");
} catch (SQLException e) {
e.printStackTrace();
}
logger.debug("h2 database started in embedded mode");
sce.getServletContext().setAttribute("connection", conn);
}
then I try to use dbvisualizer to connect to h2 using following url :
jdbc:h2:tcp://localhost/~/cdb
but get these error messages:
An error occurred while establishing the connection:
Type: org.h2.jdbc.JdbcSQLException Error Code: 90067 SQL State: 90067
Message:
Connection is broken: "Connection refused: connect" [90067-148]
I tried to replace localhost with "172.17.33.181:58524" (I found it in cdb.lock.db)
reconnect with user "sa" password "sa" ,then server response changed to :
wrong username or password !
In the Automatic Mixed Mode, you don't need to (and you can't) use jdbc:h2:tcp://localhost. Just use the same URL everywhere, that means jdbc:h2:file:...DB\\cdb;AUTO_SERVER=true.
You can use the same database URL independent of whether the database is already open or not. Explicit client/server connections (using jdbc:h2:tcp:// or ssl://) are not supported.

Resources