Project

General

Profile

Download (7.13 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 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.api.service;
11

    
12
import java.sql.Connection;
13
import java.sql.ResultSet;
14
import java.sql.SQLException;
15
import java.sql.Statement;
16
import java.util.HashMap;
17
import java.util.Map;
18

    
19
import org.apache.log4j.Logger;
20
import org.hibernate.SessionFactory;
21
import org.springframework.beans.BeansException;
22
import org.springframework.beans.factory.annotation.Autowired;
23
import org.springframework.context.ApplicationContext;
24
import org.springframework.context.ApplicationContextAware;
25
import org.springframework.jdbc.datasource.AbstractDriverBasedDataSource;
26
import org.springframework.orm.hibernate5.SessionFactoryUtils;
27
import org.springframework.stereotype.Service;
28
import org.springframework.transaction.annotation.Transactional;
29

    
30
import eu.etaxonomy.cdm.api.application.CdmApplicationController;
31
import eu.etaxonomy.cdm.config.CdmPersistentSourceUtils;
32
import eu.etaxonomy.cdm.config.CdmSourceException;
33
import eu.etaxonomy.cdm.database.CdmDataSource;
34
import eu.etaxonomy.cdm.database.CdmPersistentDataSource;
35
import eu.etaxonomy.cdm.database.DataSourceNotFoundException;
36
import eu.etaxonomy.cdm.database.DatabaseTypeEnum;
37
import eu.etaxonomy.cdm.database.H2Mode;
38
import eu.etaxonomy.cdm.database.ICdmDataSource;
39
import eu.etaxonomy.cdm.model.common.init.TermNotFoundException;
40
import eu.etaxonomy.cdm.model.metadata.CdmMetaData.MetaDataPropertyName;
41

    
42

    
43

    
44
/**
45
 * Implementation of service which provides functionality to directly access database
46
 * related information.
47
 *
48
 * @author a.mueller
49
 *
50
 */
51
@Service
52
@Transactional(readOnly = true)
53
public class DatabaseServiceHibernateImpl  implements IDatabaseService, ApplicationContextAware {
54
	private static final Logger logger = Logger.getLogger(DatabaseServiceHibernateImpl.class);
55

    
56
	private static final String TMP_DATASOURCE = "tmp";
57

    
58
	@Autowired
59
	private SessionFactory factory;
60

    
61
	@Autowired
62
	protected ApplicationContext appContext;
63

    
64
	private CdmApplicationController application;
65

    
66
	@Override
67
    public void setApplicationController(CdmApplicationController cdmApplicationController){
68
		this.application = cdmApplicationController;
69
	}
70

    
71
	@Override
72
    public boolean connectToDatasource(CdmPersistentDataSource dataSource) throws TermNotFoundException{
73
		this.application.changeDataSource(dataSource);
74
		logger.debug("DataSource changed to " + dataSource.getName());
75
		return true;
76
	}
77

    
78
	@Override
79
    public boolean connectToDatabase(DatabaseTypeEnum databaseTypeEnum, String server,
80
			String database, String username, String password, int port, String filePath, H2Mode mode) throws TermNotFoundException  {
81
		ICdmDataSource dataSource = CdmDataSource.NewInstance(databaseTypeEnum, server, database, port, username, password);
82
		CdmPersistentDataSource tmpDataSource =  saveDataSource(TMP_DATASOURCE, dataSource);
83
		boolean result = connectToDatasource(tmpDataSource);
84
		CdmPersistentSourceUtils.delete(tmpDataSource);
85
		return result;
86
	}
87

    
88
	@Override
89
    public boolean connectToDatabase(DatabaseTypeEnum databaseTypeEnum, String server,
90
			String database, String username, String password)  throws TermNotFoundException {
91
		return connectToDatabase(databaseTypeEnum, server, database, username, password, databaseTypeEnum.getDefaultPort(), null, null) ;
92
	}
93

    
94
	@Override
95
    public CdmPersistentDataSource saveDataSource(String strDataSourceName,
96
			ICdmDataSource dataSource) {
97
		return CdmPersistentDataSource.save(strDataSourceName, dataSource);
98
	}
99

    
100
	@Override
101
    public CdmPersistentDataSource updateDataSource(String strDataSourceName,
102
			CdmPersistentDataSource dataSource) throws DataSourceNotFoundException {
103
		return CdmPersistentDataSource.update(strDataSourceName, dataSource);
104
	}
105

    
106
	@Override
107
    public String getUrl() {
108
		return getDataSource().getUrl();
109
	}
110

    
111
	@Override
112
    public String getUsername() {
113
		return getDataSource().getUsername();
114
	}
115

    
116
	/**
117
	 * Returns the AbstractDriverBasedDataSource from hibernate,
118
	 * generalized in order to also allow using SimpleDriverDataSource.
119
	 *
120
	 * @return the AbstractDriverBasedDataSource from the hibernate layer
121
	 */
122
	private AbstractDriverBasedDataSource getDataSource(){
123
		AbstractDriverBasedDataSource ds = (AbstractDriverBasedDataSource)SessionFactoryUtils.getDataSource(factory);
124
		return ds;
125
	}
126

    
127
	@Override
128
    public void setApplicationContext(ApplicationContext applicationContext)
129
			throws BeansException {
130
		this.appContext = applicationContext;
131
	}
132

    
133
	@Override
134
	public  String getDbSchemaVersion() throws CdmSourceException  {
135
		try {
136
			return (String)getSingleValue(MetaDataPropertyName.DB_SCHEMA_VERSION.getSqlQuery());
137
		} catch (SQLException e) {
138
			throw new CdmSourceException(e.getMessage());
139
		}
140
	}
141

    
142
	@Override
143
	public boolean isDbEmpty() throws CdmSourceException {
144
		// Any CDM DB should have a schema version
145
		String dbSchemaVersion = getDbSchemaVersion();
146
		return (dbSchemaVersion == null || dbSchemaVersion.equals(""));
147
	}
148

    
149
    /**
150
     * Execute a SQL query which returns a single value
151
     *
152
     * @param query , which returns a single value
153
     * @return
154
     * @throws SQLException
155
     */
156
    private Object getSingleValue(String query) throws SQLException {
157
        String queryString = query == null? "(null)": query;
158
        //ResultSet resultSet = executeQuery(query);
159
        ResultSet resultSet = null;
160

    
161
        Connection connection = SessionFactoryUtils.getDataSource(factory).getConnection();
162
        if (connection != null){
163

    
164
            Statement statement = connection.createStatement();
165
            resultSet = statement.executeQuery(query);
166

    
167
            if (resultSet == null || resultSet.next() == false){
168
                logger.info("No record returned for query " +  queryString);
169
                return null;
170
            }
171
            if (resultSet.getMetaData().getColumnCount() != 1){
172
                logger.info("More than one column selected in query" +  queryString);
173
                //first value will be taken
174
            }
175
            Object object = resultSet.getObject(1);
176
            if (resultSet.next()){
177
                logger.info("Multiple results for query " +  queryString);
178
                //first row will be taken
179
            }
180
            // making sure we close all resources so we don't run out of
181
            // connections in the connection pool
182
            resultSet.close();
183
            statement.close();
184
            connection.close();
185

    
186
            return object;
187
        }else{
188
            throw new RuntimeException("Could not establish connection to database");
189
        }
190

    
191
    }
192

    
193

    
194
	@Override
195
	public Map<MetaDataPropertyName, String> getCdmMetadataMap() throws CdmSourceException {
196
		Map<MetaDataPropertyName, String> cdmMetaDataMap = new HashMap<MetaDataPropertyName, String>();
197

    
198
		for(MetaDataPropertyName mdpn : MetaDataPropertyName.values()){
199
			String value = null;
200
			try {
201
				value = (String)getSingleValue(mdpn.getSqlQuery());
202
			} catch (SQLException e) {
203
				throw new CdmSourceException(e.getMessage());
204
			}
205
			if(value != null) {
206
				cdmMetaDataMap.put(mdpn, value);
207
			}
208
		}
209
		return cdmMetaDataMap;
210
	}
211

    
212
}
(10-10/99)