Test Datasource jndi with java - java

I'm testing a method who inside has a dynamic datasource setup, the problem is when I'm trying to test it give me a nullpointer exception on the method context.lookup(name); but it works when I normally run.
The method I'm trying to test is:
public List<String> searchQuery(String key) {
List<String> resultList = null;
try {
this.createConnection(CheckDataServlet.getKey(Integer.parseInt(key)).getConnection().getName());
stmt = conn.prepareStatement(CheckDataServlet.getKey(Integer.parseInt(key)).getSelect().trim());
rs = stmt.executeQuery();
resultList = this.getValues(rs);
} catch ( SQLException e) {
Archicon.getLogger().error("AwpSapNewRepository error: "+e);
}finally {
closing connection...
}
if (resultList == null) {
resultList = new ArrayList<>();
}
return resultList;
}
public void createConnection(String key){
try {
ds = (DataSource) Archicon.getResource("jdbc/"+key);
conn = ds.getConnection();
} catch (SQLException | NamingException e) {
throw new RuntimeException(e);
}
}
public static synchronized Object getResource(String name) throws NamingException {
return context == null || name == null ? null : context.lookup(name);
}
The resource are in xml file inside WebINF (the project is built with WildFly):
<resource-ref>
<res-ref-name>jdbc/source</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<mapped-name>java:/source</mapped-name>
There is any way to get the result and set up all the enviroment for the test, I even had to use: Archicon.setConfigPath("C:\\Program Files\\wildfly-18.0.0.Final\\standalone\\configuration\\archicon"); because in the test I coudn't get the file

Related

Hi, How can i do operation of others dao with one transaction?

I have dao which methods should be within one transaction What is the best way to do it correctly?
Car dao has following method
public Car findCar(int numOfPas,String carCategory){
String query = "SELECT*FROM car_info WHERE numOfPas = ? AND carCategory=? AND carState='ready' ORDER BY RAND() LIMIT 1;";
Car foundCar = null;
ResultSet resultSet = null;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement statement = connection.prepareStatement(query)){
statement.setInt(1,numOfPas);
statement.setString(2,carCategory);
resultSet =statement.executeQuery();
if(resultSet.next()){
foundCar = new Car();
foundCar.setCarId(resultSet.getInt("carId"));
foundCar.setCarCategory(resultSet.getString("carCategory"));
foundCar.setNumOfPas(resultSet.getInt("numOfPas"));
foundCar.setCarState(resultSet.getString("carState"));
foundCar.setCarName(resultSet.getString("carName"));
foundCar.setCarImage(manager.byteToImage(resultSet.getBytes("carImage")));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return foundCar;
}
And Order Dao has following
#Override
public boolean insertOrder(Order order) {
int rowNum = 0;
String query = "INSERT INTO user_order(userId,carId,userAddress,userDestination,orderCost,orderDate) values(?,?,?,?,?,?)";
ResultSet keys = null;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement statement = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS)){
statement.setInt(1,order.getUserId());
statement.setInt(2,order.getCarId());
statement.setString(3, order.getUserAddress());
statement.setString(4, order.getUserDestination());
statement.setDouble(5,order.getOrderCost());
statement.setTimestamp(6, Timestamp.valueOf(order.getOrderDate()));
rowNum = statement.executeUpdate();
keys = statement.getGeneratedKeys();
if(keys.next()){
order.setOrderId(keys.getInt(1));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return rowNum>0;
}
How can I put these action in one transaction? I receive connection by Apache dhcp connection pool.
Edited
This is class
where I get connection
public class MySQLDAOFactory extends DAOFactory {
public static Connection getConnection(){
Connection conn = null;
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/UsersDB");
conn = ds.getConnection();
} catch (NamingException | SQLException e) {
e.printStackTrace();
}
return conn;
}
#Override
public CarDao getCarDao() {
return new MySQLCarDao();
}
#Override
public UserDao getUserDao() {
return new MySQLUserDao();
}
#Override
public OrderDao getOrderDao() {
return new MySQLOrderDao();
}
#Override
public CarCategoryDao getCarCategoryDao() {
return new MySQLCarCategoryDao();
}
}
There are a lot of different ways to manage transactions. Given your code, the simplest way would be to:
in a try block:
Create your connection in the caller that wraps both calls
Execute connection.setAutoCommit(false)
Call each of the methods findCar() and insertOrder()
Call connection.commit();
in the catch block:
call connection.rollback()
The connection is not created outside those functions, so don't forget to remove the connection setup from each function.

Failed to Start Derby Database

So I'm quite new to Java and Derby. I'm using both with my Flex app on Tomcat 7.
When I make a call to Java from Flex the login function works fine but my getUserByUsername function does not.
public Boolean loginUser(String username, String password) throws Exception
{
Connection c = null;
String hashedPassword = new String();
try
{
c = ConnectionHelper.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT password FROM users WHERE username=?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
hashedPassword = rs.getString("password");
}
else
{
return false;
}
if(Password.check(password, hashedPassword))
{
return true;
}
else
{
return false;
}
}
catch (SQLException e)
{
e.printStackTrace();throw new DAOException(e);
}
finally
{
ConnectionHelper.closeConnection(c);
}
}
public User getUserByUsername(String username) throws DAOException
{
//System.out.println("Executing DAO.getUserByName:" + username);
User user = new User();
Connection c = null;
try
{
c = ConnectionHelper.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT * FROM users WHERE username = ?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTeam(rs.getString("team"));
user.setScore(rs.getInt("score"));
}
}
catch (SQLException e)
{
e.printStackTrace();
throw new DAOException(e);
}
finally
{
ConnectionHelper.closeConnection(c);
}
return user;
}
The stack I get in Flex is useless as far as I can tell:
Flex Message (flex.messaging.messages.ErrorMessage) clientId = 8EB6D37B-7E0B-01B0->AA55-457722B9036C correlationId = A39E574F-CFC6-51FE-6CBE-451AF329E2F8 destination >= service messageId = 8EB6DF4C-650B-BDD7-7802-B813A61C8DC8 timestamp = >1401318734645 timeToLive = 0 body = null code = Server.Processing message = >services.DAOException : java.sql.SQLException: Failed to start database >'/Applications/blazeds/tomcat/webapps/testdrive/WEB-INF/database/game_db', see the next >exception for details. details = null rootCause = ASObject(23393258)>>{message=java.sql.SQLException: Failed to start database >'/Applications/blazeds/tomcat/webapps/testdrive/WEB-INF/database/game_db', see the next >exception for details., suppressed=[], localizedMessage=java.sql.SQLException: Failed to >start database '/Applications/blazeds/tomcat/webapps/testdrive/WEB->INF/database/game_db', see the next exception for details., cause=java.sql.SQLException} >body = null extendedData = null
My first thought was that it was just an error in my function (maybe someone else will notice it) but I've been looking through it for a couple hours and I can't see anything.
After that I thought maybe Derby had a problem with concurrent connections. I saw somewhere that Embedded JDBC can only handle one connection so I changed the driver from Embedded to Client which once again resulted in the login function working and the other an error saying the url in the connection was null. Any thoughts? Thanks ahead of time for any ideas.
EDIT:
package services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.net.URLDecoder;
public class ConnectionHelper
{
private String url;
private static ConnectionHelper instance;
public String getUrl()
{
return url;
}
private ConnectionHelper()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String str = URLDecoder.decode(getClass().getClassLoader().getResource("services").toString(),"UTF-8");
str= str.substring(0, str.indexOf("classes/services"));
if ( str.startsWith("file:/C:",0)){
str=str.substring(6);
}
else{
str=str.substring(5);
}
url = "jdbc:derby:" + str + "database/game_db";
System.out.println("Database url "+url);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static ConnectionHelper getInstance()
{
if (instance == null)
instance = new ConnectionHelper();
return instance;
}
public static Connection getConnection() throws java.sql.SQLException
{
return DriverManager.getConnection(getInstance().getUrl());
}
public static void closeConnection(Connection c)
{
try
{
if (c != null)
{
c.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
There is NO problem with multiple connections in embedded mode. Full stop.
That said, what you may have come across, is that only one jvm process can access the Derby database files at a time. But that jvm may well have 1000s of threads each with their own connection to Derby (resources permitting, of course).

Null Pointer Exception in my code

Hello am developing a web-app using mvc architecture am trying to insert data from form to database through service layer but it throwing a null pointer exception:
Below is my Servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Affiliate af= new Affiliate();
af.setFisrtName(request.getParameter("txtFname"));
af.setLastName(request.getParameter("txtLname"));
af.setGender(request.getParameter("txtGender"));
af.setCategory(request.getParameter("txtCategory"));
String dob=(request.getParameter("txtDob"));
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date;
try {
date = (Date)formatter.parse(dob);
af.setDate(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
af.setAge(Integer.parseInt(request.getParameter("txtAge")));
af.setAddress(request.getParameter("txtAddr"));
af.setCountry("India");
af.setState(request.getParameter("txtState"));
af.setCity(request.getParameter("txtCity"));
af.setPinCode(Integer.parseInt(request.getParameter("txtPin")));
af.setEmailId(request.getParameter("txtEmail"));
af.setStd(Integer.parseInt(request.getParameter("txtStd")));
af.setContactNo(Integer.parseInt(request.getParameter("txtPhone")));
af.setMobileNo(Long.parseLong(request.getParameter("txtMobile"),10));
AffiliateService afs=new AffiliateService();
**afs.createAffiliate(af);**
}
}
and my service code is:
public class AffiliateService {
Affiliate affiliate=null;
public Affiliate createAffiliate( Affiliate affiliate) {
**validateAffiliate(affiliate);**
return affiliate;
}
private Affiliate validateAffiliate(Affiliate affiliate) {
this.affiliate=affiliate;
if(affiliate!=null){
AffiliateDAO afd=new AffiliateDAO();
**afd.insertAffiliate(affiliate);**
}
return affiliate;
}
}
and my DAO code is as below:
public class AffiliateDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Affiliate> addAffiliate(){
ArrayList<Affiliate> affiliates = new ArrayList<Affiliate>();
return affiliates;
}
public void updateAffiliate(Affiliate affiliate){
}
public void delteAffiliate(Affiliate affiliate){
}
public void selectAffiliate(Affiliate affiliate){
}
public void insertAffiliate(Affiliate affiliate){
String sql="INSERT INTO REGISTER " +"(id,FisrtName,LastName,Gender,Category,DateOfBirth,Age,Address,Country,State,City,PinCode,EmailId,Std,ContactNo,MobileNo)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Connection conn = null;
try {
**conn = dataSource.createConnection();**
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, affiliate.getId());
ps.setString(2, affiliate.getFisrtName());
ps.setString(3, affiliate.getLastName());
ps.setString(4,affiliate.getGender());
ps.setString(5, affiliate.getCategory());
ps.setDate(6, (Date) affiliate.getDate());
ps.setInt(7, affiliate.getAge());
ps.setString(8, affiliate.getAddress());
ps.setString(9,affiliate.getCountry());
ps.setString(10,affiliate.getState());
ps.setString(11, affiliate.getCity());
ps.setInt(12, affiliate.getPinCode());
ps.setString(13, affiliate.getEmailId());
ps.setInt(14,affiliate.getStd());
ps.setInt(15, affiliate.getContactNo());
ps.setLong(16, affiliate.getMobileNo());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public Affiliate searchById(int id){
String sql = "SELECT * FROM REGISTER WHERE id = ?";
Connection conn = null;
try {
conn = dataSource.createConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
Affiliate affiliate = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
rs.getInt("id");
rs.getString("FisrtName");
rs.getString("LastName");
rs.getString("Gender");
rs.getString("Category");
rs.getDate("DateOfBirth");
rs.getString("Age");
rs.getString("Address");
rs.getString("Country");
rs.getString("State");
rs.getString("City");
rs.getInt("PinCode");
rs.getString("EmailId");
rs.getInt("Std+ContactNo");
rs.getString("MobileNo");
}
rs.close();
ps.close();
return affiliate;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
and this is my dataSource class:
public class DataSource {
Connection connection=null;
BasicDataSource bdsource=new BasicDataSource();
public DataSource(){
bdsource.setUrl("dbUrl");
bdsource.setUsername("dbuserName");
bdsource.setPassword("dbPassword");
bdsource.setDriverClassName("com.mysql.jdbc.Driver");
}
public Connection createConnection(){
Connection con=null;
try{
if(connection !=null){
System.out.println("Can't create a new connection");
}
else{
con=bdsource.getConnection();
}
}
catch(Exception e){
e.printStackTrace();
}
return con;
}
}
and my stack trace is as below:
java.lang.NullPointerException
com.affiliate.DAO.AffiliateDAO.insertAffiliate(AffiliateDAO.java:43)
com.affiliate.service.AffiliateService.validateAffiliate(AffiliateService.java:21)
com.affiliate.service.AffiliateService.createAffiliate(AffiliateService.java:12)
com.affiliate.servlet.AffiliateServlet.doPost(AffiliateServlet.java:71)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
com.affiliate.servlet.RegisterServlet.doPost(RegisterServlet.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
All the bolded lines in the codes are correspoding to the stack trace.
Please help me fix this..I doubt my validate method...
Looks like dataSource is null because setDataSource is never called.
You need to modify you validateAffiliate(Affiliate affiliate) method of the AffiliateService class. You have never initialized the Data Source which is causing NPE to occur.
Check this:
private Affiliate validateAffiliate(Affiliate affiliate) {
this.affiliate=affiliate;
if(affiliate!=null){
AffiliateDAO afd=new AffiliateDAO();
// This was causing NPE. Data source must be set before using it.
afd.setDataSource(passDataSourceInstance);
afd.insertAffiliate(affiliate);
}
Initialize dataSource before call to conn = dataSource.createConnection();
can be in AffiliateDAO constructor.

javax.sql.datasource getconnection returns null

Can someone please show me how to fix the code below so that it does not throw an error?
The following line of code is giving me a null pointer exception:
return dataSource.getConnection();
Note that dataSource is an instance of javax.sql.DataSource which is specified in web.xml, and which works fine when called by other code.
Here is the actual method in DataAccessObject.java where the null pointer is occurring:
protected static Connection getConnection(){
try {
return dataSource.getConnection(); //
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The preceding method is being called by this line of code:
connection = getConnection();
Which is located in the following method in a class called CourseSummaryDAO as follows:
public List<CourseSummary> findAll(Long sid) {
LinkedList<CourseSummary> coursesummaries = new LinkedList<CourseSummary>();
ResultSet rs = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = getConnection(); //
String sql = "select * from coursetotals where spid=?";
statement = connection.prepareStatement(sql);
statement.setLong(1, sid);
rs = statement.executeQuery();
//for every row, call read method to extract column
//values and place them in a coursesummary instance
while (rs.next()) {
CourseSummary coursesummary = read("findAll", rs);
coursesummaries.add(coursesummary);
}
return coursesummaries;
}catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
close(rs, statement, connection);
}
}
To recreate this simply, I created the following TestCourseSummaries class:
public class TestCourseSummaries {
public static void main(String[] args) {
Long id = new Long(1002);
CourseSummaryDAO myCSDAO = new CourseSummaryDAO();
List<CourseSummary> coursesummaries = myCSDAO.findAll(id);
for(int i = 0;i<coursesummaries.size();i++){
System.out.println("type, numunits are: "+coursesummaries.get(i).getCourseType()+","+coursesummaries.get(i).getNumUnits());
}
}
}
EDIT:
To address JustDanyul's question, I am enclosing the code that calls in my application, and the underlying DataAccessObject code which is extended by the two DAO objects in the calling code:
Here is the code in my application which triggers the error. See there are two classes that each extended DataAccessObject. Perhaps they are conflicting with each other, causing the second one not to get the database connection?
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String idString = req.getParameter("id");
Long id = new Long(idString);
ThisObj thisobj = new ThisDAO().find(id);
req.setAttribute("thisobj", thisobj);
ThoseObjDAO myThoseDAO = new ThoseObjDAO();
List<ThoseObj> thoseobjects = myThoseObjDAO.findAll(id);
req.setAttribute("thoseobjects", thoseobjects);
jsp.forward(req, resp);
}
And here is the code for the DataAccessObject class which is extended by the two DAO classes in the calling code:
public class DataAccessObject {
private static DataSource dataSource;
private static Object idLock = new Object();
public static void setDataSource(DataSource dataSource) {
DataAccessObject.dataSource = dataSource;
}
protected static Connection getConnection() {
try {return dataSource.getConnection();}
catch (SQLException e) {throw new RuntimeException(e);}
}
protected static void close(Statement statement, Connection connection) {
close(null, statement, connection);
}
protected static void close(ResultSet rs, Statement statement, Connection connection) {
try {
if (rs != null) rs.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {throw new RuntimeException(e);}
}
protected static Long getUniqueId() {
ResultSet rs = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = getConnection();
synchronized (idLock) {
statement = connection.prepareStatement("select next_value from sequence");
rs = statement.executeQuery();
rs.first();
long id = rs.getLong(1);
statement.close();
statement = connection.prepareStatement("update sequence set next_value = ?");
statement.setLong(1, id + 1);
statement.executeUpdate();
statement.close();
return new Long(id);
}
}
catch (SQLException e) {throw new RuntimeException(e);}
finally{close(rs, statement, connection);}
}
}
The data source is created in web.xml, as follows:
<resource-ref>
<description>dataSource</description>
<res-ref-name>datasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I suspect that the code where it "runs fine" in, is code actually running in an application server. The example you are posting, which just runs a static void main() method, wont get any resources which has been defined in web.xml.
I am guessing that you use JDNI to setup the initial datasource. And then using something like
#Resource(name="jdbc/mydb")
private DataSource dataSource;
to set up your connection. Right?
EDIT:
After seeing your code, it seems like your data source is newer initialised at all. Just putting a element into your web.xml will not do it alone. You will also need to actually configure the dataSource, you know, specify the driver, username, password, uri etc etc etc.
I'm guessing the find() method of the DAO that works, isn't actually using the dataSource. What you have shown so far, doesn't insigunate that your have a initialised dataSource at all.
Just to give you an idea, I liked a tutorial on how you would do this with Tomcat and JDNI. (Or even better, use spring-jdbc).
http://www.mkyong.com/tomcat/how-to-configure-mysql-datasource-in-tomcat-6/
Use dataSource as <javax.sql.DataSource> instance, rather than an instance of <javax.activation.DataSource>.
In short, you should replace the statement <import javax.activation.DataSource;> by this other <import javax.sql.DataSource;>.
Use dataSource as javax.sql.DataSource instance, rather than an instance of javax.activation.DataSource. In short, you should replace the statement:
import javax.activation.DataSource;
by this other:
import javax.sql.DataSource;

How to call Java object from CDI bean

I have a CDI bean with Java object which I use to display profile data from Database:
Parent Bean
#Named("DCProfileTabGeneralController")
#ViewScoped
public class DCProfileTabGeneral implements Serializable
{
public DCObj dc;
public class DCObj
{
private int componentStatsId; // COMPONENTSTATSID NUMBER(38,0)
........
// Default Constructor
public DCObj(){};
public DCObj(int componentStatsId....)
{
this.componentStatsId = componentStatsId;
.......
}
public int getComponentStatsId()
{
return componentStatsId;
}
public void setComponentStatsId(int componentStatsId)
{
this.componentStatsId = componentStatsId;
}
....
}
// Getters ------------------------------------------------------------------------------------
public DCObj getdcData()
{
return dc;
}
#PostConstruct
public void initData() throws SQLException
{
initDBData();
}
// Generate data Object from Oracle
public void initDBData() throws SQLException
{
dc = new DCObj(result.getInt("COMPONENTSTATSID"),
.........
}
}
Validator
#Named("ValidatorDatacenterController")
#ViewScoped
public class ValidatorDatacenter implements Validator, Serializable
{
public ValidatorDatacenter()
{
}
#Inject
private DCProfileTabGeneral profileTabGeneral;
// Validate Datacenter Name
public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
{
int componentStatsId = -1;
if (profileTabGeneral != null)
{
DCObj dcData = profileTabGeneral.dc;
if (dcData != null)
{
componentStatsId = dcData.getComponentStatsId();
}
}
if (componentStatsId == -1)
{
return;
}
String l;
String s;
if (value != null && !(s = value.toString().trim()).isEmpty())
{
if (s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
int resComponentStatsId = -1;
try
{
conn = ds.getConnection();
// if componentsstatsid <> edited componentstatsid in jsf -> throw validator exception
ps = conn.prepareStatement("SELECT componentstatsid from COMPONENTSTATS where NAME = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while (rs.next())
{
resComponentStatsId = rs.getInt(1);
}
if (resComponentStatsId != -1 && resComponentStatsId != componentStatsId)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' is already in use!", null));
}
}
catch (SQLException x)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" SQL error!", null));
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
}
else
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" This field cannot be empty!", null));
}
}
}
I have a custom validator which checks the input values from the profile page into the Database. I tested to get the Java object from the parent page using #Inject and to pass the Ojject to the validator. It turns out that I get empty Java object every time when I use #Inject.
I also tested to get Int using CDI. It works but when I again tested to get the Java Object again I get empty Object.
Can you tell me what is the proper way to call a Java Object from CDI bean? Why I cannot get Java object from CDI bean?
If I recall correctly CDI injection will not work with a validator. Use advanced from Myfaces CODI as the JSF-module from deltaspike is not ready yet. https://cwiki.apache.org/EXTCDI/jsf-usage.html
Or go for deltaspike and use the BeanProvider to get your instance.
BeanProvider.getContextualReference(DCProfileTabGeneral .class, false);

Categories