Getting a JDBC database connection without using Servicefactory - java

I'm using the following java code (in ColdFusion) to get a database connection:
//Creating an object of servicefactory class
local.theServiceFactory = createObject('java','coldfusion.server.ServiceFactory');
//Creating the connection object simply by passing the DSN name
local.connect = theServiceFactory.getDataSourceService().getDataSource('dsnnane').getConnection();
Works great. The only problem is I'm told I can't use ServiceFactory because of security reasons. Is there another way to get the connection object?

Instead of dropping lower in the call stack to do this kind of thing, I'd look at ways to set your options directly via the SQL itself. As I posted in my comment, you can set the autocommit values in SQL Server via T-SQL itself.

I use it like this
var datasourceService = createObject("Java", "coldfusion.server.ServiceFactory").getDataSourceService();
var ds = datasourceService.getDatasource(variables.dsn).getConnection().getPhysicalConnection();
ds.setAutoCommit(false);
...
ds.setAutoCommit(true);

Related

Java async driver for MongoDB doesn't work on replica set when "primary" is changed

I have some troubles with the usage of java async driver (3.8.1).
I'll describe my environment:
I have a replica set (rs0) with 3 istances: let me call them A,B,C.
In my application I use Mongo and two different java driver, sync and async.
At the beginning I reached no problems but when the primary went down (and come up after some minutes changing its behavior as secondary) the part of code when I use async driver was not able to use transactions and session.
The error is the following:
com.mongodb.MongoClientException: Sessions are not supported by the MongoDB cluster to which this client is connected
at com.mongodb.async.client.MongoClientImpl$1.onResult(MongoClientImpl.java:90)
at com.mongodb.async.client.MongoClientImpl$1.onResult(MongoClientImpl.java:83)
at com.mongodb.async.client.ClientSessionHelper$2.onResult(ClientSessionHelper.java:77)
at com.mongodb.async.client.ClientSessionHelper$2.onResult(ClientSessionHelper.java:73)
at com.mongodb.internal.connection.BaseCluster$ServerSelectionRequest.onResult(BaseCluster.java:433)
at com.mongodb.internal.connection.BaseCluster.handleServerSelectionRequest(BaseCluster.java:309)
at com.mongodb.internal.connection.BaseCluster.access$800(BaseCluster.java:65)
at com.mongodb.internal.connection.BaseCluster$WaitQueueHandler.run(BaseCluster.java:482)
at java.lang.Thread.run(Unknown Source)
2019-01-21 17:02:01.906 ERROR 17560 --- [271de4498944329] org.mongodb.driver.client : Callback onResult call produced an error
java.lang.NullPointerException: null
at it.mypackage.mongo.service.ProcessoDocumentService$1.onResult(ProcessoDocumentService.java:124)
at it.mypackage.mongo.service.ProcessoDocumentService$1.onResult(ProcessoDocumentService.java:1)
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:49)
at com.mongodb.async.client.MongoClientImpl$1.onResult(MongoClientImpl.java:90)
at com.mongodb.async.client.MongoClientImpl$1.onResult(MongoClientImpl.java:83)
at com.mongodb.async.client.ClientSessionHelper$2.onResult(ClientSessionHelper.java:77)
at com.mongodb.async.client.ClientSessionHelper$2.onResult(ClientSessionHelper.java:73)
at com.mongodb.internal.connection.BaseCluster$ServerSelectionRequest.onResult(BaseCluster.java:433)
at com.mongodb.internal.connection.BaseCluster.handleServerSelectionRequest(BaseCluster.java:309)
at com.mongodb.internal.connection.BaseCluster.access$800(BaseCluster.java:65)
at com.mongodb.internal.connection.BaseCluster$WaitQueueHandler.run(BaseCluster.java:482)
at java.lang.Thread.run(Unknown Source)
Just FYI, if I comment the part of code when I use session and transactions, the error is a classic timeout, as the driver was not longer able to find replica set anymore.
Someone could help me? What I'm missing?
This is how I create my MongoClient:
connectionString = new ConnectionString("mongodb://address1:27017,address2:27018,address3:27019/?replicaSet=rs0");
MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(connectionString)
.build();
settings = settings.builder().credential(credential).build();
asyncMongoClientInstance = MongoClients.create(settings);
I found the solution by myself, as the wise man once said: "If you want an help, find it at the end of your arm".
Let's us focus on this part of code:
connectionString = new connectionString("mongodb://address1:27017,address2:27018,address3:27019/?replicaSet=rs0");
MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(connectionString)
.build();
settings = settings.builder().credential(credential).build();
asyncMongoClientInstance = MongoClients.create(settings);
I'm reallocating the settings object to another object without the connection string.
So, async library doesn't know anymore where to address the connection.
Why I did that? I wanted to dinamically add credentials to the settings. But is not possible in this way. So I created two different settings object, one with credentials and one without.
MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(connectionString).credential(credential).build();
It definitely works with this object now.

Oracle database connection - without using setUrl

I am trying to use a datasource to get connection to Oracle database.
I am setting the OracleConnectionCacheImpl object with properties like driverType, networkProtocol, user, password, databaseName, serverName, portNumber.
setUrl cannot be used.
What should I do to get a connection like in the case, if the following url is used ?
jdbc:oracle:thin:#(DESCRIPTION=(LOAD_BALANCE=on)
(ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521))
(ADDRESS=(PROTOCOL=TCP)(HOST=host2) (PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=service_name)))
I hope I made some sense in what I told.
For RAC, you need to set the URL.
In my experience, if you do not set the URL explicitly, it will not work in this case.
I am unable to comment, hence posting a new reply.

Need to dynamically create a data source for MySQL Connect/J connection pool

I have an application that needs to use connection pool when connection to the database. Problem is, the application is designed to configure and change the connection settings on the fly. I have written the following code that will allow me to dynamically create the data source and then use that to open the connections to the database. However, this code was written for the DataDirect driver and I have used it to connect to Oracle and MS SQL. Unfortunately, the DataDirect Mysql driver will only connect to the commercial version of mysql, not the free version. So now I am attempting to accomplish the same task with connect/j from mysql. I cannot find how to set the connection properties found in a external (static) datasource definition via method calls like for the DD driver. Any help would be appreciated.
BaseDataSource bds = (BaseDataSource)ds;
// Populate the DataSource
bds.setDescription("Driver Data Source");
bds.setServerName(connectUrl);
bds.setUser(userName);
bds.setPassword(password);
if ( spyAttr.length() > 0 ) bds.setSpyAttributes(spyAttr);
// Create the PooledConnection DataSource. Pass the data source created above
// to the PooledConnection DataSource
pds = new PooledConnectionDataSource();
pds.setDescription("Pooled Data Source");
pds.setDataSourceName("myDataSource", bds);
pds.setPoolName("myPool");
pds.setInitialPoolSize(nPoolSize);
pds.setMinPoolSize(minPoolSize);
pds.setMaxPoolSize(maxPoolSize);
pds.setPropertyCycle(propCycle);
pds.setMaxIdleTime(maxIdleTime);
pds.setTracing(tracing);
// Get connection
pds.getConnection();
Apparently the MySQL Connector/J driver doesn't allow those parameters to be passed in with method calls so you will have to pass them in as parameters in the URL (jdbc:mysql://localhost/test?user=foo&password=bar).

Call to DataSource.getConnection not returning the expected connection

I have the following code:
Hashtable env1 = new Hashtable();
env1.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
log.info("Executed step 1");
env1.put(javax.naming.Context.PROVIDER_URL, "iiop://myhost.com:9301");
log.info("Executed step 2");
Context ctx = new InitialContext(env1);
DataSource ds = (DataSource)ctx.lookup("jdbc/mydatasource");
log.info("Excecuted lookup ="+ds);
conn = ds.getConnection();
I have the previous code in an standalone application that is connecting to WAS 6.1.0.3 in order to retrieve a connection from the datasource. The code is very straighforward, and I have seen the same code working in a different environment, but in this case when I call getConnection I get an exception. The datasource is WAS has the proper authentication alias set and when the connection is tested it works OK from the WAS side, but the previous code won't work.
If I change this line: conn = ds.getConnection();
to this: conn = ds.getConnection("username","password");
Then the code will work! But that's not what I want since the connections in the datasource should already have the credentials set. I was initially thinking this was a Sybase problem, but it's also happening with Oracle, so would rather say I have a problem with WAS.
If you are curious about the exceptions, for Sybase I get:
java.sql.SQLException: JZ004: User name property missing in DriverManager.getConnection(..., Properties).DSRA0010E: SQL State = JZ004, Error Code = 0
at com.sybase.jdbc2.jdbc.ErrorMessage.raiseError(ErrorMessage.java:569)
at com.sybase.jdbc2.tds.LoginToken.<init>(LoginToken.java:128)
at com.sybase.jdbc2.tds.Tds.doLogin(Tds.java:506)
at com.sybase.jdbc2.tds.Tds.login(Tds.java:449)
at com.sybase.jdbc2.jdbc.SybConnection.tryLogin(SybConnection.java:254)
at com.sybase.jdbc2.jdbc.SybConnection.regularConnect(SybConnection.java:230)
at com.sybase.jdbc2.jdbc.SybConnection.<init>(SybConnection.java:200)
at com.sybase.jdbc2.jdbc.SybPooledConnection.<init>(SybPooledConnection.java:72)
at com.sybase.jdbc2.jdbc.SybConnectionPoolDataSource.createConnection(SybConnectionPoolDataSource.java:138)
at com.sybase.jdbc2.jdbc.SybDriver.connect(SybDriver.java:485)
at com.sybase.jdbc2.jdbc.SybDriver.connect(SybDriver.java:517)
at com.sybase.jdbc2.jdbc.SybDataSource.getConnection(SybDataSource.java:227)
at com.sybase.jdbc2.jdbc.SybConnectionPoolDataSource.getPooledConnection(SybConnectionPoolDataSource.java:74)
at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper$1.run(InternalGenericDataStoreHelper.java:897)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper.getPooledConnection(InternalGenericDataStoreHelper.java:892)
at com.ibm.ws.rsadapter.spi.WSRdbDataSource.getPooledConnection(WSRdbDataSource.java:1181)
at com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl.createManagedConnection(WSManagedConnectionFactoryImpl.java:1047)
at com.ibm.ws.rsadapter.spi.WSDefaultConnectionManagerImpl.allocateConnection(WSDefaultConnectionManagerImpl.java:81)
at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:431)
at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:400)
And for Oracle I get this one:
java.sql.SQLException: invalid arguments in callDSRA0010E: SQL State = null, Error Code = 17,433
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:420)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:297)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:221)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:157)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:94)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:75)
at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper$1.run(InternalGenericDataStoreHelper.java:897)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper.getPooledConnection(InternalGenericDataStoreHelper.java:892)
at com.ibm.ws.rsadapter.spi.WSRdbDataSource.getPooledConnection(WSRdbDataSource.java:1181)
at com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl.createManagedConnection(WSManagedConnectionFactoryImpl.java:1047)
at com.ibm.ws.rsadapter.spi.WSDefaultConnectionManagerImpl.allocateConnection(WSDefaultConnectionManagerImpl.java:81)
at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:431)
at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:400)
In both cases I won't the exception if I pass the credentials to the getConnection method
Thanks for your advice.
Short answer: external clients don't get to use the authentication alias data
Longer Answer:
From the WAS J2C connection factory documentation:
The alias that you configure for component-managed authentication does not apply to all clients that must access the secured resource. External Java clients with Java Naming and Directory Interface (JNDI) access can look up a Java 2 Connector (J2C) resource such as a data source or Java Message Service (JMS) queue. However, they are not permitted to take advantage of the component-managed authentication alias defined on the resource. This alias is the default value that is used when the getConnection() method does not specify any authentication data, like user and password, or a value for ConnectionSpec. If an external client needs to get a connection, it must assume responsibility for the authentication by passing it through arguments on the getConnection() call.
It's been a long time since I've done anything with WebSFEAR^H^H^H^Hphere, but it looks to me that you have a configuration problem. There was a special screen where you'd create credentials (user/pass) and later you'd apply those credentials to the created data source. It looks like that your configured data source hasn't got credentials applied.
Even after defining the user/password values as custom properties I found that the connections for Oracle weren't working. After many days, I just found that the development server is running an old WAS 6.1 version, the problem I'm having was fixed in WAS 6.1.0.5: PK32838: J2CA0046E WHEN USING USING CUSTOM PROP PASSWORD ON DATASOURECE
I tried my code in a different WAS server with an updated WAS fix pack level and... it worked without introducing a single change in the code or in the configuration. So the solution is to upgrade the WAS server.
Thanks.

How do I make my Java application identify itself to Oracle on connection?

When my application connects to an Oracle database I want to be able to see by looking at the active sessions in the database that it is connected. Currently it identifies itself as "JDBC Thin Client" because that's the driver that I'm using, but other Java based applications that I have are somehow able to set this value to something more meaningful, like "SQL Developer". I thought it was a property of the Connection or the OracleDataSource, but I've not managed to find one that does the trick. Is this possible? In case it matters, I'm using Java 1.5, with Oracle 10g and the 10g thin driver.
java.util.Properties props = new java.util.Properties();
props.setProperty("password","mypassword");
props.setProperty("user","myusername");
props.put("v$session.osuser", System.getProperty("user.name").toString());
props.put("v$session.machine", InetAddress.getLocalHost().getCanonicalHostName());
props.put("v$session.program", "My Program Name");
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
Connection conn=
DriverManager.getConnection("jdbc:oracle:thin:#myhostname:1521:mysid", props);
SQL>select username,osuser,program,machine
from v$session
where username = 'ROB';
USERNAME OSUSER PROGRAM MACHINE
--------- ----------- ------------------ -----------
ROB rmerkw My Program Name machine
At application level you can use the following methods to set client_info, module and action in v$session:
dbms_application_info.set_client_info
dbms_application_info.set_module
dbms_application_info.set_action
There is also an Oracle function:
dbms_application_info.set_client_info('Client Info');
which sets the ClientInfo column in v$session.
This might be useful if you only have access to the Connection rather than the underlying DataSource or DriverManager.
Since oracle jdbc 12.1 you can set some client-info values via jdbc api, i.e. you can do
connection.setClientInfo("OCSID.CLIENTID", "MyClientId");
for properties OCSID...
ACTION, CLIENTID, ECID, MODULE, SEQUENCE_NUMBER and DBOP
See https://docs.oracle.com/database/121/JJDBC/jdbcvers.htm#JJDBC29006
Setting PROGRAM doesn't work this way, you can do that as described in the accepted answer or somewhat easier by setting the System property "oracle.jdbc.v$session.program".
You need to define the connection property v$session.program in your data source, in such a way that that property will be added to each connection. How you do that depends on your data source implementation. The value you set the property to will appear in oracle's active session table.
Starting with 12.1 the setEndToEndMetrics is deprecated, you may use setClientInfo
see the documentation for 12.2 here
Here a snippet of the usage
// "conn" is an instance of java.sql.Connection:
conn.setClientInfo("OCSID.CLIENTID", "clientID");
conn.setClientInfo("OCSID.MODULE", "myModule");
conn.setClientInfo("OCSID.ACTION", "myAction");
You may see the setting in V$SESSION with this query of the relevant session
select MODULE, ACTION, CLIENT_IDENTIFIER from v$session where ...
but only after a next statement is executed with this connection. The call of setClientInfo triggers no extra roundtrip this information is passed whit the next call.
Note also that you must use the Oracle (unwrapped) conenction - Check this for reference.

Categories

Resources