getConnection Exception javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
null
when i run below code this is the exception i am getting.
I have already created respective jndi name connectionpools in glassfishv3
pl give me any solution....
Thanks..
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Test {
/**
* #param args
*/
private static DataSource ds;
private static Context initialContext = null;
public static Connection getConnection()
{
try
{
initialContext = new InitialContext();
ds = (DataSource) initialContext.lookup("jdbc/__TimerPool");
System.out.println("data source "+ds);
return ds.getConnection();
}
catch (Exception e)
{
System.out.println(("getConnection Exception " + e));
}
return null;
}
public static void main(String[] args) {
System.out.println(Test.getConnection());
}
}
ds = (DataSource) initialContext.lookup("jdbc/__TimerPool");
ds = (DataSource) initialContext.lookup("java:comp/jdbc/__TimerPool");
EDIT: Sorry, "java:comp/env/jdbc/__TimerPool".
Related
I have the following code and I am trying to create a connection to a database.
I get an error "Could not find or load main class onjava" when I run the command: java -cp . onjava
I am able to run the javac -classpath "C:\CATALINA_HOME\lib*" onjava.java command
Both of my .class and .java files are in the same directory WEB-INF\classes\com\onjava
onjava.java
package com.onjava;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;
import javax.naming.Context;
public class onjava extends HttpServlet {
private DataSource datasource;
public void init(ServletConfig config) throws ServletException {
try {
// Look up the JNDI data source only once at init time
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
datasource = (DataSource) ((InitialContext) envCtx).lookup("jdbc/testdb");
}
catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
Connection connection=null;
try {
connection = getConnection();
//..<do JDBC work>..
if (connection != null) {
String message = "You are connected!";
System.out.println(message);
} else {
System.out.println("Failed to make connection!");
}
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
}
}
EDIT:
I changed my code and I added the public class. But I am facing the same error when I run it!
package src;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Wrapper;
import java.util.Hashtable;
import java.util.Properties;
import java.io.*;
import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import oracle.jdbc.pool.OracleDataSource;
public class onjava {
public static void main(String[] argv) throws SQLException, NamingException {
Properties prop = new Properties();
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.naming.java.javaURLContextFactory");
Context initialContext = new InitialContext(prop);
if ( initialContext == null){
System.out.print("JNDI problem. Cannot get InitialContext.");
} else {System.out.print("NO JNDI problemb ");}
// Get DataSource
Context envContext = (Context)initialContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/testdb");
System.out.println("\n -------- Oracle JDBC Connection Testing ------");
try {
Connection jdbcConnection = ((Statement) ds).getConnection();
OracleDataSource ods = ((Wrapper) ds).unwrap(OracleDataSource.class);
jdbcConnection.close();
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
String message = "You are connected!";
System.out.println(message);
}
}
When running java like this, you need to explicitly state the main class. Your command should look something more like java -cp . com.onjava.onjava. However, I don't see the main method in this class either. You need to point to the main method (ie, signature public static void main()).
By the way, it is proper convention to give your classes names that start with a capital letter (Onjava).
Ok so from what you told me, you need to have a main class attached to your project. This means going back to your compiler and creating the main method. To add your code, you will need to do something like this in the main class, which I will call onjavaMain:
public class onjavaMain{
//Main method is this
public static void main(String[] args)
{
//create variable of your onjava class
onjava onJavaConnectToDatabase = new onjava();
onJavaConnectToDatabase.doGet(argument1,argument2);
}
}
Now this is not the complete answer, but this will give you an idea of what you need to do in order to run your project in command line.
i need your help with my code. I have a PoolConnector class with this code:
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
public class PoolConnector
{
private static final String user = "root";
private static final String password = "";
private static final String dbUrl = "jdbc:mysql://localhost/gene_ontology";
private static DataSource ds;
static {
try {
Context context = new InitialContext();
Context envctx = (Context) context.lookup("java:comp/env");
ds = (DataSource) envctx.lookup("jdbc/TestDB");
}
catch (NamingException ex) {
Logger.getLogger(PoolConnector.class.getName()).log(Level.SEVERE, null, ex);
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://localhost/gene_ontology?autoReconnect=true");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("root");
p.setPassword("");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
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");
ds = new DataSource();
ds.setPoolProperties(p);
}
}
public static Connection getConnection()
{
Connection conn = null;
try
{
conn =
DriverManager.getConnection(dbUrl, user, password);
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
return conn;
}
}
public static Connection getConnection(boolean pool)
{
if (pool)
{
Connection conn = null;
try
{
conn = ds.getConnection();
return conn;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
}
else return getConnection();
}
public static boolean closeConnection(Connection conn)
{
try
{
conn.close();
return true;
}
catch (SQLException ex)
{
Logger.getLogger(Connector.class.getName()).log(Level.SEVERE,
"Connection could not be closed", ex);
return false;
}
}
}
I get an error for two packages, it seems that they do not exist
(import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;)
what am I doing wrong?
Thank you in advance.
Do you have tomcat-dbcp.jar at your classpath? Please be sure tomcat lib directory is in your classpath.
I have an JPS Project.
If I have different computers using the system, they use the same MySQL connection.
When the system is running any query and a client tries to make any mysql command, it puts everyone in a queue, the system is very slow.
I want each client has a different connection with mysql.
Sorry if I was not clear enough.
package br.com.scope.model;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import br.com.scope.log.LoggerIntegrador;
public class ConexaoMysql {
private static Connection connection;
private final static ConexaoMysql conexaoMysql = new ConexaoMysql();
private static Properties prop;
private LoggerIntegrador logger;
private ConexaoMysql() {
super();
prop = new Properties();
Class<? extends ConexaoMysql> cls = this.getClass();
InputStream is = cls.getResourceAsStream("db.properties");
try {
prop.load(is);
} catch (IOException e) {
logger = LoggerIntegrador.getInstance();
logger.error(e.getMessage(), e);
}
}
public static ConexaoMysql getConnection() throws SQLException, ClassNotFoundException, IOException {
if (connection == null || connection.isClosed()){
conexaoMysql.abreConexao();
}
return conexaoMysql;
}
public static void beginTransaction() throws SQLException, ClassNotFoundException, IOException {
getConnection();
connection.setAutoCommit(false);
}
public static void commit() throws SQLException {
connection.commit();
connection.setAutoCommit(true);
}
public static String getDriver() {
return prop.getProperty("driver");
}
public static String getConnectionString() {
return prop.getProperty("connectionstring");
}
public static String getUser() {
return prop.getProperty("user");
}
public static String getPassword() {
return prop.getProperty("password");
}
private void abreConexao() throws ClassNotFoundException, SQLException, IOException{
Class.forName(getDriver());
connection = DriverManager.getConnection(
getConnectionString(),
getUser(),
getPassword());
}
public static void fechaConexao() throws SQLException {
if (!connection.isClosed()) {
connection.close();
}
}
public PreparedStatement getPreparedStatement(String sql) throws SQLException {
return connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
public static int getId() {
return conexaoMysql.hashCode();
}
}
What you're looking for is a connection pool. It is a bounded pool of connections that the clients can take a connection from when they need it, and put it back to when done. This saves you from the overhead or creating and destroying connections all the time. It also makes sure the number of connections grows predictably.
Most containers provide a facility like this e.g. here's the documentation for configuring a connection pool in Tomcat. Find the one for your container.
If for some reason you can not use that or do not want the container to be in charge, you can use a library that helps you manage a connection pool yourself, in your application. c3p0 is a popular one with many examples on the web.
EDIT:
Hikari is the new cool choice for connection pooling.
For tests I want to manually bind a datasource to a name. It works with apache SharedPoolDataSource, but if I extend the class, ctx.lookup() returns null.
It has something to do with InstanceKeyObjectFactory.isCorrectClass() returning false.
All I wanted was to log Datasource.getConnection()
package org.foo;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameAlreadyBoundException;
import javax.sql.DataSource;
import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
public class TestFactory {
private static final String JNDINAME = "stubJs";
private static final String JDBCURL = "jdbc:db2://localhost:50000/dbname";
public static void main(String[] args) throws Exception {
String jndiName = JNDINAME;
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(jndiName);
System.out.println(ds);
}
static {
Context ictx;
try {
DriverAdapterCPDS cpds = new DriverAdapterCPDS();
cpds.setDriver("com.ibm.db2.jcc.DB2Driver");
cpds.setUrl(JDBCURL);
cpds.setUser("db2admin");
cpds.setPassword("db2admin");
SharedPoolDataSource tds = new SharedPoolDataSource() {};
//SharedPoolDataSource tds = new SharedPoolDataSource();
tds.setConnectionPoolDataSource(cpds);
tds.setMaxActive(10);
tds.setMaxIdle(10);
tds.setMaxWait(10000);
ictx = new InitialContext();
Context ic = ictx;
String jndiName = JNDINAME;
int i = -1;
while (-1 != (i = jndiName.indexOf('/', i+1))) {
String s2 = jndiName.substring(0, i);
try {
ic.createSubcontext(s2);
} catch (NameAlreadyBoundException e) {
System.err.println(e);
}
}
ictx.bind(jndiName, tds);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
I'm trying to access Oracle datasource from CDI bean.
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
import javax.sql.DataSource;
#Named("ParentIDNameResolveController")
#ViewScoped
public class ParentIDNameResolve implements Serializable
{
// Call the Oracle JDBC Connection driver
#Resource(name = "jdbc/Oracle")
private static DataSource ds;
// Get the ID if the parent
public static int ParentId(int chieldId) throws SQLException
{
int ParentId = 0;
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
try
{
conn = ds.getConnection();
ps = conn.prepareStatement("SELECT COMPONENTID, FKCOMPONENTID, COMPONENTSTATSID from COMPONENT where COMPONENTID = ?");
ps.setLong(1, chieldId);
rs = ps.executeQuery();
while (rs.next())
{
ParentId = rs.getInt("FKCOMPONENTID");
}
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
return ParentId;
}
// Get Parent Name
public static String ParentName(int ParentId) throws SQLException
{
String ParentName = null;
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
try
{
conn = ds.getConnection();
ps = conn.prepareStatement("SELECT COMPONENTSTATSID, NAME from COMPONENTSTATS where COMPONENTSTATSID = ?");
ps.setLong(1, ParentId);
rs = ps.executeQuery();
while (rs.next())
{
ParentName = rs.getString("NAME");
}
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
return ParentName;
}
}
Unfortunately when I reference datasource from static Java method I get this error:
Can't get data source
I'm not sure is it possible to access datasource from static Java method. Is there a way to fix this problem?
It's not sure that your container will inject anything with adnotation #Resource to a static field or a static method. Try to rethink your class and maybe make it as #ApplicationScoped then you will also have only one instance per application.
Here are little changes to your class:
#Named("ParentIDNameResolveController")
#javax.enterprise.context.ApplicationScoped // not from javax.faces.bean
public class ParentIDNameResolve implements Serializable
{
// Call the Oracle JDBC Connection driver
#Resource(name = "jdbc/Oracle")
private DataSource dataSource;
/*
Add getter/setter for DataSource
*/
public DataSource getDataSource() {
return this.ds;
}
public void DataSource setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/* Change method signature to non static */
public int ParentId(int chieldId) throws SQLException
{
DataSource ds = getDataSource();
// your code here
return ParentId;
}
/* Change method signature to non static */
public String ParentName(int ParentId) throws SQLException
{
DataSource ds = getDataSource();
// your code here
return ParentName;
}
}
Next you can use it in your code also as injected object and You can be sure that DataSource wont' be null but if it will be - check is it properly defined as DataSource in configuration files.