How to use oracle proxy connection with JPA repository - oracle

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");

Related

Glassfish RAR5035:Unexpected Exception While Destroying Resource From Pool

I have a Java EE web application. I am connecting database with JDBC and I am using JDBC connection pool. My application's main page is login page. After I enter the login page and wait for a while, I take this glassfish server(4.1.0) warning consistently.
Warning: RAR5035:Unexpected exception while destroying resource from
pool OraclePool. Exception message: Error while destroying resource
:IO Error: Socket read timed out
Even if I don't do any action on the page. When I monitore the statistics of the connection pool, NumConnCreated is increasing continuously. How can I solve the problem?. Thank you.
This is my managed bean class.
#ManagedBean
#SessionScoped
public class Login implements Serializable{
private String userName;
private String password;
private User user;
private #EJB DBRemote db;
public void test(){
String[] params1 = {"user","1234"};
int[] getParams = {Types.INTEGER,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
CallableStatement statement = db.run("TBL.USERLOGIN(?,?,?,?,?,?)", params1 , getParams);
try {
int isLogin = statement.getInt(3);
if (isLogin==1) {
String uName = statement.getString(4);
String uId = statement.getString(5);
user = new User(uId, uName, isLogin);
System.out.println("LOGGED IN " + uName + "\t" + uId);
}else{
String errMessage = statement.getString(6);
user = new User(errMessage,isLogin);
System.out.println("LOG IN FAILURE " + errMessage);
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}finally{
db.close();
FacesContext.getCurrentInstance().addMessage("infoback", new FacesMessage(FacesMessage.SEVERITY_INFO,
"TEST","Test Works"));
}
}
}
This my interface class
#Remote
public interface DBRemote {
CallableStatement run(String query, String[] setParams, int[] getParams);
void close();
String getErrorMessage();
String getSql();
}
This is my Stateless Bean class
#Stateless
public class DB implements DBRemote{
#Resource(mappedName = "pwresource")
private DataSource ds;
private String sql;
private String errorMessage;
private CallableStatement statement;
private Connection connection;
public DB() {
}
#Override
public CallableStatement run(String query, String[] setParams, int[] getParams){
sql = "{call " + query + "}";
int getParamIndex = setParams.length + 1;
try {
connection = ds.getConnection();
statement = connection.prepareCall(sql);
for (int i = 0; i < setParams.length; i++) {
statement.setString(i+1, setParams[i]);
}
for (int getParam : getParams) {
statement.registerOutParameter(getParamIndex, getParam);
getParamIndex++;
}
statement.execute();
}catch (SQLException ex) {
if (ex.getErrorCode()==17008) {
errorMessage = "Timeout";
}else{
errorMessage = "System Error";
}
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
close();
}
return statement;
}
#Override
public void close(){
try {
if (statement != null) {
statement.close();
}
if(connection != null){
connection.close();
}
errorMessage = null;
} catch (SQLException e) {
errorMessage = "Close Connection Error";
}
}
#Override
public String getErrorMessage() {
return errorMessage;
}
#Override
public String getSql() {
return sql;
}
}
I have solved my problem. My problem is because of the connection between connection pool and database. Database closes the connections automically because of the server and database in different networks caused timeout issue.

Cannot close Oracle connection from WebSphere datasource

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.

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 :)

How to show Oracle DB Tables on my JDeveloper Swing projects frame?

I want to show my Oracle DB tables on my application. I create a new database connection DBConnection1. But I don't bind DBConnection1 in my class. How to do it?
OK. I solve my question.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection connection = DriverManager.getConnection(connStr,"scott","tiger");
Connector conn = new Connector(connStr);
Statement stmt = conn.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(sql);
ResultSetMetaData metaData = rset.getMetaData();
int rowCount = metaData.getColumnCount();
for(i=1;i<=rowCount;i++)
headers.add(metaData.getColumnLabel(i).toString());
while(rset.next()){
Vector tmp = new Vector();
for(i=1;i<=rowCount;i++) {
tmp.add(rset.getString(i));
}
lists.add(tmp);
index++;
Here is the my connector class.
package client;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connector
{
private String connection_string;
private Statement stmt;
private Connection connection;
public Connector(String conn)
{
//String connection_string = "jdbc:oracle:thin:#<host>:<port>:<db name>";
try
{
connection_string = conn;
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection(conn,"scott","tiger");
} catch(Exception f)
{
f.printStackTrace();
}
}
public ResultSet execute(String sql)
{
try
{
stmt = connection.createStatement();
return stmt.executeQuery(sql);
} catch (Exception f)
{
f.printStackTrace();
}
return null;
}
public void setConnection_string(String connection_string)
{
this.connection_string = connection_string;
}
public String getConnection_string()
{
return connection_string;
}
public void setStmt(Statement stmt)
{
this.stmt = stmt;
}
public Statement getStmt()
{
return stmt;
}
public void setConnection(Connection connection)
{
this.connection = connection;
}
public Connection getConnection()
{
return connection;
}
}

Resources