Call ojdbc in JUnit - java

Using this post I want to create JUnit test with datasource. I tested this code:
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.junit.BeforeClass;
public class NewEmptyJUnitTest
{
public NewEmptyJUnitTest()
{
}
#BeforeClass
public static void setUpClass() throws Exception
{
// rcarver - setup the jndi context and the datasource
try
{
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES,
"org.apache.naming");
InitialContext ic = new InitialContext();
ic.createSubcontext("java:");
ic.createSubcontext("java:/comp");
ic.createSubcontext("java:/comp/env");
ic.createSubcontext("java:/comp/env/jdbc");
// Construct DataSource
OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
ds.setURL("jdbc:oracle:thin:#host:port:db");
ds.setUser("MY_USER_NAME");
ds.setPassword("MY_USER_PASSWORD");
ic.bind("java:/comp/env/jdbc/nameofmyjdbcresource", ds);
}
catch (NamingException ex)
{
Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void inittest() throws NamingException
{
Context initContext = new InitialContext();
Context webContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) webContext.lookup("jdbc/nameofmyjdbcresource");
}
}
But Netbeans cannot find this class 'OracleConnectionPoolDataSource'. How I can solve this problem?
What is the package that I have to import in order to use this class?

As per ojdbc14.jar, OracleConnectionPoolDataSource can be found in oracle.jdbc.pool:
import oracle.jdbc.pool.OracleConnectionPoolDataSource;

Related

JMS template to publish and subscribe to Oracle AQ

I am trying to connect to Oracle AQ using JMS template to publish and subscribe.
However, I am unable to get it working. I might be lacking basic understanding of connecting to Oracle AQ in general. Any advice would be appreciated
Following is my code
import java.sql.SQLException;
import javax.jms.QueueConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jms.AQjmsFactory;
#EnableJms
public class DataSourceConfig {
#Value("${spring.datasource.username}")
String username;
#Value("${spring.datasource.password}")
String password;
#Value("${spring.datasource.url}")
String url;
#Bean
private OracleDataSource dataSource() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setURL(url);
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean
public QueueConnectionFactory connectionFactory() throws Exception {
return AQjmsFactory.getQueueConnectionFactory(dataSource());
}
#Bean
public JmsTemplate jmsTemplate() throws Exception {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(connectionFactory());
return jmsTemplate;
}
}
Driver class
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.core.JmsTemplate;
#SpringBootApplication
public class AQProcessorApplication implements CommandLineRunner {
#Autowired
#Qualifier("jmsTemplate")
JmsTemplate template;
public static void main(String[] args) {
SpringApplication.run(AQProcessorApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
template.convertAndSend("QUEUE_NAME", "test");
System.out.println("------------- MESSAGE SENT--------------------------");
}
I get MESSAGE SENT in console but I do not see anything in Oracle DB

Jboss 7 multiple threads on client side

I have an swing application that connects to a Jboss 7 AS.
Invoking some background threads causes a no such ejb error on client side.
Here is an example
package com.asf.capone.client.util;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.asf.capone.common.exception.AppException;
import ro.asf.capone.ejb.beans.security.SecurityController;
import ro.asf.capone.ejb.beans.security.SecurityControllerRemote;
public class TestJndi {
public static void main(final String[] args) throws AppException {
final Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
env.put("java.naming.provider.url", "remote://localhost:4447");
env.put("java.naming.security.credentials", "c4ca4238a0b923820dcc509a6f75849b");
env.put("java.naming.security.principal", "capone");
env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
env.put("jboss.naming.client.ejb.context", "true");
env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
try {
final InitialContext ctx = new InitialContext(env);
System.out.println("ctx: " + ctx);
final SecurityController o = (SecurityControllerRemote) ctx.lookup(
"ejb:agency-ear/agency-ejb/SecurityControllerBean!ro.asf.capone.ejb.beans.security.SecurityControllerRemote");
System.out.println("1outcome: " + o.getServerTimeMillis());
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("2outcome: " + o.getServerTimeMillis());
}
}).start();
} catch (final NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output for this is:
ctx: javax.naming.InitialContext#307f6b8c
1outcome: 1443465336127
Exception in thread "Thread-4" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:agency-ear, moduleName:agency-ejb, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#381dfddb
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:754)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:186)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy2.getServerTimeMillis(Unknown Source)
at com.asf.capone.client.util.TestJndi$1.run(TestJndi.java:36)
at java.lang.Thread.run(Thread.java:745)
I am missing something that should allow me to get the same output on both calls but I cannot figure what is the problem. Thanks!
It looks like this doesn't work on that version of Jboss (they've changed the remote) because my initial code worked in Jboss 7.3.0. My current Jboss version is JBoss EAP 6.4.0.GA (AS 7.5.0.Final-redhat-21)
The code that works now is:
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.ejb.client.ContextSelector;
import org.jboss.ejb.client.EJBClientConfiguration;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.ejb.client.PropertiesBasedEJBClientConfiguration;
import org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector;
import ro.asf.capone.ejb.beans.security.SecurityControllerRemote;
public class AppJboss {
public static void main(String[] args) throws NamingException {
System.out.println("Hello World!");
final String lookup = "ejb:agency-ear/agency-ejb//SecurityControllerBean!ro.asf.capone.ejb.beans.security.SecurityControllerRemote";
final Properties clientProperties = new Properties();
clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS",
"JBOSS-LOCAL-USER");
clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT",
"false");
clientProperties.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
clientProperties.put("remote.connections", "default");
clientProperties.put("endpoint.name", "client-endpoint");
clientProperties.put("remote.connection.default.port", "4447");
clientProperties.put("remote.connection.default.host", "127.0.0.1");
clientProperties.put("remote.connection.default.username", "capone");
clientProperties.put("remote.connection.default.password", "c4ca4238a0b923820dcc509a6f75849b");
clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS",
"false");
final EJBClientConfiguration ejbClientConfiguration = new PropertiesBasedEJBClientConfiguration(
clientProperties);
final ContextSelector<EJBClientContext> contextSelector = new ConfigBasedEJBClientContextSelector(
ejbClientConfiguration);
EJBClientContext.setSelector(contextSelector);
final Properties properties = new Properties();
properties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(properties);
final SecurityControllerRemote myBean = (SecurityControllerRemote) context.lookup(lookup);
final long result = myBean.getServerTimeMillis();
System.out.println("result " + result);
new Thread(new Runnable() {
public void run() {
final long result = myBean.getServerTimeMillis();
System.out.println(result);
}
}).start();
}
}
The client library was taken from jboss/bin/client/jboss-client.jar
The same code works in Wildfly also, just with the change of port and client library. Hope this helps others.

Addition of web service access in servlet unrecognized/unresolved; seen as "type".

I am trying to create a simple servlet (tomcat) that accesses a database, then a USDA web service. I've successfully deployed/tested the database connectivity. When I added the web service access, eclipse reports the problem: AwdbWebService_Service cannot be resolved to a type.
The hour is late... I just don't see why this won't resolve as a service instance.
The error is tripped by this line:
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
Here is the code:
package localdomain.localhost;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL; //added for usda webservice
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.namespace.QName; // added for usda webservice
import usda.nrcs.wcc.awdbWebService.*;
#WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
// use this for usda reservoir station values later
static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
protected final Logger logger = Logger.getLogger(getClass().getName());
#Resource(name = "jdbc/mydb", lookup = "jdbc/mydb")
private DataSource dataSource;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Init");
System.out.println(getClass().getName() + ".init");
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<head><title>MyServlet</title></head>");
writer.println("<body><h1>MyServlet</h1>");
writer.println("<h2>DataSource</h2>");
Connection conn = null;
try {
writer.println("Datasource: " + dataSource + "<br/><br/>");
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select 1");
while (rst.next()) {
writer.println("Resultset result: " + rst.getString(1) + "<br/><br/>");
}
rst.close();
stmt.close();
conn.close();
writer.println("SUCCESS to access the datasource");
// Now try accessing usda
URL wsURL = new URL("http://www.wcc.nrcs.usda.gov/awdbWebService/services?wsdl");
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
m_webService = lookup.getAwdbWebServiceImplPort();
} catch (Exception e) {
e.printStackTrace(writer);
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.println("</body></html>");
}
}
For those following this thread:
The package statement at the start of the java classes I generated with wsimport begins with:
package gov.usda.nrcs.wcc.awdbWebService
My import statement however looked like this:
import usda.nrcs.wcc.awdbWebService.*;
In essence I placed the source # the wrong level and defined the build config to point incorrectly for the package references in the java classes. I removed the build reference, moved the tree to begin pointing on the gov level. Now that there wasn't a mismatch, the unresolved type error vanished.

javax.naming.Reference cannot be cast to javax.sql.DataSource Error

I am using Apache Derby and have the following code:
DBConnectionFactory.java
package edu.unsw.comp9321.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import edu.unsw.comp9321.common.DataSourceException;
import edu.unsw.comp9321.common.ServiceLocatorException;
// This class looks up the database via JNDI and returns a connection to the DAO Implementation class
public class DBConnectionFactory {
static Logger logger = Logger.getLogger(DBConnectionFactory.class.getName());
private static DBConnectionFactory factory = null;
private DataSource ds = null;
private InitialContext ctx;
private Context subctx;
private DBConnectionFactory() throws ServiceLocatorException{
try{
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/cs9321");
logger.info("Database found:"+ds.toString());
}catch(NamingException e){
logger.severe("Cannot find context, throwing exception"+e.getMessage());
e.printStackTrace();
throw new ServiceLocatorException();
}
}
public DataSource getDataSource(){
return ds;
}
public static Connection getConnection() throws ServiceLocatorException, SQLException{
if(factory==null)
factory = new DBConnectionFactory();
Connection conn = factory.getDataSource().getConnection();
return conn;
}
}
The error seems to occur here:
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/cs9321");
I read that this may occur if derbyclient.jar is not in the build path. However, I have already added this jar to the build path.
Would anyone have any suggestions as to what I can do?
Thanks.
You're missing a couple of jars, add this two and everything should be ok:
commons-dbcp-1.4.jar
commons-pool-1.6.jar
Hope that helps!
Cheers

Correct JNDI #Resource(name)

I have the following class for obtaining a JDBC connection:
package util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class OracleConnection implements AutoCloseable{
private final String oracle_DS_CTX = "java:jboss/oracleDS";
// #Resource(name="java:jboss/oracleDS")
// private DataSource ds; //doesn't work
private Connection _conn;
public OracleConnection() throws SQLException, NamingException{
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(oracle_DS_CTX);
_conn = ds.getConnection();
}
#Override
public void close() throws Exception {
if(_conn != null){
_conn.close();
}
}
public Connection getConnection() throws SQLException {
return _conn;
}
}
I have a problem using the #Resource annotation. Datasource obtained via InitialContext works without any problems but I am not sure what string should I put into resource name (commented out in my code).
I have tried:
#Resource(name="java:jboss/oracleDS")
#Resource(name="oracleDS")
AS is JBOSS AS7
What name did you define in your standalone.xml?
That is the name you need to define in your #Resource
But there's a little trick, you need to set it in the lookup property instead of name.
Here's an example, let's assume my DS jndi is java:jboss/ExampleDS.
#Resource(lookup = "java:jboss/ExampleDS")
private DataSource dataSource;

Categories