-1

Before it work but now it is not working.And previously when it worked i use to get session Null in CrediCarddao.java for updating the customer status and inserting new creditcard record into database.

Apr 14, 2017 9:32:36 AM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy Apr 14, 2017 9:32:36 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\spring.xml] Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache INFO: Looking for @ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext@68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy Apr 14, 2017 9:32:37 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache INFO: Looking for @ControllerAdvice: org.springframework.context.support.FileSystemXmlApplicationContext@68de145: startup date [Fri Apr 14 09:32:36 CDT 2017]; root of context hierarchy Apr 14, 2017 9:32:37 AM org.springframework.context.support.FileSystemXmlApplicationContext refresh WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardDao' defined in file [C:\BCJ_DEC_2016\workspace\CoreJava\creditcardprocess\target\classes\com\bcj\creditcardprocess\dao\CreditCardDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140) at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84) at com.bcj.creditcardprocess.CreditCardMain.main(CreditCardMain.java:15) Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bcj.creditcardprocess.dao.CreditCardDao]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ... 13 more Caused by: java.lang.NullPointerException at com.bcj.creditcardprocess.dao.CreditCardDao.(CreditCardDao.java:22) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ... 15 more

CreditCardMain.java*

package com.bcj.creditcardprocess;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.bcj.creditcardprocess.service.CreditCardService;

public class CreditCardMain {    

    public static void main(String[] args) {    

        @SuppressWarnings("resource")
        ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml");

        CreditCardService obj = (CreditCardService) context.getBean("cCardService");
        //CreditCardService  cCardService = new CreditCardService();

        obj.processCreditCard();    
    }    
}

CreditCardService.java

package com.bcj.creditcardprocess.service;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.Customer;


@Service
public class CreditCardService {

    @Autowired
    private CreditCardDao cCardDao;

    public void setcCardDao(CreditCardDao cCardDao) {
        this.cCardDao = cCardDao;
    }

    public void processCreditCard() {

        List<Customer> customerList = cCardDao.getCustomerList();
        // creating a pool of 5 threads

        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
            Customer cust = (Customer) iterator.next();
            System.out.println(cust);

            WorkerThread thread =  new WorkerThread();
            thread.threadmain(customerList);
            //Runnable worker = new WorkerThread(cust);

            // calling execute method of ExecutorService

            //executor.execute(worker);
/*WorkerThread thread =  new WorkerThread();
thread.threadmain(customerList);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }

        System.out.println("Finished all threads");*/

        /*
         * List<Object> result = (List<Object>) customerList; Iterator itr =
         * result.iterator(); while(itr.hasNext()){ Object[] obj = (Object[])
         * itr.next();
         * 
         * System.out.println(String.valueOf(obj[0])+"   "+String.valueOf(obj[1]
         * ));
         * 
         */

        /*
         * for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread(obj
         * ); executor.execute(worker);//calling execute method of
         * ExecutorService }
         */
        /*executor.shutdown();
        while (!executor.isTerminated()) {
        }

        System.out.println("Finished all threads");*/
    }
}
}

WorkerThread.java

package com.bcj.creditcardprocess.service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bcj.creditcardprocess.dao.CreditCardDao;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;

@Service
public class WorkerThread implements Runnable {

    @Autowired
    private CreditCardDao cCardDao;

    public void setcCardDao(CreditCardDao cCardDao) {
        this.cCardDao = cCardDao;
    }

    public WorkerThread() {

    }

    WorkerThread(Customer cust2) {
        this.cust = cust2;
    }

    Customer cust;

    public void run() {

        System.out.println(Thread.currentThread().getName() + " (Start) message = " + cust.getFirstName());

        try {
            getCutomerDetailsByTextFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + " (End)");

    }

    public synchronized void getCutomerDetailsByTextFile() throws IOException {

        FileReader fr = new FileReader("details.txt");
        BufferedReader br = new BufferedReader(fr);

        String line = "";
        while ((line = br.readLine()) != null) {
            System.out.println(line);

            String[] details = line.split(" ");

            if (details[0].equalsIgnoreCase(cust.getFirstName()) && details[1].equalsIgnoreCase(cust.getLastName())
                    && details[2].equals(cust.getSsn())) {
                System.out.println(" ssn had");

                if (Integer.parseInt(details[3]) > 700 && Integer.parseInt(cust.getAnnualIncome()) > 100000) {

                    CreditCard card = new CreditCard();
                    card.setCreditLimit(5000);
                    card.setCustomerId(cust.getId());
                    generateCardNumber(card, cust);

                    cust.setStatus("Approved");

                } else if (Integer.parseInt(details[3]) > 600 && Integer.parseInt(details[3]) < 700
                        && Integer.parseInt(cust.getAnnualIncome()) > 70000) {

                    CreditCard card = new CreditCard();
                    card.setCreditLimit(3000);
                    card.setCustomerId(cust.getId());
                    generateCardNumber(card, cust);

                    cust.setStatus("Approved");

                } else {
                    cCardDao.updateCustomer(cust);

                    cust.setStatus("Declined");
                }

                break;

            }
        }

    }

    public void threadmain(List<Customer> customerList) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (Iterator iterator = customerList.iterator(); iterator.hasNext();) {
            Customer cust = (Customer) iterator.next();

            Runnable worker = new WorkerThread(cust);
            executor.execute(worker);// calling execute method of
                                        // ExecutorService
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }

        System.out.println("Finished all threads");

    }

    private void generateCardNumber(CreditCard cCard, Customer cust) {

        Random rand = new Random();

        String cardNumber = Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000)
                + Integer.toString(rand.nextInt(9999) + 1000) + Integer.toString(rand.nextInt(9999) + 1000);

        String cvv = Integer.toString(rand.nextInt(999) + 100);

        Calendar cal = Calendar.getInstance();
        Date today = cal.getTime();
        cal.add(Calendar.YEAR, 3); // to get previous year add -1
        Date next = cal.getTime();

        SimpleDateFormat adf = new SimpleDateFormat("MM/YY");
        String expiryDate = adf.format(next);

        cCard.setCardNumber(cardNumber);
        cCard.setCvv(cvv);
        cCard.setExpiryDate(expiryDate);

        cCardDao.persistCreditCard(cCard, cust);    
    }    
}

CreditCardDao.java

package com.bcj.creditcardprocess.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bcj.creditcardprocess.model.CreditCard;
import com.bcj.creditcardprocess.model.Customer;

@Repository
@Transactional
public class CreditCardDao {

    @Autowired
    private SessionFactory sessionFactory;
    private Session session = sessionFactory.getCurrentSession();

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    // Session session = sessionFactory.getCurrentSession();
    List<Customer> custs;

    public List<Customer> getCustomerList() {

        Transaction tx = session.beginTransaction();
        List custs = session.createQuery("FROM Customer WHERE status='New'").list();

        return custs;    
    }

    public void persistCreditCard(CreditCard cCard, Customer cust) {
        int x = cCard.getCustomerId();
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        session.persist(cCard);
        session.update(cust);

        System.out.println("customer saved sucessfully" + cCard);    
    }

    public void updateCustomer(Customer cust) {
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        session.update(cust);    
    }    
}

Spring.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="com.bcj.creditcardprocess" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="cCardService" class="com.bcj.creditcardprocess.service.CreditCardService" />
    <bean id="cCardDao" class="com.bcj.creditcardprocess.dao.CreditCardDao" />

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/citibank" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <!--Hibernate 4 SessionFactory Bean definition -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.bcj.creditcardprocess.model.CreditCard</value>
                <value>com.bcj.creditcardprocess.model.Customer</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.hbm2ddl.auto">update
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
            </props>
        </property>
    </bean>
</beans>

POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.bcj</groupId>
  <artifactId>creditcardprocess</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>creditcardprocess</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>


   <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.3.Final</version>
</dependency>
   <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->



     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
   <!--  https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>


    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>


    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
  </dependencies>
</project>
Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26

2 Answers2

0

Maybe try to change

private Session session = sessionFactory.getCurrentSession();

to a function

public Session getSession() {
    return sessionFactory.getCurrentSession();
}

I am thinking during the class initialization, the class is trying initialize private Session session. And sessionFactory is not ready yet.

shokulei
  • 85
  • 7
0

Your getSessionFactory() in CreditCardDao.java is throwing the nullPointerExceptionbecause You haven't initialized the SessionFactory so it's initialy pointing to null. You would do that like this:

private SessionFactory sessionFactory=//build sessionfactory code

Note that the SessionFactoryshould be created once only, you can use the singleton design pattern for that.

Gherbi Hicham
  • 2,416
  • 4
  • 26
  • 41
  • intially spring will inject the sessionfactory right? But in the next methods i.e, persistcreditcard() and updatecustomer() i am creating the session through sessionFactory. so inthis methods session is null but in the first getcustomers() i am able to get customers. – Sridhar Reddy Apr 15 '17 at 05:43
  • I see you are using the @Autowired annotation which injects the configuration for you, see this thread which might help you to debug the problem: http://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage – Gherbi Hicham Apr 15 '17 at 08:49