1
|
/**
|
2
|
* Copyright (C) 2009 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
|
10
|
package eu.etaxonomy.cdm.opt.config;
|
11
|
|
12
|
import java.io.File;
|
13
|
import java.lang.reflect.InvocationTargetException;
|
14
|
import java.lang.reflect.Method;
|
15
|
import java.sql.Connection;
|
16
|
import java.sql.ResultSet;
|
17
|
import java.sql.SQLException;
|
18
|
import java.util.Objects;
|
19
|
import java.util.Properties;
|
20
|
|
21
|
import javax.naming.NamingException;
|
22
|
import javax.sql.DataSource;
|
23
|
|
24
|
import org.apache.commons.io.FilenameUtils;
|
25
|
import org.apache.log4j.Logger;
|
26
|
import org.hibernate.dialect.H2CorrectedDialect;
|
27
|
import org.hibernate.dialect.MySQL5MyISAMUtf8Dialect;
|
28
|
import org.hibernate.dialect.PostgreSQL82Dialect;
|
29
|
import org.springframework.beans.BeansException;
|
30
|
import org.springframework.beans.factory.annotation.Autowired;
|
31
|
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
32
|
import org.springframework.context.annotation.Bean;
|
33
|
import org.springframework.context.annotation.Configuration;
|
34
|
import org.springframework.context.annotation.PropertySource;
|
35
|
import org.springframework.core.Ordered;
|
36
|
import org.springframework.core.annotation.Order;
|
37
|
import org.springframework.core.env.MutablePropertySources;
|
38
|
import org.springframework.core.env.PropertiesPropertySource;
|
39
|
import org.springframework.core.io.FileSystemResource;
|
40
|
import org.springframework.jndi.JndiObjectFactoryBean;
|
41
|
|
42
|
import com.mchange.v2.c3p0.ComboPooledDataSource;
|
43
|
|
44
|
import eu.etaxonomy.cdm.api.config.CdmConfigurationKeys;
|
45
|
import eu.etaxonomy.cdm.config.ConfigFileUtil;
|
46
|
import eu.etaxonomy.cdm.database.CdmDatabaseException;
|
47
|
import eu.etaxonomy.cdm.database.WrappedCdmDataSource;
|
48
|
import eu.etaxonomy.cdm.database.update.CdmUpdater;
|
49
|
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
|
50
|
import eu.etaxonomy.cdm.model.metadata.CdmMetaDataPropertyName;
|
51
|
import eu.etaxonomy.cdm.remote.config.AbstractWebApplicationConfigurer;
|
52
|
|
53
|
/**
|
54
|
* The <code>DataSourceConfigurer</code> can be used as a replacement for a xml configuration in the application context.
|
55
|
* <p>
|
56
|
* The id of the loaded data source bean aka the <b>cdm instance name</b> is put into the <b>Spring environment</b> from
|
57
|
* where it can be retrieved using the key {@link CDM_DATA_SOURCE_ID}.
|
58
|
* <p>
|
59
|
* Enter the following in your application context configuration in order to enable the <code>DataSourceConfigurer</code>:
|
60
|
*
|
61
|
<pre>
|
62
|
<!-- enable processing of annotations such as @Autowired and @Configuration -->
|
63
|
<context:annotation-config/>
|
64
|
|
65
|
<bean class="eu.etaxonomy.cdm.remote.config.DataSourceConfigurer" >
|
66
|
</bean>
|
67
|
</pre>
|
68
|
* The <code>DataSourceConfigurer</code> allows alternative ways to specify a data source:
|
69
|
*
|
70
|
* <ol>
|
71
|
* <li>Specify the data source bean to use in the Java environment properties:
|
72
|
* <code>-Dcdm.datasource={dataSourceName}</code> ({@link #ATTRIBUTE_DATASOURCE_NAME}).
|
73
|
* The data source bean with the given name will then be loaded from the <code>cdm.beanDefinitionFile</code>
|
74
|
* ({@link #CDM_BEAN_DEFINITION_FILE}), which must be a valid Spring bean definition file.
|
75
|
* </li>
|
76
|
* <li>
|
77
|
* Use a JDBC data source which is bound into the JNDI context. In this case the JNDI name is specified
|
78
|
* via the {@link #ATTRIBUTE_JDBC_JNDI_NAME} as attribute to the ServletContext.
|
79
|
* This scenario usually being used by the cdm-server application.
|
80
|
* </li>
|
81
|
* </ol>
|
82
|
* The attributes used in (1) and (2) are in a first step being searched in the ServletContext
|
83
|
* if not found search in a second step in the environment variables of the OS, see:{@link #findProperty(String, boolean)}.
|
84
|
*
|
85
|
* @author a.kohlbecker
|
86
|
* @since 04.02.2011
|
87
|
*/
|
88
|
@Configuration
|
89
|
// cdmlib-remote.properties is used by developers to define the datasource bean to use from
|
90
|
// the datasources.xml. It is not relevant for production systems.
|
91
|
@PropertySource(value="file:${user.home}/.cdmLibrary/cdmlib-remote.properties", ignoreResourceNotFound=true)
|
92
|
public class DataSourceConfigurer extends AbstractWebApplicationConfigurer {
|
93
|
|
94
|
public static final Logger logger = Logger.getLogger(DataSourceConfigurer.class);
|
95
|
|
96
|
protected static final String HIBERNATE_DIALECT = "hibernate.dialect";
|
97
|
protected static final String HIBERNATE_SEARCH_DEFAULT_INDEX_BASE = "hibernate.search.default.indexBase";
|
98
|
protected static final String CDM_BEAN_DEFINITION_FILE = "cdm.beanDefinitionFile";
|
99
|
|
100
|
@Autowired // Important!!!!
|
101
|
private ConfigFileUtil configFileUtil;
|
102
|
|
103
|
/**
|
104
|
* Attribute to configure the name of the data source as set as bean name in the datasources.xml.
|
105
|
* This name usually is used as the prefix for the webapplication root path.
|
106
|
* <br>
|
107
|
* <b>This is a required attribute!</b>
|
108
|
*
|
109
|
* @see AbstractWebApplicationConfigurer#findProperty(String, boolean)
|
110
|
*
|
111
|
* see also :
|
112
|
*
|
113
|
* <ul>
|
114
|
* <li><code>eu.etaxonomy.cdm.server.instance.SharedAttributes</code></li>
|
115
|
* <li>{@link CdmConfigurationKeys#CDM_DATA_SOURCE_ID}</li>
|
116
|
* </ul>
|
117
|
*
|
118
|
*/
|
119
|
protected static final String ATTRIBUTE_DATASOURCE_NAME = "cdm.datasource";
|
120
|
|
121
|
/**
|
122
|
* see also <code>eu.etaxonomy.cdm.server.instance.SharedAttributes</code>
|
123
|
*/
|
124
|
public static final String ATTRIBUTE_JDBC_JNDI_NAME = "cdm.jdbcJndiName";
|
125
|
|
126
|
/**
|
127
|
* Force a schema update when the cdmlib-remote-webapp instance is starting up
|
128
|
* see also <code>eu.etaxonomy.cdm.server.instance.SharedAttributes.ATTRIBUTE_FORCE_SCHEMA_UPDATE</code>
|
129
|
*/
|
130
|
public static final String ATTRIBUTE_FORCE_SCHEMA_UPDATE = "cdm.forceSchemaUpdate";
|
131
|
|
132
|
/**
|
133
|
* <b>WARNING!!!!!!!!!!!!!!!</b> Using this option will delete the existing data base followed by database creation.
|
134
|
* <p>
|
135
|
* Force a schema creation when the cdmlib-remote-webapp instance is starting up. Will set the hibernate property
|
136
|
* {@code hibernate.hbm2ddl.auto} to {@code create}
|
137
|
* <p>
|
138
|
* This option will inactivate {@link #ATTRIBUTE_FORCE_SCHEMA_UPDATE} even if this is set.
|
139
|
* <p>
|
140
|
* This attribute has no equivalent in <code>eu.etaxonomy.cdm.server.instance.SharedAttributes</code> and never must
|
141
|
* have any since this setting this attribute for any database listed for a server is far too dangerous. It must only
|
142
|
* be possible to set this option per data base individually.
|
143
|
*/
|
144
|
public static final String ATTRIBUTE_FORCE_SCHEMA_CREATE = "cdm.forceSchemaCreate";
|
145
|
|
146
|
private static String beanDefinitionFile = null;
|
147
|
|
148
|
|
149
|
/**
|
150
|
* The file to load the {@link DataSource} beans from.
|
151
|
* This file is usually {@code ${user.home}/.cdmLibrary/datasources.xml}
|
152
|
* The variable <code>${user.home}</code>is determined by {@link ConfigFileUtil.getCdmHomeDir()}
|
153
|
*
|
154
|
*
|
155
|
* @param filename
|
156
|
*/
|
157
|
public void setBeanDefinitionFile(String filename){
|
158
|
beanDefinitionFile = filename;
|
159
|
}
|
160
|
|
161
|
public String getBeanDefinitionFile(){
|
162
|
if(beanDefinitionFile == null){
|
163
|
beanDefinitionFile = configFileUtil.getCdmHomeDir().getPath() + File.separator + "datasources.xml";
|
164
|
}
|
165
|
return beanDefinitionFile;
|
166
|
}
|
167
|
|
168
|
private String dataSourceId = null;
|
169
|
|
170
|
private DataSource dataSource;
|
171
|
|
172
|
private DataSourceProperties dataSourceProperties;
|
173
|
|
174
|
private Properties getHibernateProperties() {
|
175
|
Properties hibernateProperties = webApplicationContext.getBean("jndiHibernateProperties", Properties.class);
|
176
|
return hibernateProperties;
|
177
|
}
|
178
|
|
179
|
@Bean
|
180
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
181
|
public DataSource dataSource() {
|
182
|
|
183
|
String beanName = findProperty(ATTRIBUTE_DATASOURCE_NAME, true);
|
184
|
String jndiName = null;
|
185
|
if(this.dataSource == null){
|
186
|
jndiName = findProperty(ATTRIBUTE_JDBC_JNDI_NAME, false);
|
187
|
|
188
|
if(jndiName != null){
|
189
|
try {
|
190
|
dataSource = useJndiDataSource(jndiName);
|
191
|
dataSourceId = FilenameUtils.getName(jndiName);
|
192
|
} catch (NamingException e) {
|
193
|
throw new DataSourceException("JNDI data source (" + jndiName + ") not found. Jdbc URI correct? Does the database exist?", e);
|
194
|
}
|
195
|
} else {
|
196
|
dataSource = loadDataSourceBean(beanName);
|
197
|
dataSourceId = beanName;
|
198
|
}
|
199
|
}
|
200
|
|
201
|
if(dataSource == null){
|
202
|
return null;
|
203
|
}
|
204
|
|
205
|
MutablePropertySources sources = env.getPropertySources();
|
206
|
Properties props = new Properties();
|
207
|
props.setProperty(CdmConfigurationKeys.CDM_DATA_SOURCE_ID, dataSourceId);
|
208
|
sources.addFirst(new PropertiesPropertySource("cdm-datasource", props));
|
209
|
|
210
|
if(!isForceSchemaCreate()) {
|
211
|
// validate correct schema version
|
212
|
Connection connection = null;
|
213
|
try {
|
214
|
connection = dataSource.getConnection();
|
215
|
String metadataTableName = "CdmMetaData";
|
216
|
if(inferHibernateDialectName(dataSource).equals(H2CorrectedDialect.class.getName())){
|
217
|
metadataTableName = metadataTableName.toUpperCase();
|
218
|
}
|
219
|
ResultSet tables = connection.getMetaData().getTables(connection.getCatalog(), null, metadataTableName, null);
|
220
|
if(tables.first()){
|
221
|
ResultSet resultSet;
|
222
|
try {
|
223
|
resultSet = connection.createStatement().executeQuery(CdmMetaDataPropertyName.DB_SCHEMA_VERSION.getSqlQuery());
|
224
|
} catch (Exception e) {
|
225
|
try {
|
226
|
resultSet = connection.createStatement().executeQuery(CdmMetaDataPropertyName.DB_SCHEMA_VERSION.getSqlQueryOld());
|
227
|
} catch (Exception e1) {
|
228
|
throw e1;
|
229
|
}
|
230
|
}
|
231
|
String version = null;
|
232
|
if(resultSet.next()){
|
233
|
version = resultSet.getString(1);
|
234
|
} else {
|
235
|
CdmDatabaseException cde = new CdmDatabaseException("Unable to retrieve version info from data source " + dataSource.toString()
|
236
|
+ " - the database may have been corrupted or is not a cdm database");
|
237
|
addErrorMessageToServletContextAttributes(cde.getMessage());
|
238
|
throw cde;
|
239
|
}
|
240
|
|
241
|
connection.close();
|
242
|
|
243
|
if(!CdmMetaData.isDbSchemaVersionCompatible(version)){
|
244
|
/*
|
245
|
* any exception thrown here would be nested into a spring
|
246
|
* BeanException which can not be caught in the servlet
|
247
|
* container, so we post the information into the
|
248
|
* ServletContext
|
249
|
*/
|
250
|
String errorMessage = "Incompatible version [" + (beanName != null ? beanName : jndiName) + "] expected version: " + CdmMetaData.getDbSchemaVersion() + ", data base version " + version;
|
251
|
addErrorMessageToServletContextAttributes(errorMessage);
|
252
|
}
|
253
|
} else {
|
254
|
CdmDatabaseException cde = new CdmDatabaseException("database " + dataSource.toString() + " is empty or not a cdm database");
|
255
|
logger.error(cde.getMessage());
|
256
|
// throw cde; // TODO: No exception was thrown here before. Is this correct behavior or
|
257
|
}
|
258
|
} catch (SQLException e) {
|
259
|
CdmDatabaseException re = new CdmDatabaseException("Unable to connect or to retrieve version info from data source " + dataSource.toString() , e);
|
260
|
addErrorMessageToServletContextAttributes(re.getMessage());
|
261
|
throw re;
|
262
|
} finally {
|
263
|
if(connection != null){
|
264
|
try {
|
265
|
connection.close();
|
266
|
} catch (SQLException e) {
|
267
|
// IGNORE //
|
268
|
}
|
269
|
}
|
270
|
} // END // validate correct schema version
|
271
|
} // END !isForceSchemaCreate()
|
272
|
|
273
|
|
274
|
String forceSchemaUpdate = findProperty(ATTRIBUTE_FORCE_SCHEMA_UPDATE, false);
|
275
|
if(forceSchemaUpdate != null){
|
276
|
if(!isForceSchemaCreate()) {
|
277
|
logger.info("Update of data source requested by property '" + ATTRIBUTE_FORCE_SCHEMA_UPDATE + "'");
|
278
|
CdmUpdater updater = CdmUpdater.NewInstance();
|
279
|
WrappedCdmDataSource cdmDataSource = new WrappedCdmDataSource(dataSource);
|
280
|
updater.updateToCurrentVersion(cdmDataSource, null);
|
281
|
cdmDataSource.closeOpenConnections();
|
282
|
} else {
|
283
|
logger.info("Update of data source requested by property '" + ATTRIBUTE_FORCE_SCHEMA_UPDATE + "' but overwritten by " + ATTRIBUTE_FORCE_SCHEMA_CREATE);
|
284
|
}
|
285
|
}
|
286
|
|
287
|
return dataSource;
|
288
|
}
|
289
|
|
290
|
@Bean
|
291
|
public DataSourceProperties dataSourceProperties(){
|
292
|
if(this.dataSourceProperties == null){
|
293
|
dataSourceProperties = loadDataSourceProperties();
|
294
|
if(dataSourceId == null){
|
295
|
dataSource();
|
296
|
}
|
297
|
dataSourceProperties.setCurrentDataSourceId(dataSourceId);
|
298
|
}
|
299
|
return dataSourceProperties;
|
300
|
}
|
301
|
|
302
|
|
303
|
private DataSource useJndiDataSource(String jndiName) throws NamingException {
|
304
|
logger.info("using jndi datasource '" + jndiName + "'");
|
305
|
|
306
|
JndiObjectFactoryBean jndiFactory = new JndiObjectFactoryBean();
|
307
|
/*
|
308
|
JndiTemplate jndiTemplate = new JndiTemplate();
|
309
|
jndiFactory.setJndiTemplate(jndiTemplate); no need to use a JndiTemplate
|
310
|
if I try using JndiTemplate I get an org.hibernate.AnnotationException: "Unknown Id.generator: system-increment"
|
311
|
when running multiple instances via the Bootloader
|
312
|
*/
|
313
|
jndiFactory.setResourceRef(true);
|
314
|
jndiFactory.setJndiName(jndiName);
|
315
|
try {
|
316
|
jndiFactory.afterPropertiesSet();
|
317
|
} catch (IllegalArgumentException e) {
|
318
|
logger.error(e, e);
|
319
|
} catch (NamingException e) {
|
320
|
logger.error(e, e);
|
321
|
throw e;
|
322
|
}
|
323
|
Object obj = jndiFactory.getObject();
|
324
|
return (DataSource)obj;
|
325
|
}
|
326
|
|
327
|
/**
|
328
|
* Loads the {@link DataSource} bean from the cdm bean definition file.
|
329
|
* This file is usually {@code ./.cdmLibrary/datasources.xml}
|
330
|
*
|
331
|
* @param beanName
|
332
|
* @return
|
333
|
*/
|
334
|
private DataSource loadDataSourceBean(String beanName) {
|
335
|
|
336
|
String beanDefinitionFileFromProperty = findProperty(CDM_BEAN_DEFINITION_FILE, false);
|
337
|
String path = (beanDefinitionFileFromProperty != null ? beanDefinitionFileFromProperty : getBeanDefinitionFile());
|
338
|
logger.info("loading DataSourceBean '" + beanName + "' from: " + path);
|
339
|
FileSystemResource file = new FileSystemResource(path);
|
340
|
XmlBeanFactory beanFactory = new XmlBeanFactory(file);
|
341
|
DataSource dataSource = beanFactory.getBean(beanName, DataSource.class);
|
342
|
if(dataSource instanceof ComboPooledDataSource){
|
343
|
logger.info("DataSourceBean '" + beanName + "' is a ComboPooledDataSource [URL:" + ((ComboPooledDataSource)dataSource).getJdbcUrl()+ "]");
|
344
|
} else {
|
345
|
logger.error("DataSourceBean '" + beanName + "' IS NOT a ComboPooledDataSource");
|
346
|
}
|
347
|
return dataSource;
|
348
|
}
|
349
|
|
350
|
|
351
|
/**
|
352
|
* Loads the <code>dataSourceProperties</code> bean from the cdm bean
|
353
|
* definition file.
|
354
|
* This file is usually {@code ./.cdmLibrary/datasources.xml}
|
355
|
*
|
356
|
* @return the DataSourceProperties bean or an empty instance if the bean is not found
|
357
|
*/
|
358
|
private DataSourceProperties loadDataSourceProperties() {
|
359
|
|
360
|
String beanDefinitionFileFromProperty = findProperty(CDM_BEAN_DEFINITION_FILE, false);
|
361
|
String path = (beanDefinitionFileFromProperty != null ? beanDefinitionFileFromProperty : getBeanDefinitionFile());
|
362
|
logger.info("loading dataSourceProperties from: " + path);
|
363
|
FileSystemResource file = new FileSystemResource(path);
|
364
|
XmlBeanFactory beanFactory = new XmlBeanFactory(file);
|
365
|
DataSourceProperties properties = null;
|
366
|
try {
|
367
|
properties = beanFactory.getBean("dataSourceProperties", DataSourceProperties.class);
|
368
|
} catch (BeansException e) {
|
369
|
logger.warn("bean 'dataSourceProperties' not found");
|
370
|
properties = new DataSourceProperties();
|
371
|
}
|
372
|
return properties;
|
373
|
}
|
374
|
|
375
|
@Bean
|
376
|
public Properties hibernateProperties(){
|
377
|
Properties props = getHibernateProperties();
|
378
|
props.setProperty(HIBERNATE_DIALECT, inferHibernateDialectName());
|
379
|
String searchPath = configFileUtil.getCdmHomeSubDir(ConfigFileUtil.SUBFOLDER_WEBAPP).getPath();
|
380
|
props.setProperty(HIBERNATE_SEARCH_DEFAULT_INDEX_BASE,
|
381
|
searchPath +
|
382
|
"/index/".replace("/", File.separator) +
|
383
|
findProperty(ATTRIBUTE_DATASOURCE_NAME, true));
|
384
|
if(isForceSchemaCreate()) {
|
385
|
props.setProperty("hibernate.hbm2ddl.auto", "create");
|
386
|
}
|
387
|
logger.debug("hibernateProperties: " + props.toString());
|
388
|
return props;
|
389
|
}
|
390
|
|
391
|
private boolean isForceSchemaCreate() {
|
392
|
String propVal = findProperty(ATTRIBUTE_FORCE_SCHEMA_CREATE, false);
|
393
|
logger.debug("System property " + ATTRIBUTE_FORCE_SCHEMA_CREATE + " = " + Objects.toString(propVal, "[NULL]"));
|
394
|
return propVal != null && !(propVal.toLowerCase().equals("false") || propVal.equals("0"));
|
395
|
}
|
396
|
|
397
|
/**
|
398
|
* Returns the full class name of the according {@link org.hibernate.dialect.Dialect} implementation
|
399
|
*
|
400
|
* @param ds the DataSource
|
401
|
* @return the name
|
402
|
*/
|
403
|
public String inferHibernateDialectName() {
|
404
|
DataSource ds = dataSource();
|
405
|
return inferHibernateDialectName(ds);
|
406
|
}
|
407
|
|
408
|
|
409
|
|
410
|
/**
|
411
|
* Returns the full class name of the according {@link org.hibernate.dialect.Dialect} implementation
|
412
|
*
|
413
|
* @param ds the DataSource
|
414
|
* @return the name
|
415
|
*/
|
416
|
public String inferHibernateDialectName(DataSource ds) {
|
417
|
String url = "<SEE PRIOR REFLECTION ERROR>";
|
418
|
Method m = null;
|
419
|
try {
|
420
|
m = ds.getClass().getMethod("getUrl");
|
421
|
} catch (SecurityException e) {
|
422
|
logger.error(e);
|
423
|
} catch (NoSuchMethodException e) {
|
424
|
try {
|
425
|
m = ds.getClass().getMethod("getJdbcUrl");
|
426
|
} catch (SecurityException e2) {
|
427
|
logger.error(e2);
|
428
|
} catch (NoSuchMethodException e2) {
|
429
|
logger.error(e2);
|
430
|
}
|
431
|
}
|
432
|
try {
|
433
|
url = (String)m.invoke(ds);
|
434
|
} catch (IllegalArgumentException e) {
|
435
|
logger.error(e);
|
436
|
} catch (IllegalAccessException e) {
|
437
|
logger.error(e);
|
438
|
} catch (InvocationTargetException e) {
|
439
|
logger.error(e);
|
440
|
} catch (SecurityException e) {
|
441
|
logger.error(e);
|
442
|
}
|
443
|
|
444
|
if(url != null){
|
445
|
if(url.contains(":mysql:")){
|
446
|
// TODO we should switch all databases to InnoDB !
|
447
|
// TODO open jdbc connection to check engine and choose between
|
448
|
// MySQL5MyISAMUtf8Dialect and MySQL5MyISAMUtf8Dialect
|
449
|
// see #3371 (switch cdm to MySQL InnoDB)
|
450
|
return MySQL5MyISAMUtf8Dialect.class.getName();
|
451
|
}
|
452
|
if(url.contains(":h2:")){
|
453
|
return H2CorrectedDialect.class.getName();
|
454
|
}
|
455
|
if(url.contains(":postgresql:")){
|
456
|
return PostgreSQL82Dialect.class.getName();
|
457
|
}
|
458
|
}
|
459
|
|
460
|
logger.error("hibernate dialect mapping for "+url+ " not yet implemented or unavailable");
|
461
|
return null;
|
462
|
}
|
463
|
|
464
|
}
|