Почему я получаю NullPointer в диспетчере транзакций, когда я передаю туда пул соединений? - PullRequest
0 голосов
/ 30 сентября 2018

при работе с сервлетами и jdbc столкнулся с проблемой.Я получаю NullPointer в моем менеджере транзакций, и я не могу понять, почему.Я настраиваю пул соединений, используя BasicDataSource, затем пытаюсь получить соединение, используя DataSource, но я получаю NPE.Я не могу понять, где я был не прав.И в чем проблема?Я буду благодарен за помощь!

public class TransactionManager {
    private DataSource dataSource;

    public TransactionManager(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public <T> T doInTransaction(TransactionOperation<T> operation) {
        T result = null;

        Connection connection = null;
        try {
            connection = dataSource.getConnection();  // here i got NPE
            connection.setAutoCommit(false);
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

            result = operation.operation(connection);

            connection.commit();
        } catch (SQLException e) {
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

Класс MyConnectionPool:

public final class ConnectionPool {

    private ConnectionPool(){

    }

    public static BasicDataSource getPoolConnection() {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/shop_db");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setConnectionProperties("useSSL=false");
        return dataSource;
    }

Мой класс ConyextListener:

public class ContextListener implements ServletContextListener {
    private static final Logger LOG = Logger.getLogger(ContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent event) {
        BasicDataSource dataSource = ConnectionPool.getPoolConnection();
        UserService userService = new UserServiceImpl(dataSource);

        event.getServletContext().setAttribute("userService", userService);

        ServletContext servletContext = event.getServletContext();
        initLog4J(servletContext);
    }

Здесь я использую свой менеджер транзакций:

public class UserServiceImpl implements UserService {

    private TransactionManager transactionManager;

    private UserDAO userDAO;

    public UserServiceImpl(BasicDataSource dataSource) {
        userDAO = new UserDAOImpl();
        transactionManager = new TransactionManager(dataSource);
    }


    @Override
    public boolean isExistUser(String login) {
        return transactionManager.doInTransaction( // here is my program to move to the transaction manager
                connection ->
                        userDAO.isExistUser(login, connection)
        );
    }

Трассировка стека исключений:

SEVERE: Servlet.service() for servlet [servlet.RegistrationServlet] in context with path [] threw exception
java.lang.NullPointerException
    at service.impl.UserServiceImpl.isExistUser(UserServiceImpl.java:33)
    at servlet.RegistrationServlet.doPost(RegistrationServlet.java:52)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Регистрационный сервлет:

@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
    private static final Logger LOG = Logger.getLogger(RegistrationServlet.class);

    private long startTime;

    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = (UserService) getServletContext().getAttribute("userService");
    }

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        startTime = System.currentTimeMillis();
        httpServletRequest.getRequestDispatcher(ConstantApp.JSPPages.REGISTRATION_PAGE).forward(httpServletRequest, httpServletResponse);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RegistrationInfo registrationInfo = new RegistrationInfoImpl(request);
        Map<String, String> validationError = Validation.validate(registrationInfo);
        CaptchaValidate captchaValidate = new CaptchaValidate(request);

        String contextType = getServletContext().getInitParameter(ConstantApp.ContextType.CONTEXT_TYPE);
        String imageName = getServletContext().getInitParameter(ConstantApp.ContextType.CONTEXT_AVATAR_PATH);
        boolean isValidateCaptcha = captchaValidate.validateCaptcha(contextType);
        boolean isValidTime = RegistrationTimer.isValidRegistrationTime(startTime, Integer.parseInt(getServletContext().getInitParameter(ConstantApp.ContextType.CONTEXT_REGISTRATION_TIME)));

        LOG.debug("Validation error map: " + validationError.entrySet());
        if (validationError.isEmpty() && !userService.isExistUser(registrationInfo.getLogin()) && isValidateCaptcha && isValidTime) {////// here i move to UserServiceImpl I do not get inside the conditions
            userService.registrationUser(new User(registrationInfo.getLogin(), registrationInfo.getFirstName(), registrationInfo.getLastName(), registrationInfo.getEmail(), registrationInfo.getPassword(), imageName, "client"));
            request.getSession().setAttribute(ConstantApp.SessionUserAttribute.SESSION_LOGIN, registrationInfo.getLogin());
            request.getRequestDispatcher(ConstantApp.JSPPages.INDEX_PAGE).forward(request, response);
        }
...