View Javadoc
1   /*
2    * Copyright (c) 2002-2022, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  /** Contibution AtosWorldline / Meteo France - mlux */
35  package fr.paris.lutece.util.pool.service;
36  
37  import com.mchange.v2.c3p0.ComboPooledDataSource;
38  import fr.paris.lutece.util.env.EnvUtil;
39  
40  import java.sql.Connection;
41  import java.sql.SQLException;
42  
43  import java.util.Map;
44  
45  import javax.sql.DataSource;
46  
47  import org.apache.logging.log4j.LogManager;
48  import org.apache.logging.log4j.Logger;
49  
50  /**
51   * C3P0 connection service
52   */
53  public class C3p0ConnectionService implements ConnectionService
54  {
55      /**
56       * C3P0 connection pool
57       */
58      private ComboPooledDataSource _dataSource;
59  
60      /**
61       * Pool name
62       */
63      private String _strPoolName;
64  
65      /**
66       * Log4j logger
67       */
68      private Logger _logger = LogManager.getLogger( this.getClass( ) );
69  
70      /**
71       * {@inheritDoc }
72       */
73      @Override
74      public void init( Map<String, String> htParamsConnectionPool )
75      {
76          try
77          {
78              _dataSource = new ComboPooledDataSource( _strPoolName );
79  
80              String strDriver = htParamsConnectionPool.get( getPoolName( ) + ".driver" );
81              _dataSource.setDriverClass( strDriver );
82  
83              String strUrl = htParamsConnectionPool.get( getPoolName( ) + ".url" );
84              strUrl = EnvUtil.evaluate( strUrl, EnvUtil.PREFIX_ENV );
85              _dataSource.setJdbcUrl( strUrl );
86  
87              String strUser = htParamsConnectionPool.get( getPoolName( ) + ".user" );
88              strUser = EnvUtil.evaluate( strUser, EnvUtil.PREFIX_ENV );
89              _dataSource.setUser( strUser );
90  
91              String strPassword = htParamsConnectionPool.get( getPoolName( ) + ".password" );
92              strPassword = EnvUtil.evaluate( strPassword, EnvUtil.PREFIX_ENV );
93              _dataSource.setPassword( strPassword );
94  
95              String strMaxConns = htParamsConnectionPool.get( getPoolName( ) + ".maxconns" );
96              int nMaxConns = ( strMaxConns == null ) ? 0 : Integer.parseInt( strMaxConns );
97              _dataSource.setMaxPoolSize( nMaxConns );
98  
99              String strMinConns = htParamsConnectionPool.get( getPoolName( ) + ".initconns" );
100             int nInitConns = ( strMinConns == null ) ? 0 : Integer.parseInt( strMinConns );
101             _dataSource.setInitialPoolSize( nInitConns );
102             _dataSource.setMinPoolSize( nInitConns );
103         }
104         catch( Exception e )
105         {
106             _logger.error( "Error while initializing the pool {}", getPoolName( ), e );
107         }
108 
109         _logger.info( "Initialization of the C3P0 pool named '{}', Min/Max pool size : {} / {}", ( ) -> getPoolName( ), _dataSource::getMinPoolSize,
110                 _dataSource::getMaxPoolSize );
111     }
112 
113     /**
114      * {@inheritDoc }
115      */
116     @Override
117     public Connection getConnection( )
118     {
119         Connection conn = null;
120 
121         try
122         {
123             if ( _dataSource != null )
124             {
125                 conn = _dataSource.getConnection( );
126 
127                 if ( conn != null )
128                 {
129                     if ( _logger.isDebugEnabled( ) )
130                     {
131                         _logger.debug( "The connexion is get, Current/Max pool : {}/{}", _dataSource.getNumConnectionsAllUsers( ),
132                                 _dataSource.getMaxPoolSize( ) );
133                     }
134                 }
135             }
136         }
137         catch( Exception e )
138         {
139             _logger.error( "Erreur when getting the connexion with the pool : {}", getPoolName( ), e );
140         }
141 
142         return conn;
143     }
144 
145     /**
146      * {@inheritDoc }
147      */
148     @Override
149     public void freeConnection( Connection conn )
150     {
151         try
152         {
153             conn.close( );
154 
155             if ( _logger.isDebugEnabled( ) )
156             {
157 
158                 _logger.debug( "The connexion is released, Current/Max pool : {}/{}", _dataSource.getNumConnectionsAllUsers( ), _dataSource.getMaxPoolSize( ) );
159 
160             }
161         }
162         catch( SQLException e )
163         {
164             _logger.error( "SQL error when releasing the connexion with the pool : {}", getPoolName( ), e );
165         }
166         catch( Exception e )
167         {
168             _logger.error( "Error while releasing the connexion with the pool : {}", getPoolName( ), e );
169         }
170     }
171 
172     /**
173      * {@inheritDoc }
174      */
175     @Override
176     public void setPoolName( String poolName )
177     {
178         this._strPoolName = poolName;
179     }
180 
181     /**
182      * {@inheritDoc }
183      */
184     @Override
185     public String getPoolName( )
186     {
187         return _strPoolName;
188     }
189 
190     /**
191      * {@inheritDoc }
192      */
193     @Override
194     public void setLogger( Logger log )
195     {
196         this._logger = log;
197     }
198 
199     /**
200      * {@inheritDoc }
201      */
202     @Override
203     public Logger getLogger( )
204     {
205         return _logger;
206     }
207 
208     /**
209      * {@inheritDoc }
210      */
211     @Override
212     public void release( )
213     {
214         _dataSource.close( );
215     }
216 
217     /**
218      * {@inheritDoc }
219      */
220     @Override
221     public int getCurrentConnections( )
222     {
223         int nCurrentConnections = -1;
224 
225         try
226         {
227             nCurrentConnections = _dataSource.getNumConnections( );
228         }
229         catch( SQLException ex )
230         {
231             _logger.error( "GetCurrentConnections error : {}", ex.getMessage( ), ex );
232         }
233 
234         return nCurrentConnections;
235     }
236 
237     /**
238      * {@inheritDoc }
239      */
240     @Override
241     public int getMaxConnections( )
242     {
243         return _dataSource.getMaxPoolSize( );
244     }
245 
246     /**
247      * {@inheritDoc }
248      */
249     @Override
250     public String getPoolProvider( )
251     {
252         return "C3P0";
253     }
254 
255     /**
256      * {@inheritDoc }
257      */
258     @Override
259     public DataSource getDataSource( )
260     {
261         return _dataSource;
262     }
263 }