Cannot close Oracle connection from WebSphere datasource - oracle

I try to connect to Oracle database (check connection status). I'm using following code, which works fine.
public String getDatabaseStatus() {
Connection conn;
try {
conn = DriverManager.getConnection( "jdbc:oracle:thin:#192.168.0.70:1521:XE", "foo","bar");
conn.close();
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
However, when using Websphere datasource, after 10 (connection limit) refreshes page hangs. Code:
public String getDatabaseStatus() {
Connection conn;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
conn = WSCallHelper.getNativeConnection(ds.getConnection());
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
I tried to close provided connection, but it gives me error:
J2CA0206W - A connection error occurred. To help determine the problem, enable the Diagnose Connection Usage option on the Connection Factory or Data Source. This is the multithreaded access detection option. Alternatively check that the Database or MessageProvider is available.
Any help will be appreciated.

You must close the connection that you received from the DataSource:
public String getDatabaseStatus() {
Connection conn;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
java.sql.Connection connection = ds.getConnection();
try {
conn = WSCallHelper.getNativeConnection(connection);
} finally {
safeClose(connection);
}
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
private void safeClose(java.sql.Connection connection) {
try {
connection.close();
} catch (SQLException e) {
log.warn("Failed to close database connection", e);
}
}
If you're using Java 7 or better you can simplify it to:
public String getDatabaseStatus() {
Connection conn;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/xe");
try (java.sql.Connection connection = ds.getConnection()) {
conn = WSCallHelper.getNativeConnection(connection);
}
} catch (Exception e) {
return "ERR - " + e.getMessage();
}
return "Connection succesful";
}
If you fail to do this your connections will not be returned to the pool and you will run out of connections.

Related

How to use oracle proxy connection with JPA repository

I'm using this openProxyConnection in the oracle method to create a proxy user to the database and used it with JDBC connection as below.
public static void openProxyConnection(OracleConnection conn, HttpUserDetails userDetails)
throws SQLException {
java.util.Properties prop = new java.util.Properties();
prop.put(OracleConnection.PROXY_USER_NAME,
userDetails.getUserName().toUpperCase()); //To uppercase needed for 11g compatibility
try {
// Open proxy connection for user
conn.openProxySession(OracleConnection.PROXYTYPE_USER_NAME, prop);
log.debug("Login proxy user: " + userDetails.getUserName());
try (PreparedStatement preparedStatement = conn
.prepareStatement("begin DBMS_APPLICATION_INFO.SET_CLIENT_INFO (?); end;")) {
preparedStatement.setString(1, userDetails.getClientIp());
preparedStatement.execute();
}
} catch (Exception e) {
throw new ProxyConnectionException("Error creating proxy connection", e);
}
}
#Override
public GetHostNameOutputDto getUserDetailsList(GetHostNameInputDto loginRequest, String spcNumber)
throws SQLException {
OracleCallableStatement statement = null;
OracleConnection connection = null;
GetHostNameOutputDto getHostNameOutputDto = new GetHostNameOutputDto();
try {
connection = (OracleConnection) dataSource.getConnection();
DbUtil.openProxyConnection(connection, httpUserDetails);
statement = (oracle.jdbc.OracleCallableStatement) connection
.prepareCall("begin ? := spc_login.get_host_name(?); end;");
statement.registerOutParameter(1, OracleTypes.VARCHAR);
statement.executeQuery();
...
As in the above example would I be able to get the proxy connection for JpaRepository? Something like below?
List<JobCode> jobCodeList = jobCodeRepository.findByLfunLbrFuncAndCorpCode("IN", "Y");

IBM MQ JMSWMQ0018: Failed to connect to queue manager 'MY_LOCAL_QM' with connection mode 'Client' and host name 'MY_LOCAL_QM(1401)'

I created a queue manager, queue, channel(Server-connection).
When I try to send a message, see this error:
com.ibm.msg.client.jms.DetailedIllegalStateException: JMSWMQ0018: Failed to connect to queue manager 'MY_LOCAL_QM' with connection mode 'Client' and host name 'epspa(1401)'.
Check the queue manager is started and if running in client mode, check there is a listener running. Please see the linked exception for more information.
Maybe I need to set a user to queue manager? Because I use the same java code, but try to connect to another queue manager, and it works fine. But it doesn't work with my queue manager.
IBM MQ installed on another PC.
private static final String HOST = "epspa";
private static final int PORT = 1401;
private static final String CHANNEL = "API.SVRCONN_LOCAL";
private static final String QMN = "MY_LOCAL_QM";
private static final String QUEUE_NAME = "API.QUEUE_NAME";
private static final String message ="message";
public static String sendMessage(String message) {
String result = "Error";
try {
MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
cf.setHostName(HOST);
cf.setChannel(CHANNEL);
cf.setPort(PORT);
cf.setQueueManager(QMN);
cf.setTransportType(WMQConstants.WMQ_MESSAGE_BODY_MQ);
Destination destination = null;
MessageProducer producer = null;
Connection c = cf.createConnection();
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = s.createQueue(QUEUE_NAME);
producer = s.createProducer(destination);
TextMessage tmo = s.createTextMessage();
((MQDestination) destination).setMessageBodyStyle
(WMQConstants.WMQ_MESSAGE_BODY_MQ);
tmo.setIntProperty(WMQConstants.JMS_IBM_CHARACTER_SET, 1208);
tmo.setIntProperty(WMQConstants.JMS_IBM_ENCODING,546);
tmo.setText(message);
producer.send(tmo);
result = "Success!";
} catch (JMSException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
cf.setTransportType(WMQConstants.WMQ_MESSAGE_BODY_MQ);
Well, that's not correct. It should be:
cf.setTransportType(WMQConstants.WMQ_CM_CLIENT);
JMSWMQ0018: Failed to connect to queue manager
A JMS error does not give enough details about what MQ is complaining about. You need to output the LinkedException.
catch (JMSException e)
{
if (e != null)
{
System.err.println("getLinkedException()=" + e.getLinkedException());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
}
}
Are you sure that port # of 1401 is correct? The default port # for MQ is 1414. Start runmqsc against your queue manager. i.e.
runmqsc MY_LOCAL_QM
then issue the following command:
DIS LISTENER(LISTENER.TCP)
what value is given for the PORT attribute?
tmo.setIntProperty(WMQConstants.JMS_IBM_CHARACTER_SET, 1208);
tmo.setIntProperty(WMQConstants.JMS_IBM_ENCODING,546);
Why are you setting the CCSID and Encoding? Why don't you let JMS & MQ take care of it?
Here is a fully functioning JMS program that puts a message to a queue:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import javax.jms.*;
import com.ibm.mq.jms.*;
import com.ibm.msg.client.wmq.WMQConstants;
/**
* Program Name
* MQTestJMS11
*
* Description
* This java JMS class will connect to a remote queue manager and put a message to a queue.
*
* Sample Command Line Parameters
* -m MQA1 -h 127.0.0.1 -p 1414 -c TEST.CHL -q TEST.Q1 -u UserID -x Password
*
* #author Roger Lacroix
*/
public class MQTestJMS11
{
private static final SimpleDateFormat LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private Hashtable<String,String> params;
private MQQueueConnectionFactory mqQCF = null;
/**
* The constructor
*/
public MQTestJMS11()
{
super();
params = new Hashtable<String,String>();
}
/**
* Make sure the required parameters are present.
* #return true/false
*/
private boolean allParamsPresent()
{
boolean b = params.containsKey("-h") && params.containsKey("-p") &&
params.containsKey("-c") && params.containsKey("-m") &&
params.containsKey("-q") &&
params.containsKey("-u") && params.containsKey("-x");
if (b)
{
try
{
Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
b = false;
}
}
return b;
}
/**
* Extract the command-line parameters and initialize the MQ variables.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
if (args.length > 0 && (args.length % 2) == 0)
{
for (int i = 0; i < args.length; i += 2)
{
params.put(args[i], args[i + 1]);
}
}
else
{
throw new IllegalArgumentException();
}
if (allParamsPresent())
{
try
{
mqQCF = new MQQueueConnectionFactory();
mqQCF.setQueueManager((String) params.get("-m"));
mqQCF.setHostName((String) params.get("-h"));
mqQCF.setChannel((String) params.get("-c"));
mqQCF.setTransportType(WMQConstants.WMQ_CM_CLIENT);
try
{
mqQCF.setPort(Integer.parseInt((String) params.get("-p")));
}
catch (NumberFormatException e)
{
mqQCF.setPort(1414);
}
}
catch (JMSException e)
{
if (e != null)
{
MQTestJMS11.logger("getLinkedException()=" + e.getLinkedException());
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
}
throw new IllegalArgumentException();
}
catch (Exception e)
{
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Test the connection to the queue manager.
* #throws MQException
*/
private void testConn()
{
QueueConnection conn = null;
QueueSession session = null;
Queue myQ = null;
try
{
conn = mqQCF.createQueueConnection((String) params.get("-u"), (String) params.get("-x"));
conn.start();
session = conn.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
MQTestJMS11.logger("successfully connected.");
myQ = session.createQueue((String) params.get("-q"));
MQDestination mqd = (MQDestination) myQ;
mqd.setTargetClient(WMQConstants.WMQ_CLIENT_JMS_COMPLIANT);
// mqd.setTargetClient(WMQConstants.WMQ_CLIENT_NONJMS_MQ);
sendMsg( session, myQ);
}
catch (JMSException e)
{
if (e != null)
{
MQTestJMS11.logger("getLinkedException()=" + e.getLinkedException());
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
}
}
catch (Exception e)
{
MQTestJMS11.logger(e.getLocalizedMessage());
e.printStackTrace();
}
finally
{
try
{
if (session != null)
session.close();
}
catch (Exception ex)
{
MQTestJMS11.logger("session.close() : " + ex.getLocalizedMessage());
}
try
{
if (conn != null)
conn.stop();
}
catch (Exception ex)
{
MQTestJMS11.logger("connection.stop() : " + ex.getLocalizedMessage());
}
try
{
if (conn != null)
conn.close();
}
catch (Exception ex)
{
MQTestJMS11.logger("connection.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* Send a message to a queue.
* #throws MQException
*/
private void sendMsg(QueueSession session, Queue myQ) throws JMSException
{
QueueSender sender = null;
try
{
TextMessage msg = session.createTextMessage();
msg.setText("Nice simple test. Time in 'ms' is -> " + System.currentTimeMillis());
// msg.setJMSReplyTo(tq);
// msg.setJMSDeliveryMode( DeliveryMode.NON_PERSISTENT);
MQTestJMS11.logger("Sending request to " + myQ.getQueueName());
MQTestJMS11.logger("");
sender = session.createSender(myQ);
sender.send(msg);
}
finally
{
try
{
if (sender != null)
sender.close();
}
catch (Exception ex)
{
MQTestJMS11.logger("sender.close() : " + ex.getLocalizedMessage());
}
}
}
/**
* A simple logger method
* #param data
*/
public static void logger(String data)
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
// Remove the package info.
if ( (className != null) && (className.lastIndexOf('.') != -1) )
className = className.substring(className.lastIndexOf('.')+1);
System.out.println(LOGGER_TIMESTAMP.format(new Date())+" "+className+": "+Thread.currentThread().getStackTrace()[2].getMethodName()+": "+data);
}
/**
* mainline
* #param args
*/
public static void main(String[] args)
{
MQTestJMS11 write = new MQTestJMS11();
try
{
write.init(args);
write.testConn();
}
catch (IllegalArgumentException e)
{
MQTestJMS11.logger("Usage: java MQTestJMS11 -m QueueManagerName -h host -p port -c channel -q JMS_Queue_Name -u UserID -x Password");
System.exit(1);
}
catch (Exception e)
{
MQTestJMS11.logger(e.getLocalizedMessage());
System.exit(1);
}
System.exit(0);
}
}

Difference between Mysql-Connector- Java vs Spring-Jdbc

As far as I know we use Mysql-connector jar for connecting java application to the database. I am following a spring tutorial and both the above mentioned things have been added via maven. What is the difference between both?
MySQL Connector is a driver that allows Java to talk to MySQL.
Spring JDBC is a library that makes it easier to write JDBC code. JdbcTemplate is particularly useful.
Before JdbcTemplate:
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
int count;
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
rs = statement.executeQuery("select count(*) from foo");
if(rs.next()) {
count = rs.getInt(0);
}
} catch (SQLException exp) {
throw new RuntimeException(exp);
} finally {
if(connection != null) {
try { connection.close(); } catch (SQLException exp) {}
}
if(statement != null) {
try { statement.close(); } catch (SQLException exp) {}
}
if(rs != null) {
try { rs.close(); } catch (SQLException exp) {}
}
}
After JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int count = jdbcTemplate.queryForObject("select count(*) from foo", Integer.class);
See how one way sucks much less?

I get a nullpointerexception when connecting to oracle DataBase

Here is the stack trace:
java.sql.SQLException
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:290)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:702)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:634)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:488)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at com.boeing.DBReader.Server.makeConnection(Server.java:85)
at com.boeing.DBReader.Server.<init>(Server.java:26)
at com.boeing.DBReader.Reader.main(Reader.java:13)
Caused by: java.lang.NullPointerException
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:395)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
... 11 more
Connection closed
And here is the code:
public class Server
{
private DataSource datasource;
public Server()
{
try
{
createConnectionToDatabase();
} catch (Exception e)
{
// TODO Auto-generated catch block
System.out.println("Exception:" + e.toString());
}
makeConnection();
}
private void createConnectionToDatabase() throws Exception
{
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("**");
p.setPassword("**");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
datasource = new DataSource();
datasource.setPoolProperties(p);
}
private void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ignore) {
System.out.println("Could not close connection, WTF?");
}
}
}
private void makeConnection()
{
Connection con = null;
String queryString = "SQL QUERY GOES HERE ";
try {
System.out.println("Connection attempt");
con = datasource.getConnection();
System.out.println("Connection made no issues");
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
e.printStackTrace();
} finally {
closeConnection(con);
System.out.println("Connection closed");
}
}
I have the driver attached to the build path.. What am I doing wrong? This is set up without maven, and just a normal java project.
Thanks!
Not entirely sure from the stack trace, but this looks wrong:
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
You're setting the URL to connectionString, which is null.

How to Connect oracle db with JSP

I am a new for JSP and I dont know any information about connection of oracle with JSP can anyone help me step by step?
You have to look at JDBC for Oracle. Using Java of course, not JSP.
This is a very basic Database class I used to use for very little projects.
public class Database {
private String driverName = "oracle.jdbc.driver.OracleDriver";
private Connection conn;
public static Hashtable errors = null;
public Database(String serverName, String portNumber, String serviceName, String username, String password, String db) {
errors = new Hashtable();
try {
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + serviceName;
Class.forName(driverName);
this.conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println(e);
errors.put(db, e);
}
}
public Connection getConnection(){
return this.conn;
}
}
here is a sample of a query
Database db = new Database(......); // see Database class construct
try {
java.sql.Statement st = db.getConnection().createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM FOO");
while(rs.next()){
// your code
}
rs.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
hope this helps :)

Resources