e9abec031477e0d1329f0d26dd1f16acab12351d
[taxeditor.git] / taxeditor-store / src / main / java / eu / etaxonomy / taxeditor / store / CdmStore.java
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.taxeditor.store;
11
12 import java.util.ArrayList;
13 import java.util.LinkedHashMap;
14 import java.util.List;
15 import java.util.UUID;
16
17 import javax.security.auth.spi.LoginModule;
18
19 import org.apache.log4j.Logger;
20 import org.springframework.security.Authentication;
21 import org.springframework.security.context.SecurityContextHolder;
22 import org.springframework.security.providers.ProviderManager;
23 import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
24
25 import eu.etaxonomy.cdm.api.application.CdmApplicationController;
26 import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
27 import eu.etaxonomy.cdm.api.service.ILocationService;
28 import eu.etaxonomy.cdm.api.service.INameService;
29 import eu.etaxonomy.cdm.api.service.IReferenceService;
30 import eu.etaxonomy.cdm.api.service.ITaxonService;
31 import eu.etaxonomy.cdm.api.service.IUserService;
32 import eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator;
33 import eu.etaxonomy.cdm.api.service.config.impl.TaxonServiceConfiguratorImpl;
34 import eu.etaxonomy.cdm.database.DbSchemaValidation;
35 import eu.etaxonomy.cdm.database.ICdmDataSource;
36 import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
37 import eu.etaxonomy.cdm.model.common.Language;
38 import eu.etaxonomy.cdm.model.common.User;
39 import eu.etaxonomy.cdm.model.name.TaxonNameBase;
40 import eu.etaxonomy.cdm.model.reference.Article;
41 import eu.etaxonomy.cdm.model.reference.Book;
42 import eu.etaxonomy.cdm.model.reference.BookSection;
43 import eu.etaxonomy.cdm.model.reference.Generic;
44 import eu.etaxonomy.cdm.model.reference.ReferenceBase;
45 import eu.etaxonomy.cdm.model.taxon.Taxon;
46 import eu.etaxonomy.cdm.model.taxon.TaxonomicTree;
47 import eu.etaxonomy.cdm.persistence.query.MatchMode;
48 import eu.etaxonomy.taxeditor.datasource.CdmDataSourceRepository;
49 import eu.etaxonomy.taxeditor.model.TaxeditorLoginModule;
50 import eu.etaxonomy.taxeditor.user.AuthenticatedUserBar;
51
52 /**
53 * This implementation of ICdmDataRepository depends on hibernate sessions to store the data correctly
54 * for the current session. No state is held in this class.
55 *
56 * Only methods that either get or manipulate data are exposed here. So this class acts as a facade
57 * for the methods in cdmlib-service.
58 *
59 *
60 * @author n.hoffmann
61 * @created 17.03.2009
62 * @version 1.0
63 */
64 public class CdmStore{
65 private static final Logger logger = Logger.getLogger(CdmStore.class);
66
67 // FIXME change this to ClassPathResources as soon as it is included into the plugin
68 private static String DEFAULT_APPLICATION_CONTEXT = null;
69 private static DbSchemaValidation DEFAULT_DB_SCHEMA_VALIDATION = DbSchemaValidation.UPDATE;
70
71 private static CdmStore instance;
72
73 private CdmApplicationController applicationController;
74
75 private ConversationHolder globalReadOnlyConversation;
76
77 private static DbSchemaValidation dbSchemaValidation;
78
79 private static LoginModule loginModule;
80
81 /**
82 *
83 * @return
84 */
85 public static CdmStore getDefault(){
86 return getDefault(DEFAULT_APPLICATION_CONTEXT);
87 }
88
89 /**
90 *
91 * @param applicationContextBean
92 * @return
93 */
94 public static CdmStore getDefault(String applicationContextBean){
95 if(instance == null){
96 logger.info("Initializing application context ...");
97 ICdmDataSource cdmDatasource = CdmDataSourceRepository.getDefault().
98 getCurrentDataSource();
99
100 instance = new CdmStore(cdmDatasource, getDbSchemaValidation(), applicationContextBean);
101
102 logger.info("Application context initialized.");
103 }
104 return instance;
105 }
106
107 /**
108 * @return
109 */
110 private static DbSchemaValidation getDbSchemaValidation() {
111 return (dbSchemaValidation == null) ? DEFAULT_DB_SCHEMA_VALIDATION : dbSchemaValidation;
112 }
113
114 /**
115 *
116 */
117 private CdmStore(ICdmDataSource dataSource, DbSchemaValidation dbSchemaValidation, String applicationContextBean) {
118 // TODO application context bean is not honored by application controller at the moment.
119 // cdmDefaultApplicationController bean gets loaded per default always.
120
121 try {
122 CdmStore.DEFAULT_APPLICATION_CONTEXT = applicationContextBean;
123 // applicationController = CdmApplicationController.NewInstance(applicationContextBean, dataSource, dbSchemaValidation, false);
124
125 // logger.warn("OMITTING TERM LOADING FOR DEBUGGING");
126 // applicationController = CdmApplicationController.NewInstance(dataSource, dbSchemaValidation, true);
127 applicationController = CdmApplicationController.NewInstance(dataSource, dbSchemaValidation);
128 } catch (Exception e) {
129 throw new RuntimeException(e);
130 }
131 }
132
133
134 public ReferenceBase<?> getDefaultSec() {
135 // TODO why is this returning null? and of course, replace w the real deal
136 return applicationController.getReferenceService().getReferenceByUuid(
137 UUID.fromString("f3593c18-a8d2-4e51-bdad-0befbf8fb2d1"));
138 }
139
140 /**
141 * @deprecated use taxonomic tree instead
142 */
143 public List<Taxon> getRootTaxa() {
144 boolean onlyWithChildren = false;
145 boolean withMisapplications = true;
146
147 return applicationController.getTaxonService().getRootTaxa(
148 getDefaultSec(), onlyWithChildren, withMisapplications);
149 }
150
151 /**
152 * @return
153 */
154 public List<TaxonomicTree> getTaxonomicTrees() {
155 return applicationController.getTaxonService().listTaxonomicTrees(null, null, null, null);
156 }
157
158
159 private CdmApplicationController getApplicationControllerInternal(){
160 return applicationController;
161 }
162
163 public static CdmApplicationController getApplicationController(){
164 return getDefault().getApplicationControllerInternal();
165 }
166
167
168 /**
169 * Create a new conversation and bind resources to it
170 *
171 * @return
172 */
173 public static ConversationHolder NewConversation(){
174
175 CdmStore store = getDefault();
176 CdmApplicationController controller = store.getApplicationController();
177
178 ConversationHolder conversation = controller.NewConversation();
179
180 return conversation;
181 }
182
183 /**
184 * Creates a new conversation, binds resources to the conversation and
185 * start a transaction for this conversation.
186 *
187 * @return
188 */
189 public static ConversationHolder NewTransactionalConversation() {
190 ConversationHolder conversation = NewConversation();
191
192 conversation.startTransaction();
193 return conversation;
194 }
195
196
197 private ConversationHolder getGlobalReadOnlyConversation() {
198 ConversationHolder conversation = globalReadOnlyConversation == null
199 ? NewConversation()
200 : globalReadOnlyConversation;
201 conversation.bind();
202 return conversation;
203 }
204
205 public static ConversationHolder getGlobalConversation(){
206 return getDefault().getGlobalReadOnlyConversation();
207 }
208
209
210 /*
211 * EXPOSING SERVICES
212 */
213
214 public static ITaxonService getTaxonService(){ return getDefault().getApplicationControllerInternal().getTaxonService();}
215
216 public static INameService getNameService(){ return getDefault().getApplicationControllerInternal().getNameService();}
217
218 public static IReferenceService getReferenceService(){ return getDefault().getApplicationControllerInternal().getReferenceService();}
219
220 public static ILocationService getLocationService(){ return getDefault().getApplicationControllerInternal().getLocationService();}
221
222 public static ProviderManager getAuthenticationManager() { return getDefault().getApplicationControllerInternal().getAuthenticationManager();}
223
224 public static IUserService getUserService() { return getDefault().getApplicationControllerInternal().getUserService(); }
225
226 /**
227 * @param searchText
228 * @return
229 */
230 @SuppressWarnings("unchecked")
231 public static List<TaxonNameBase> searchNameString(String searchText) {
232 List<TaxonNameBase> resultSet = new ArrayList<TaxonNameBase>();
233 resultSet.addAll(getNameService()
234 .getNamesByName(searchText.replace("*", "%")));
235 return resultSet;
236 }
237
238 private List<IdentifiableEntity> findTaxaByName(String queryString, boolean restrictToTaxonObjs) {
239
240 ITaxonServiceConfigurator configurator = new TaxonServiceConfiguratorImpl();
241
242 configurator.setSearchString(queryString.trim());
243 configurator.setDoTaxa(true);
244 configurator.setMatchMode(MatchMode.BEGINNING);
245 if (restrictToTaxonObjs) {
246 configurator.setDoNamesWithoutTaxa(false);
247 configurator.setDoSynonyms(false);
248 } else {
249 configurator.setDoNamesWithoutTaxa(true);
250 configurator.setDoSynonyms(true);
251 }
252 configurator.setSec(null);
253 configurator.setPageNumber(0);
254 // TODO currently limit results to 1000
255 configurator.setPageSize(1000);
256
257 List<IdentifiableEntity> result = getTaxonService().findTaxaAndNames(configurator).getRecords();
258
259 return result;
260 }
261
262 public static List<IdentifiableEntity> searchTaxaByName(String queryString){
263 return getDefault().findTaxaByName(queryString, false);
264 }
265
266 public static List<IdentifiableEntity> searchTaxaByName(String queryString, boolean restrictToTaxonObjs){
267 return getDefault().findTaxaByName(queryString, restrictToTaxonObjs);
268 }
269
270 /**
271 * Searches for references by string. "%" is used as a wildcard.
272 *
273 * @param text
274 * @return
275 */
276 public static List<ReferenceBase> getReferencesByTitle(String reference) {
277
278 reference = reference.replace("*", "%");
279 List<ReferenceBase> resultsList = null;
280 try {
281 resultsList = getReferenceService().getReferencesByTitle(reference);
282 } catch (RuntimeException e) {
283 // MessageDialog.openError(GlobalController.getShell(), "Search reference error",
284 // "Reference search returned an error. This could be a Hibernate concurrency problem. " +
285 // "Please try saving your work, then searching again.");
286 e.printStackTrace();
287 }
288 return resultsList;
289 }
290
291 /**
292 * FIXME mock
293 *
294 * @return
295 */
296 public static Language getDefaultLanguage(){
297 return Language.ENGLISH();
298 }
299
300 /**
301 * @return
302 */
303 public static LinkedHashMap<Class<?>, String> getReferenceTypes() {
304 LinkedHashMap<Class<?>, String> nomReferenceTypeMap = new LinkedHashMap<Class<?>, String>();
305
306 // referenceTypeMap.put(BibtexReference.class, "BibTeX Reference");
307 nomReferenceTypeMap.put(Article.class, "Article");
308 nomReferenceTypeMap.put(Generic.class, "Generic");
309 nomReferenceTypeMap.put(Book.class, "Book");
310 nomReferenceTypeMap.put(BookSection.class, "Book Section");
311
312 return nomReferenceTypeMap;
313 }
314
315 /**
316 * TODO implement LoginModule to handle the whole login stuff
317 *
318 * @param token
319 */
320 public static void authenticate(UsernamePasswordAuthenticationToken token){
321 Authentication authentication = CdmStore.getAuthenticationManager().authenticate(token);
322 SecurityContextHolder.getContext().setAuthentication(authentication);
323
324 // TODO register a listener on LoginModule instead of calling a set method here
325 // AuthenticatedUserBar.setAuthenticatedUser(getAuthenticatedUser().getUsername());
326 }
327
328 public static User getAuthenticatedUser(){
329 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
330
331 if(authentication != null
332 && authentication.getPrincipal() != null
333 && authentication.getPrincipal() instanceof User){
334 return (User)authentication.getPrincipal();
335 }
336 return null;
337 }
338
339 /**
340 * incomplete! do note use!
341 */
342 public static LoginModule getLoginModule(){
343 if(loginModule == null){
344 loginModule = new TaxeditorLoginModule();
345 }
346 return loginModule;
347 }
348 }