Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc / JDBCResource.java @ 43020

History | View | Annotate | Download (7.91 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.fmap.dal.store.jdbc;
24

    
25
import java.sql.Connection;
26
import java.sql.SQLException;
27
import java.text.MessageFormat;
28

    
29
import javax.sql.DataSource;
30

    
31
import org.apache.commons.dbcp.BasicDataSource;
32
import org.apache.commons.lang3.StringUtils;
33
import org.gvsig.fmap.dal.exception.DataException;
34
import org.gvsig.fmap.dal.exception.InitializeException;
35
import org.gvsig.fmap.dal.resource.ResourceParameters;
36
import org.gvsig.fmap.dal.resource.db.AbstractDBResourceNoBlocker;
37
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
38
import org.gvsig.fmap.dal.resource.exception.ResourceException;
39
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
40
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
41
import org.slf4j.Logger;
42
import org.slf4j.LoggerFactory;
43

    
44
public class JDBCResource extends AbstractDBResourceNoBlocker {
45

    
46
    final static private Logger logger = LoggerFactory.getLogger(JDBCResource.class);
47

    
48
    public final static String NAME = "JDBCResource";
49
    public static final String DESCRIPTION = "JDBC Connection";
50

    
51
    protected DataSource dataSource = null;
52

    
53
    public JDBCResource(
54
            JDBCResourceParameters parameters
55
    ) throws InitializeException {
56
        super(parameters);
57
        registerJDBCDriver();
58
    }
59

    
60
    /**
61
     * Registra/Carga el driver de JDBC.
62
     * 
63
     * Debe ser sobreescrita en cada proveedor de datos para asegurar que se
64
     * tegna acceso al driver.
65
     * 
66
     * @throws InitializeException 
67
     */
68
    protected void registerJDBCDriver() throws InitializeException {
69
        String className = this.getParameters().getJDBCDriverClassName();
70
        if (className == null) {
71
            return;
72
        }
73
        try {
74
            Class theClass = Class.forName(className);
75
            if (theClass == null) {
76
                throw new JDBCDriverClassNotFoundException(this.getName(), className);
77
            }
78
        } catch (Exception e) {
79
            throw new InitializeException(e);
80
        }
81
    }
82

    
83
    /**
84
     * Crea el JDBC DataSource a partir de la informacion de los parametros
85
     * del recurso.
86
     * 
87
     * Debe ser sobreescrita en cada proveedor de datos para asegurar que se
88
     * tenga acceso al driver.
89
     * 
90
     * @return 
91
     */
92
    protected DataSource createDataSource() {
93
        JDBCResourceParameters jdbcParams = this.getParameters();
94
        BasicDataSource dataSource = new BasicDataSource();
95
        dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
96
        dataSource.setUsername(jdbcParams.getUser());
97
        dataSource.setPassword(jdbcParams.getPassword());
98
        dataSource.setUrl(jdbcParams.getUrl());
99

    
100
        dataSource.setMaxWait(60L * 1000); // FIXME
101

    
102
//                FIXME Set Pool parameters:
103
//                dataSource.setMaxActive(maxActive);
104
//                dataSource.setMaxIdle(maxActive);
105
//                dataSource.setMaxOpenPreparedStatements(maxActive);
106
//                dataSource.setMaxWait(maxActive);
107
//                dataSource.setInitialSize(initialSize);
108
//                dataSource.setDefaultReadOnly(defaultReadOnly);
109
//                dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
110
//                dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
111
//                dataSource.setMinIdle(minIdle);
112
//                dataSource.setTestOnBorrow(testOnBorrow);
113
//                dataSource.setTestOnReturn(testOnReturn);
114
//                dataSource.setTestWhileIdle(testOnReturn);
115
//                dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
116
//
117
//                dataSource.setAccessToUnderlyingConnectionAllowed(allow);
118
//                dataSource.setLoginTimeout(seconds);
119
//                dataSource.setLogWriter(out);
120
        return dataSource;
121
    }
122

    
123

    
124
    @Override
125
    public JDBCResourceParameters getParameters() {
126
        return (JDBCResourceParameters) super.getParameters();
127
    }
128

    
129
    @Override
130
    public String getName() throws AccessResourceException {
131
        JDBCResourceParameters params = this.getParameters();
132
        return MessageFormat.format("JDBCResource({0},{1},{2},{3},{4})",
133
                new Object[]{
134
                    params.getJDBCDriverClassName(),
135
                    params.getHost(),
136
                    params.getPort(),
137
                    params.getUser(),
138
                    params.getDBName()
139
                }
140
        );
141
    }
142
    
143
    public Connection getJDBCConnection() throws AccessResourceException {
144
        return (Connection) get();
145
    }
146

    
147
    public void closeConnection(Connection connection) {
148
        try {
149
            logger.debug("before-close connection" + this.getStatusInformation());
150
            connection.close();
151
            logger.debug("after close connection " + this.getStatusInformation());
152
        } catch (Exception ex) {
153
            logger.warn("Problems closing connection.", ex);
154
        }
155
    }
156

    
157
    protected void debugPoolStatus(String src) {
158
        if (logger.isDebugEnabled()) {
159
            logger.debug(src + "  " + this.getStatusInformation());
160
        }
161
    }
162

    
163
    public String getStatusInformation() {
164
        if (!(dataSource instanceof BasicDataSource)) {
165
            return "Connected: " + this.isConnected();
166
        }
167
        BasicDataSource ds = (BasicDataSource) dataSource;
168
        String s = MessageFormat.format("Conneted {0}, actives {1}/{2}, idle {3}/{4}",
169
            this.isConnected(),
170
            ds.getNumActive(),
171
            ds.getMaxActive(),
172
            ds.getNumIdle(),
173
            ds.getMaxIdle()
174
        );
175
        return s;
176
    }
177

    
178
    @Override
179
    protected synchronized Object getTheConnection() throws DataException {
180
        try {
181
            Object conn = this.dataSource.getConnection();
182
            debugPoolStatus("getTheConnection");
183
            return conn;
184
        } catch (SQLException e) {
185
            throw new JDBCSQLException(e);
186
        }
187
    }
188

    
189
    @Override
190
    public boolean isThis(ResourceParameters parameters)
191
            throws ResourceException {
192
        if (!super.isThis(parameters)) {
193
            return false;
194
        }
195
        JDBCResourceParameters params = (JDBCResourceParameters) parameters;
196
        String dbName = params.getDBName();
197
        String myDbName = this.getParameters().getDBName();
198
        if ( !StringUtils.equals(dbName, myDbName) ) {
199
            return false;
200
        }
201

    
202
        String driver = params.getJDBCDriverClassName();
203
        String myDriver = getParameters().getJDBCDriverClassName();
204
        if ( !StringUtils.equals(driver, myDriver) ) {
205
            return false;
206
        }
207
        return true;
208
    }
209

    
210
    @Override
211
    public boolean isConnected() {
212
        if (dataSource == null) {
213
            return false;
214
        }
215
        if (dataSource instanceof BasicDataSource) {
216
            return ((BasicDataSource) dataSource).getNumActive() > 0
217
                    || ((BasicDataSource) dataSource).getNumIdle() > 0;
218
        }
219
        return true;
220
    }
221

    
222
    @Override
223
    protected void connectToDB() throws DataException {
224
        if (this.dataSource != null) {
225
            return;
226
        }
227
        this.dataSource = this.createDataSource();
228
    }
229

    
230
    public void beginUse() {
231
        this.executeBegins();
232
    }
233

    
234
    public void endUse() {
235
        this.executeEnds();
236
    }
237
}