PageRenderTime 10ms CodeModel.GetById 1ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/NewsManagerJSF/src/main/java/com/epam/news2/dao/pool/Connector.java

https://bitbucket.org/BahdanSiamionau/news-manager-2
Java | 53 lines | 42 code | 11 blank | 0 comment | 4 complexity | 5d625eef80eee0de49030ff61aef94a9 MD5 | raw file
 1package com.epam.news2.dao.pool;
 2
 3import java.sql.Connection;
 4import java.sql.PreparedStatement;
 5import java.sql.SQLException;
 6import java.sql.Statement;
 7
 8import org.apache.log4j.Logger;
 9
10import com.epam.news2.exception.NewsManagerException;
11
12
13public final class Connector implements AutoCloseable {
14	
15	private static final String EXCEPTION_NULL_CONN = "Connection is null";
16	private static final Logger logger = Logger.getLogger(Connector.class);
17	
18	private ConnectorPool pool;
19	private Connection connection;
20
21	public Connector(ConnectorPool pool, Connection connection) {
22		this.pool = pool;
23		this.connection = connection;
24	}
25	
26	public Statement getStatement() throws NewsManagerException {
27		try {
28			if (connection != null) {
29				return connection.createStatement();
30			}
31			throw new NewsManagerException(EXCEPTION_NULL_CONN);
32		} catch (SQLException ex) {
33			logger.error(ex.getMessage());
34			throw new NewsManagerException(ex);
35		}
36	}
37	
38	public PreparedStatement getPreparedStatement(String query) throws NewsManagerException {
39		try {
40			if (connection != null) {
41				return connection.prepareStatement(query);
42			}
43			throw new NewsManagerException(EXCEPTION_NULL_CONN);
44		} catch (SQLException ex) {
45			logger.error(ex.getMessage());
46			throw new NewsManagerException(ex);
47		}
48	}
49	
50	public void close() {
51		pool.release(this);
52	}
53}