javax.naming.NamingException: Cannot create resource instance issue - java

While running this sample code in eclipse (the issue is not related to JSF though) i get the error javax.naming.NamingException: Cannot create resource instance
Java file
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
#SessionScoped
public class CustomerBean implements Serializable{
//resource injection
#Resource(name="jdbc/SSHD")
private DataSource ds;
//if resource inject is not support, you still can get it manually.
public CustomerBean(){
try {
System.out.println("11111111111111");
Context ctx = new InitialContext();
System.out.println("222222222222222222");
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/SSHD");
} catch (NamingException e) {
System.out.println("3333333333333333333");
e.printStackTrace();
}
}
}
webapp/WEB-INF/web.xml
<resource-ref>
<description>SSHD Connection</description>
<res-ref-name>jdbc/SSHD</res-ref-name>
<res-type>oracle.jdbc.pool.OracleDataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
webapp/META-INF/context.xml
<Context>
<Resource name="jdbc/SSHD" auth="Container" type="oracle.jdbc.pool.OracleDataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="ABCD" password="XYZZ" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:#XX.XX.XX.XXXX:1521:SSHD"/>
</Context>
webapp/WEB-INF/lib
classes12.jar
error stack
11111111111111
javax.naming.NamingException: Cannot create resource instance
222222222222222222
3333333333333333333
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:146)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
at org.apache.naming.NamingContext.lookup(NamingContext.java:843)
at org.apache.naming.NamingContext.lookup(NamingContext.java:154)
Please advise

Related

Java Jee getting a Connection pool configured in context.xml

I'm making a webapp using JSP and MYSQL.
I have set up a connection pool and used it in a Servlet, but I cannot access it.
I had to create manually the "lib" folder inside WEB-INF to put the database connector and the META-INF folder to put the context.xml file, because those folders were not there at the begining.
I'm following a tutorial from 2016 so I don't know how different it is now.
Thanks in advance for your help.
Src folder:
Main files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
</web-app>
context.xml
<Context>
<Resource name="jdbc/wishes" auth="Container" type="javax.sql.DataSource" maxActive="15" maxIdle="3" maxWait="5000" username="root" password="" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/jee">
</Resource>
</Context>
Servlet
package com.gabit.dev.makeawish.controllers;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
#WebServlet(name = "ServletDatabase", value = "/ServletDatabase")
public class ServletDatabase extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(name = "jdbc/wishes")
private DataSource myPool;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/plain");
Connection myConnection = null;
Statement myStatement = null;
ResultSet myResult = null;
try {
myConnection = myPool.getConnection();
String query = "SELECT * FROM wishes";
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(query);
while (myResult.next()) {
String title = myResult.getString(2);
output.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error
java.lang.NullPointerException: Cannot invoke "javax.sql.DataSource.getConnection()" because "this.myPool" is null
at com.gabit.dev.makeawish.controllers.ServletDatabase.doGet(ServletDatabase.java:31)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
...
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)

Place ehCache 3 ehcache.xml outside of the Springboot 2 (Spring 5 ) project's jar file

Had spent quite some time figuring out how to externalize ehCache 3 ehcache.xml outside of the jar file of an Spring 5 (Springboot 2.x) project. This is important so that ehcache settings could be tweaked without having to redeploy the project.
Just sharing a solution that worked using Java 8 in case anybody else faces this challenge:
package com.myproject.config;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import javax.cache.Caching;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configures ehCache.
*
* #author
*
*/
#Configuration
#EnableCaching
public class CacheConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfiguration.class);
#Value("${myproject.cache.ehcache.xml.fullpath:/dir/outside/of/project/config/ehcache.xml}")
private String ehcacheXmlFullPath;
#Bean
public CacheManager cacheManager() throws URISyntaxException {
// To get from the classpath: getClass().getResource("/ehcache.xml").toURI()
return new JCacheCacheManager(Caching.getCachingProvider().getCacheManager(Paths.get(ehcacheXmlFullPath).toUri(),
getClass().getClassLoader()));
}
}

Strange error during db connection

Using JUnit to test a class that connects to Database Java print this error:
Error: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
Using the same class in a Main Class i have the same error.
Using the same class in a servlet, testing it from the browser, it works with no problems.
My database class to connect with DB (the error is on "ds.getConnection();"):
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Database {
private static DataSource ds;
static {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
ds = (DataSource) envCtx.lookup("jdbc/mua");
} catch (NamingException e) {
System.out.println("Error:" + e.getMessage());
}
}
public static Connection getConnessione() throws SQLException {
return ds.getConnection();
}
}
This is the context.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Context>
<Resource name="jdbc/mua"
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
type="javax.sql.DataSource"
username="root"
password="admin"
url="jdbc:mysql://localhost:3306/mua?useSSL=false"/>
</Context>

Spring : How to configure tomcat Datasource Programatically in Groovy DAO

I have my tomcat datasource configured in XML as below:
<bean id="docDataSource"
class="org.apache.tomcat.jdbc.pool.DataSource"
destroy-method="close"
p:driverClassName="${doc.database.driver}"
p:url="${doc.database.url}"
p:username="${doc.database.user}"
p:password="${doc.database.password}"
p:validationQuery="select 1"
p:testOnBorrow="true"
p:minIdle="2"
p:maxIdle="4"
p:maxActive="6"
p:defaultTransactionIsolation="1">
</bean>
And my customDAO(groovy class) uses the above datasource as below
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import groovy.sql.Sql
import org.apache.log4j.Level
import javax.sql.DataSource
import java.util.Map
import java.util.Map.Entry
import java.util.ResourceBundle
#Component
public class customDao implements GroovyInterceptable {
#Autowired
private Services services
#Autowired
#Qualifier("docDataSource")
private DataSource dataSource
// implementation
}
I wanna switch my tomcat dataSource to a class file instead of XML. Can someone help me how to do this?
Here's the piece of code you can follow (with PostgreSQL, but it should more or less work the same):
import org.postgresql.ds.PGPoolingDataSource
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import javax.sql.DataSource
#Configuration
class PostgreSQLDatasourceConfiguration {
#Bean(name = 'dataSource')
DataSource ds(#Value('${DATABASE_URL}') String databaseFullUrl) {
assert databaseFullUrl, 'Database URL is required to start the application'
URI uri = new URI(databaseFullUrl)
def (_, dbUsername, dbPassword) = (uri.getUserInfo() =~ /(.*):(.*)/)[0]
(DataSource) new PGPoolingDataSource().tap {
url = "jdbc:postgresql://$uri.host:${uri.port}$uri.path"
password = dbPassword
user = dbUsername
}
}
}

NoInitialContextException Error Tomcat

I've been trying to find a solution here but I cant...
I have the following code and i get this error.
Am I missing something? Thank you :)
Code
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.*;
import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import oracle.jdbc.pool.OracleDataSource;
public class TestServlet {
#SuppressWarnings("unused")
public static void main(String[] argv) throws SQLException, NamingException {
Context initialContext = new InitialContext();
if ( initialContext == null){System.out.println("initialContext null");}
else {System.out.println("initialContext");}
// Get DataSource
Context environmentContext = (Context)initialContext.lookup("java:/comp/env");
if ( environmentContext == null){System.out.println("envContext null.");}
else {System.out.println("envContext");}
DataSource ds = (DataSource)environmentContext.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);
}
}
context.xml
<Context>
<Resource name="jdbc/testdb"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="dba01"
password="qvE-g7Cacontext.xml"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:oracle:thin:#10.0.1.6:1521:xe"/>
</Context>
Error
Exception in thread "main" 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
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at src.TestServlet.main(TestServlet.java:34)
Please let me know if you need more information!
You need an initial context factory. For Tomcat it is org.apache.naming.java.javaURLContextFactory:
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
So is it the code deployed on the server? It seems you try to access the Context using standard java as you call static main (so I guess you are calling TeestServlet.main from your runtime). The context will be setup by the web server (Tomcat), so it is availble only after you deploy your web application to it.
Please note that driverClassName that you are using is incorrect.
It should be "oracle.jdbc.OracleDriver" if you are trying to connect to Oracle Database.
<Context>
<Resource name="jdbc/testdb"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="dba01"
password="qvE-g7Cacontext.xml"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:oracle:thin:#10.0.1.6:1521:xe"/>
</Context>

Categories

Resources