issue populating v$session properties in oracle datasource - java

I have a issue populating v$session properties in oracle datasource ie after starting tomcat server my application would be using connection , now if I query DB with below query I should get a row from DB, currently I am not getting any row for 1st approach ,but 2nd approach works
select schemaname, osuser, machine, program
from v$session
where program = 'Test';
below are the configuration and tools I am using , any help regaring this is appriciated .
Thanks
1.Tomcate 6.0.35.3
2.Oracle version :Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
3.Spring and JPA
Approach 1:-
server.xml :
<Resource
name="jdbc/oraclepool"
auth="Container"
factory="oracle.ucp.jdbc.PoolDataSourceImpl"
type="oracle.ucp.jdbc.PoolDataSource"
description="main DB"
connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
connectionPoolName="UCPPool"
url="${db.url}"
user="${db.username}"
password="${db.password.encrypted}"
initialPoolSize="3"
minPoolSize="1"
maxPoolSize="5"
maxIdleTime="${db.maxIdleTime}"
inactiveConnectionTimeout="${db.inactiveConnectionTimeout}"
abandonedConnectionTimeout="${db.abandonedConnectionTimeout}"
timeToLiveConnectionTimeout="${db.timeToLiveConnectionTimeout}"
maxStatements="${db.maxOpenPreparedStatements}"
timeoutCheckInterval="${db.timeoutCheckInterval}"
connectionWaitTimeout="${db.connectionWaitTimeout}"
sqlForValidateConnection="${db.validationQuery}"
connectionProperties="v$session.program=Test;"
/>
Approach 2 :-
Added below code snippet in java class , it worked .
When I queried the db with below query , I was getting the row .
select schemaname, osuser, machine, program
from v$session
where program = 'Test';
Connection conn=null;
// set connection properties
Properties info = new java.util.Properties();
info.put("v$session.program", "Test");
// connect to database
Context context = new InitialContext();
PoolDataSourceImpl ds = (PoolDataSourceImpl)context.lookup("java:comp/env/jdbc/oraclepool");
((PoolDataSourceImpl)ds).setConnectionProperties(info);
conn = ds.getConnection();
Can anybody tell what is the issue with first approach
Thanks again .

Related

How to configure Java Hibernate for Google Cloud SQL?

I am using Hibernate + Java + Jersey + MYSql and it's working fine on local machine. However I am unable to create a connection to MySql on Google Cloud.
I think MYSql configuration and instance creation is fine on Google Cloud, but I am unable to pass all configuration through hibernate properties. See here what Google's sample code:
// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();
// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", "postgres"
config.setPassword(DB_PASS); // e.g. "my-password"
// For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);
config.addDataSourceProperty("useSSL", "false");
// ... Specify additional connection properties here.
// ...
// Initialize the connection pool using the configuration object.
DataSource pool = new HikariDataSource(config);
Now I dont know how to pass cloudSqlInstance and socketFactory in Hibernate. Here what I tried to pass these parameters but it's not working:
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://google/pashumandi_db?cloudSqlInstance=pashuserver:asia-south1:mysql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory
hibernate.connection.username = abc_user
hibernate.connection.password = 12345678
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Could you please let me know what is correct hibernate configuration to connect with MySql on Google Cloud? Thanks.
For Google Cloud you can select your DB instance and then under “CONNECTIONS” you can select to allow connections from Public IP addresses and then add your machine’s IP address to the list of addresses authorizes to make a connection. From there all you need to do is use the public IP address of your DB instance in the URL.
Find the INSTANCE_CONNECTION_NAME for the instance on the Instance details page on Google Cloud Console. It uses the format PROJECT_ID:REGION:INSTANCE_ID, and is used to identify the Cloud SQL instance you are connecting to.
To enable a local TCP port, add the following to your project's app.yaml file:
runtime: java
env: flex
beta_settings:
cloud_sql_instances: <INSTANCE_CONNECTION_NAME>=tcp:<PORT>
Then here is my hibernate.properties file:
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://172.17.0.1:PORT_NUMBER_IN_YAML_FILE
hibernate.connection.username = DB_USERNAME
hibernate.connection.password = DB_PASSWORD
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.default_schema = DATABASE_NAME
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
For more details you can visit: https://cloud.google.com/sql/docs/mysql/connect-app-engine

How to save to Cassandra from java?

I am new to Cassandra and i am working on a project that uses Cassandra as DB. The Cassandra is installed in another device and i will have to save it to the db remotely.
I have little knowledge about Cassandra and its functionality but I'm good with MySQL.
What are the steps to save a message into Cassandra?
Can I use the same database that I used with MySQL?
I believe that I will have to connect to the Cassandra Server and then save it.
Cluster cluster = Cluster.builder().addContactPoint("localhost").withPort(3306).build();
I have used this statement to connect to Cassandra. (replacing localhost to the ip of the device)
Your best bet here is to start with the java driver docs. If you use maven its quite easy to setup, but I often find the examples don't always give a full pom.xml so you can use some of the examples in the github project
The quick start guide gives a very simple example:
Cluster cluster = null;
try {
cluster = Cluster.builder()
.addContactPoint("127.0.0.1")
.build();
Session session = cluster.connect();
ResultSet rs = session.execute("select release_version from system.local");
Row row = rs.one();
System.out.println(row.getString("release_version"));
} finally {
if (cluster != null) cluster.close();
}
Some other items of interest are the connection pooling and load balancing
Create a session with the cluster created and the keyspace:
Session session = cluster.connect("keyspace");
create keyspace if u don't have one.
then use
session.execute(query);
to execute any query of your choice.
query has to be string and not null.
eg:
String query= "INSERT INTO keyspace.table_name (id, lastname, firstname) VALUES (6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47, 'KRUIKSWIJK','Steven');";
session.execute(query);

DB2 StatementPool configuration issue

I'm trying to activate the statementPool with the db2 jdbc driver, and i m having trouble doing so.
I've tried different techniques mentionned here : http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2z10.doc.java%2Fsrc%2Ftpc%2Fimjcc_c0052041.htm
Here is the java code :
csUrl += ":maxStatements=1000;";
System.err.println("Connecting to csUrl : " + csUrl);
DB2ConnectionPoolDataSource ds = new DB2ConnectionPoolDataSource();
//DB2SimpleDataSource ds = new DB2SimpleDataSource();
//ds = new DB2ConnectionPoolDataSource();
ds.setServerName("edited");
ds.setPortNumber(edited);
ds.setDatabaseName("edited");
ds.setCurrentSchema("edited");
ds.setMaxStatements(1000);
ds.setDriverType(4);
Connection connection = ds.getPooledConnection(csUser, csPassword).getConnection();
//Connection connection = ds.getConnection(csUser, csPassword);
//Connection connection = DriverManager.getConnection(csUrl);
//Connection connection = m_driver.connect(csUrl, propertiesUserPassword);
boolean pooling = connection.getMetaData().supportsStatementPooling();
if (pooling) {
System.err.println(">>> Pooling is ON!");
} else {
System.err.println(">>> Pooling is OFF! <<<");
}
All techniques fail according to : connection.getMetaData().supportsStatementPooling() and statementPooling is always deactivated.
I'm running DB2 Express /Linux :
Database server = DB2/LINUXX8664 10.1.2
with the matching jdbc driver.
Same code with a different db2 backend (db2 10 zOs) gives the same result, so i guess it s not an Express issue.
Client code is running on windows.
We have a in-house statement cache, but i wanted to play around with DB2's especially since it can apparently share the pool in between logical connections provided thru a PooledDataSource
Thanks :)

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

How do you configure a DataSource in Java to connect to MS SQL Server?

I'm trying to follow Java's JDBC tutorials to write a Java program that can connect to SQL Server 2008. I'm getting lost at the point of making a connection.
The following snippet is from the tutorial:
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection();
There's no explanation of what comp/env/jdbc/myDB should point to, and I don't know how I should choose a port. Also, the object ds seems to be defined twice.
I'm using the JSQLDataSource driver, for the record. Can anyone point me in the right direction here?
http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html
I'm not sure anyone above has really answered the question.
I found this microsoft sample useful.
The key information in there is really that the class you need is SQLServerDataSource
that is basically a configuration object - you use it something like this:
SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setUser("aUser");
dataSource.setPassword("password");
dataSource.setServerName("hostname");
dataSource.setDatabaseName("db");
You would then call
dataSource.getConnection();
to get a connection object which is basically the thing you use to talk to the database.
Use
connection.prepareStatement("some sql with ? substitutions");
to make something for firing off sql and:
connection.prepareCall
for calling stored procedures.
Start with the JDBC tutorial or the Microsoft docs.
and this:
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
Fill in your values for host, database, username, and password. The default port for SQL server is 1433.
UPDATE: Good point below. JDBC drivers can be had from both Microsoft and jTDS. I prefer the latter.
JNDI lookups have to do with Java EE app servers that support connection pooling. You can ask the app server to create a pool of connections, which can be an expensive thing to do, and loan them out to clients like library books as needed.
If you aren't using a Java EE app server or connection pooling, you have to create the connection on your own. That's where manual processes and DriverManager come in.
EXPLANATION: As for why the Sun tutorial shows DataSource twice, I'd say it's a case of poor editing. If you look above the code sample it says you can get a DataSource "by lookup or manually". The code snippet below shows both together, when it should be one or the other.
You know it's an inadvertent error because there's no way the code as written could compile. You have "ds" declared twice.
So it should read "...lookup", followed by its code snippet, and then "...manually", followed by its code snippet.
I like the jTDS driver for connecting to SQL Server. A URL will look like this:
jdbc:jtds:sqlserver://localhost/Finance;instance=sqlexpress
Check this for jTDS Url Info.
This also has some interesting information to help troubleshoot jtds to sql express sorts of problems.
DataSource ds = new SimpleDriverDataSource(new com.mysql.jdbc.Driver(),
"jdbc:mysql://database:1433;databaseName=name", "username", "password");
JdbcTemplate jdbc = new JdbcTemplate(ds);
This question has already been answered long time ago. The question was asked about JNDI lookup. With lookup you have to see the application server log to see what the connection is bound to. For example in Jboss startup, I can see:
[ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=myDB' to JNDI name 'java:myDB'
Using that name=myDB you lookup
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:myDB");
Notice how the server log and the code both point to the JNDI name java:myDB.

Categories

Resources