Connecting to a SQL Server 2000 db from Java - jdbc

I am receiving an error that I did see on your site, but as a novice java coder I think that I flubbed my implementation of the solution.
I am getting a message
"SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3"
I am using Eclipse Mars 1
The database is a sql server 2000, so I downloaded sqljdbc.jar from the Microsoft site as suggested by an earlier question. I loaded it to c:\temp and added that to the CLASSPATH and rebooted.
code snippet reads:
package texasLAMPConversion;
import java.sql.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TexasLAMPConversion {
public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "jdbc:sqlserver://serverName\\instanceName";
String uName = "*********";
String uPass = "*********";
Connection conn = null;
try {
conn = DriverManager.getConnection(host, uName,uPass);
if (conn != null) { System.out.println("Connected to the database");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage() );
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
FileWriter fw= null;
File file =null;
try {
file=new File("C:/temp/generated_stmts_update_t_customer_master.sql");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
}catch (IOException e) {
e.printStackTrace();
}
String oldKey = "8000001234", newKey = "8";
int lenAcct = 10;
oldKey = ReformatOldAcct(lenAcct, oldKey );
newKey = leftZeroAcct(lenAcct, newKey);
System.out.println("oldkey = " + oldKey + " and newKey = " + newKey);
}
private static String ReformatOldAcct(int lenAcct, String oldKey) {
// TODO Auto-generated method stub
String reformatedAcct = "";
reformatedAcct = "0" + oldKey.substring(2, lenAcct);
return (reformatedAcct);
}
private static String leftZeroAcct(int lenAcct, String acctNo) {
// TODO Auto-generated method stub
int index =0;
int currentLengthAcct;
String leadingZero = "";
currentLengthAcct = acctNo.length();
while (index < (lenAcct -currentLengthAcct) ) {
leadingZero = '0' + leadingZero;
index ++;
}
return (leadingZero + acctNo);
}
}
and it is throwing this complete message
Apr 19, 2016 11:29:44 AM com.microsoft.sqlserver.jdbc.SQLServerConnection Prelogin
WARNING: ConnectionID:1 ClientConnectionId: 602d619d-c033-41d0-9109-80f56e3ab9b3 Server major version:8 is not supported by this driver.
Apr 19, 2016 11:29:44 AM com.microsoft.sqlserver.jdbc.SQLServerConnection Prelogin
WARNING: ConnectionID:1 ClientConnectionId: 602d619d-c033-41d0-9109-80f56e3ab9b3 Server major version:8 is not supported by this driver.
com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2226) at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2226)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2210)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2210)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.Prelogin(SQLServerConnection.java:2095)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.Prelogin(SQLServerConnection.java:2095)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1799)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1799)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1285)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1285)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1131)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1131)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at texasLAMPConversion.TexasLAMPConversion.main(TexasLAMPConversion.java:20)
at texasLAMPConversion.TexasLAMPConversion.main(TexasLAMPConversion.java:20)
SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3
SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3
Any thoughts for a novice java programmer moving away from PowerBuilder?

Related

Apache Drill JDBC connectivity through java code is giving error:Failure in connecting to Drill: oadd.org.apache.drill.exec.rpc.RpcException

i am trying drill-jdbc connectivity through java code.
Error is:-
java.sql.SQLException: Failure in connecting to Drill: oadd.org.apache.drill.exec.rpc.RpcException: CONNECTION : java.net.ConnectException: Connection refused: no further information: localhost/127.0.0.1:31010
So the steps followed are below:-
wget http://www-eu.apache.org/dist/drill/drill-1.12.0/apache-drill-1.12.0.tar.gz
tar -xvf apache-drill-1.12.0.tar.gz
cd apache-drill-1.12.0
cd bin
./drillbit.sh start -Ddrill.exec.http.port=8765
To check check its running under zookeeeper
cd /usr/hdp/current/zookeeper-client
./zkCli.sh
ls /drill
In apache-drill-1.12.0/bin
started drill-localhost # ./drill-localhost
received contents "OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=512M; support was removed in 8.0 apache drill 1.12.0"
normal database queries were working properly
is there any dependancy between jdk -version?
Java Code:-
import java.sql.*;
public class DrillJDBCExample {
static final String JDBC_DRIVER = "org.apache.drill.jdbc.Driver";
static final String DB_URL = "jdbc:drill:drillbit=localhost:";//"jdbc:drill:zk=localhost:2181";
//"jdbc:drill:drillbit=localhost";
static final String USER = "admin";
static final String PASS = "admin";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
/* Class.forName("org.apache.drill.jdbc.Driver");
Connection connection =DriverManager.getConnection("jdbc:drill:drillbit=127.0.0.1:8765");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * from cp.`employee`");
while(rs.next()){
System.out.println(rs.getString(1));
}
}*/
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
// Perform a select on data in the classpath storage plugin.
String sql = "select employee_id,first_name,last_name from cp.`employee.json`";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("employee_id");
String first = rs.getString("first_name");
String last = rs.getString("last_name");
System.out.print("ID: " + id);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
try{
if(stmt!=null)
stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
}
}
Error Logs:-
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
java.sql.SQLException: Failure in connecting to Drill: oadd.org.apache.drill.exec.rpc.RpcException: HANDSHAKE_COMMUNICATION : Channel closed /127.0.0.1:60181 <--> localhost/127.0.0.1:8765.
at org.apache.drill.jdbc.impl.DrillConnectionImpl.<init>(DrillConnectionImpl.java:162)
at org.apache.drill.jdbc.impl.DrillJdbc41Factory.newDrillConnection(DrillJdbc41Factory.java:64)
at org.apache.drill.jdbc.impl.DrillFactory.newConnection(DrillFactory.java:69)
at oadd.net.hydromatic.avatica.UnregisteredDriver.connect(UnregisteredDriver.java:126)
at org.apache.drill.jdbc.Driver.connect(Driver.java:72)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.mapr.drill.DrillJDBCExample.main(DrillJDBCExample.java:29)
Caused by: oadd.org.apache.drill.exec.rpc.RpcException: HANDSHAKE_COMMUNICATION : Channel closed /127.0.0.1:60181 <--> localhost/127.0.0.1:8765.
at oadd.org.apache.drill.exec.client.DrillClient$FutureHandler.connectionFailed(DrillClient.java:675)
at oadd.org.apache.drill.exec.rpc.user.QueryResultHandler$ChannelClosedHandler.connectionFailed(QueryResultHandler.java:389)
at oadd.org.apache.drill.exec.rpc.BasicClient$ConnectionMultiListener$HandshakeSendHandler.failed(BasicClient.java:254)
at oadd.org.apache.drill.exec.rpc.RequestIdMap$RpcListener.setException(RequestIdMap.java:134)
at oadd.org.apache.drill.exec.rpc.RequestIdMap$SetExceptionProcedure.apply(RequestIdMap.java:74)
at oadd.org.apache.drill.exec.rpc.RequestIdMap$SetExceptionProcedure.apply(RequestIdMap.java:64)
at oadd.com.carrotsearch.hppc.IntObjectHashMap.forEach(IntObjectHashMap.java:692)
at oadd.org.apache.drill.exec.rpc.RequestIdMap.channelClosed(RequestIdMap.java:58)
at oadd.org.apache.drill.exec.rpc.RemoteConnection.channelClosed(RemoteConnection.java:175)
at oadd.org.apache.drill.exec.rpc.RpcBus$ChannelClosedHandler.operationComplete(RpcBus.java:167)
at oadd.org.apache.drill.exec.rpc.RpcBus$ChannelClosedHandler.operationComplete(RpcBus.java:146)
at oadd.io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:680)
at oadd.io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:567)
at oadd.io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:406)
at oadd.io.netty.channel.DefaultChannelPromise.trySuccess(DefaultChannelPromise.java:82)
at oadd.io.netty.channel.AbstractChannel$CloseFuture.setClosed(AbstractChannel.java:943)
at oadd.io.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:592)
at oadd.io.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:584)
at oadd.io.netty.channel.DefaultChannelPipeline$HeadContext.close(DefaultChannelPipeline.java:1099)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:615)
at oadd.io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:600)
at oadd.io.netty.channel.ChannelOutboundHandlerAdapter.close(ChannelOutboundHandlerAdapter.java:71)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:615)
at oadd.io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:600)
at oadd.io.netty.channel.ChannelDuplexHandler.close(ChannelDuplexHandler.java:73)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:615)
at oadd.io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:600)
at oadd.io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:466)
at oadd.org.apache.drill.exec.rpc.RpcExceptionHandler.exceptionCaught(RpcExceptionHandler.java:39)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:275)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:253)
at oadd.io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:131)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:275)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:253)
at oadd.io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:131)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:275)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:253)
at oadd.io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:131)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:275)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:253)
at oadd.io.netty.channel.ChannelHandlerAdapter.exceptionCaught(ChannelHandlerAdapter.java:79)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:275)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:253)
at oadd.io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:131)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:275)
at oadd.io.netty.channel.AbstractChannelHandlerContext.notifyHandlerException(AbstractChannelHandlerContext.java:809)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:341)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:324)
at oadd.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:242)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:339)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:324)
at oadd.io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86)
at oadd.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:339)
at oadd.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:324)
at oadd.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:847)
at oadd.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
at oadd.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
at oadd.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
at oadd.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
at oadd.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
at oadd.io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
at java.lang.Thread.run(Unknown Source)
Caused by: oadd.org.apache.drill.exec.rpc.ChannelClosedException: Channel closed /127.0.0.1:60181 <--> localhost/127.0.0.1:8765.
at oadd.org.apache.drill.exec.rpc.RpcBus$ChannelClosedHandler.operationComplete(RpcBus.java:166)
... 52 more
Followed documents are:-
1) https://drill.apache.org/docs/
2) https://community.hortonworks.com/articles/10551/apache-drill-unofficial-introduction.html

Oracle DB - Application Continuity - How to test it?

How to Test/POC application continuity concept. I tried making the code to hold connections so that the application is not able get the connections and it tries to get from the pool. I am sure this is not the right way of testing application continuity, but I don't know how to create a proper scenario.
Is it the only way to bring down db while a transaction is in progress ?
I used the below code to simulate AC where a procedure is called 20 times in 20 threads with a new connection everytime. I am creating a scenario where one thread goes and waits for a connection, times-out as not getting connection in time, and then retires to get a connection, IS This a proper AC test. (Below is test class)
package com.ac;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.ucp.jdbc.PoolDataSourceFactory;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.ValidConnection;
import java.sql.ResultSet;
public class App {
public static void main(String[] args) {
try {
new App().acSimulation();
} catch (Exception e) {
e.printStackTrace();
}
}
public void acSimulation() throws Exception{
final PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();
pds.setConnectionFactoryClassName("oracle.jdbc.replay.OracleDataSourceImpl");
System.out.println("connection factory set");
String URL = "jdbc:oracle:thin:#(DESCRIPTION = (TRANSPORT_CONNECT_TIMEOUT=3) (RETRY_COUNT=20)(FAILOVER=ON) " +
" (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = " +
" (SERVER = DEDICATED) (SERVICE_NAME=orcl)))";
System.out.println("Using URL\n" + URL);
pds.setURL(URL);
pds.setUser("system");
pds.setPassword("oracle");
pds.setInitialPoolSize(1);
pds.setMinPoolSize(1);
pds.setMaxPoolSize(3);
pds.setConnectionWaitTimeout(10);
// RAC Features
pds.setConnectionPoolName("Application Continuity Pool");
pds.setFastConnectionFailoverEnabled(true);
// use srvctl config nodeapps to get the ONS ports on the cluster
// pds.setONSConfiguration("nodes=192.168.100.30:6200,192.168.100.32:6200");
System.out.println("pool configured, trying to get a connection");
// final Connection conn = null;
final Connection conn = pds.getConnection();
if (conn == null || !((ValidConnection) conn).isValid()) {
System.out.println("connection is not valid");
throw new Exception ("invalid connection obtained from the pool");
}
if ( conn instanceof oracle.jdbc.replay.ReplayableConnection ) {
System.out.println("got a replay data source");
} else {
System.out.println("this is not a replay data source. Why not?");
}
System.out.println("got a connection! Getting some stats if possible");
oracle.ucp.jdbc.JDBCConnectionPoolStatistics stats = pds.getStatistics();
System.out.println("\tgetAvailableConnectionsCount() " + stats.getAvailableConnectionsCount());
System.out.println("\tgetBorrowedConnectionsCount() " + stats.getBorrowedConnectionsCount() );
System.out.println("\tgetRemainingPoolCapacityCount() " + stats.getRemainingPoolCapacityCount());
System.out.println("\tgetTotalConnectionsCount() " + stats.getTotalConnectionsCount());
System.out.println(((oracle.ucp.jdbc.oracle.OracleJDBCConnectionPoolStatistics)pds.getStatistics()).getFCFProcessingInfo());
System.out.println("Now working");
int i=0;
while(i < 20){
new Runnable() {
public void run() {
try {
seperateInstance(conn, pds);
} catch (SQLException e) {
e.printStackTrace();
}
}
}.run();
i++;
}
}
private void seperateInstance(Connection conn, PoolDataSource pds) throws SQLException{
java.sql.CallableStatement cstmt = null;
oracle.ucp.jdbc.JDBCConnectionPoolStatistics stats = pds.getStatistics();
conn = pds.getConnection();
cstmt = conn.prepareCall("{call P_M_emp(?,?)}");
cstmt.setLong(1, 1);
cstmt.setString(2, "TEST");
cstmt.execute();
System.out.println("Statement executed. Now closing down");
System.out.println("Almost done! Getting some more stats if possible");
stats = pds.getStatistics();
System.out.println("\tgetAvailableConnectionsCount() " + stats.getAvailableConnectionsCount());
System.out.println("\tgetBorrowedConnectionsCount() " + stats.getBorrowedConnectionsCount() );
System.out.println("\tgetRemainingPoolCapacityCount() " + stats.getRemainingPoolCapacityCount());
System.out.println("\tgetTotalConnectionsCount() " + stats.getTotalConnectionsCount());
System.out.println(((oracle.ucp.jdbc.oracle.OracleJDBCConnectionPoolStatistics)pds.getStatistics()).getFCFProcessingInfo());
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing connection "+ conn);
cstmt.close();
conn.close();
conn = null;
}
}
I got the code from below site and modified a bit to add threads and simulate AC. But I am unable to get a replayable datasource.
https://martincarstenbach.wordpress.com/2013/12/13/playing-with-application-continuity-in-rac-12c/
To test Application Continuity you can kill the sessions on the server by doing ALTER SYSTEM KILL SESSION 'sid,serial#' which will simulate a failure.

Connection acquired from ComboPooledDataSource occasionally already checked-out

I'm finding that when multiple threads request a connection each from a single, shared instance of a ComboPooledDataSource, there is the occasion of if returning a connection from the pool that's already in-use. Is there a configuration setting or other means to make sure that connections currently checked-out aren't checked-out again?
package stress;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
public class StressTestDriver
{
private static final String _host = "";
private static final String _port = "3306";
private static final String _database = "";
private static final String _user = "";
private static final String _pass = "";
public static void main(String[] args)
{
new StressTestDriver();
}
StressTestDriver()
{
ComboPooledDataSource cpds = new ComboPooledDataSource();
try
{
cpds.setDriverClass( "com.mysql.jdbc.Driver" );
String connectionString = "jdbc:mysql://" + _host + ":" + _port + "/"
+ _database;
cpds.setJdbcUrl( connectionString );
cpds.setMaxPoolSize( 15 );
cpds.setMaxIdleTime( 100 );
cpds.setAcquireRetryAttempts( 1 );
cpds.setNumHelperThreads( 3 );
cpds.setUser( _user );
cpds.setPassword( _pass );
}
catch( PropertyVetoException e )
{
e.printStackTrace();
return;
}
write("BEGIN");
try
{
for(int i=0; i<100000; ++i)
doConnection( cpds );
}
catch( Exception ex )
{
ex.printStackTrace();
}
finally
{
try
{
DataSources.destroy( cpds );
}
catch( SQLException e )
{
e.printStackTrace();
}
}
write("END");
}
void doConnection( final ComboPooledDataSource cpds )
{
Thread[] threads = new Thread[ 10 ];
final Set<String> set = new HashSet<String>(threads.length);
Runnable runnable = new Runnable()
{
public void run()
{
Connection conn = null;
try
{
conn = cpds.getConnection();
synchronized(set)
{
String toString = conn.toString();
if( set.contains( toString ) )
write("In-use connection: " + toString);
else
set.add( toString );
}
conn.close();
}
catch( Exception e )
{
e.printStackTrace();
return;
}
}
};
for(int i=0; i<threads.length; ++i)
{
threads[i] = new Thread( runnable );
threads[i].start();
}
for(int i=0; i<threads.length; ++i)
{
try
{
threads[i].join();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
private static void write(String msg)
{
String threadName = Thread.currentThread().getName();
System.err.println(threadName + ": " + msg);
}
}
I've run you stress test in my environment. It terminated without output.
That said, it strikes me as a bit unreliable to use toString() output as a token for identity. The hashcodes encoded in Object.toString() are not guaranteed unique, and you're generating lots. You might just be seeing collisions.
In particular, the scenario you are concerned about would represent a surprising and perplexing sort of bug. You should be seeing instances of com.mchange.v2.c3p0.impl.NewProxyConnection. Those instances are not checked in and out of the pool — they are single use, disposable proxies that wrap the underlying database Connection. They are constructed with new when you call getConnection(), remain associated with a PooledConnection object while you work, then dereferenced by the c3p0 library when you call close(), to be garbage collected after client code dereferences them. If somehow getConnection() was being called on the same underlying PooledConnection, that would be a c3p0 bug, and c3p0 would emit a warning to that effect. You are not seeing anything like...
c3p0 -- Uh oh... getConnection() was called on a PooledConnection when
it had already provided a client with a Connection that has not yet
been closed. This probably indicates a bug in the connection pool!!!
are you?
I'd verify that you are not just seeing collisions of NewProxyConnection.toString(). Use a map rather than a set, hold a reference to close()ed Connection instances as values, when you see a collision of String keys, check with == whether the new Connection is the same instance as the value in your map. I'd be astonished if you find that they are the same instance. (I wish I could reproduce the problem to verify this on my own.)
I added code to get the connection ID/##SPID for Oracle and MS SQL Server, and whenever the toString value was the same, the connection ID always differed, so c3p0 is not the culprit:
94843 - pool-1-thread-12 - : onCheckOut called with: com.microsoft.sqlserver.jdbc.SQLServerConnection#5e65d9 - H: 6186457 - P: : 57
94843 - pool-1-thread-13 - : onCheckOut called with: com.microsoft.sqlserver.jdbc.SQLServerConnection#170a25e - H: 24158814 - P: : 55
94843 - pool-1-thread-1 - : onCheckOut called with: com.microsoft.sqlserver.jdbc.SQLServerConnection#5e65d9 - H: 6186457 - P: : 54
19172 - pool-1-thread-11 - : onCheckOut called with: oracle.jdbc.driver.T4CConnection#2475ca - H: 2389450 - P: : 6564
19172 - pool-1-thread-31 - : onCheckOut called with: oracle.jdbc.driver.T4CConnection#2475ca - H: 2389450 - P: : 6448
I'll have to look into revising the existing code. Thanks for your help Steve! You've pointed me in the right direction.

java.net.UnknownHostException thrown from commons-httpclient-3.1.jar

I need to use commons-httpclient-3.1.jar library even it is now end of life.
I am trying to do a simple http GET from url http://www.apache.org/ via proxy server address "10.100.1.44" with proxy port "8080" which requires no credential whatsoever.
Below is my sample code.
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// setting proxy
client.getParams().setAuthenticationPreemptive(true);
client.getState().setProxyCredentials(
new AuthScope("10.100.1.44", 8080),
new UsernamePasswordCredentials("", ""));
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary
// data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
However when I run the code I get exception thrown which is
14 ส.ค. 2556 13:11:28 org.apache.commons.httpclient.HttpMethodDirector authenticateHost
WARNING: Required credentials not available for BASIC <any realm>#www.apache.org:80
14 ส.ค. 2556 13:11:28 org.apache.commons.httpclient.HttpMethodDirector authenticateHost
WARNING: Preemptive authentication requested but no default credentials available
Fatal transport error: www.apache.org
java.net.UnknownHostException: www.apache.org
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80)
at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at jenkins.plugin.assembla.api.HttpClientTutorial.main(HttpClientTutorial.java:38)
Could someone tell me what I did wrong as I am new to this HttpClient library however I need to use it as I have no intention to use HttpComponents library?
Now I have found a solution to this problem. Please refer to the code below.
import java.io.IOException;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// setting proxy
client.getHostConfiguration().setProxy("10.100.1.44", 8080);
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary
// data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
There is a similar problem here with the answer.
I think it is the same case as yours:
Using HttpProxy to connect to a host with preemtive authentication

ERROR - oracle.jdbc.pool.OracleDataSource

I'm trying to develop an adf mobile app using jDeveloper and oracle sql developer.
I have connected jDev and sql. I want to populate selectOneChoice comp. that I m gonna fetch datas.
this is my connection method;
package salesorder.application;
import groovy.sql.Sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import oracle.adf.share.jndi.InitialContextFactoryImpl;
import oracle.adfmf.framework.api.AdfmfJavaUtilities;
import oracle.jbo.server.InitialContextImpl;
import oracle.jdbc.connector.OracleConnectionManager;
import oracle.jdbc.pool.OracleDataSource;
public class DBConnection {
public DBConnection() {
super();
}
private static String jdbcUrl = "jdbc:oracle:thin:#10.172.105.37:1521:VIS";
private static String userid = "***";
private static String password = "***";
protected static Connection conn = null;
public static Connection getConnection()throws Exception{
if (conn == null) {
try {
OracleDataSource ds; ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn=ds.getConnection(userid,password);
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
}
return conn;
}
}
and this, my method to fetch data;
private void Execute() {
Trace.log(Utility.ApplicationLogger, Level.INFO, Customers.class, "Execute",
"!!!!!!!!!!!!!!!!!In COUNTRY Execute!!!!!!!!!!!!!!!!!!!!!!!!!");
try{
Connection conn = DBConnection.getConnection();
customers.clear();
conn.setAutoCommit(false);
PreparedStatement stat= conn.prepareStatement("select cust_account_id,account_name from hz_cust_accounts_all where account_name is not null order by account_name asc");
// fetching customers name
ResultSet rs = stat.executeQuery();
Trace.log(Utility.ApplicationLogger, Level.INFO, Customers.class, "Execute",
"!!!!!!!!!!!!!!!!!Query Executed!!!!!!!!!!!!!!!!!!!!!!!!!");
while(rs.next()){
int id = rs.getInt("CUST_ACCOUNT_ID"); // customer id
String name = rs.getString("ACCOUNT_NAME"); // customer name
Customer c = new Customer(id,name);
customers.add(c);
}
rs.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
when i try to start application, an error comes up like that.
i cant use an image. so
Error
oracle.jdbc.pool.OracleDataSource
I dont know how Im gonna solve that, i cannot figure out why . Any help ?
Just to clarify - are you trying to use ADF Mobile (AMX pages)?
If so then you can't connect with JDBC to a remote database from the client.
You can only connect with JDBC to the local SQLite DB on your device.
To access data from remote servers you'll need to expose this data with web services and call those.

Resources