Salome HOME
Show URLs for previous versions of the document's files.
[tools/siman.git] / Workspace / Siman / src / org / splat / simer / AbstractSearchBaseAction.java
1 package org.splat.simer;
2
3 import java.text.SimpleDateFormat;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.Iterator;
7 import java.util.LinkedHashMap;
8 import java.util.List;
9 import java.util.Map;
10
11 import org.splat.dal.bo.kernel.User;
12 import org.splat.dal.bo.som.SimulationContext;
13 import org.splat.dal.bo.som.SimulationContextType;
14 import org.splat.kernel.InvalidPropertyException;
15 import org.splat.kernel.Name;
16 import org.splat.service.SimulationContextService;
17 import org.splat.service.UserService;
18 import org.splat.service.dto.Proxy;
19 import org.splat.service.dto.SearchFilterDTO;
20 import org.splat.service.technical.ProjectSettingsService;
21 import org.splat.som.ApplicationRights;
22 import org.splat.wapp.Constants;
23
24 /**
25  * Base search action class used for searching studies and knowledge.
26  * 
27  * @param <FilterClass>
28  *            search filter class
29  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
30  */
31 public abstract class AbstractSearchBaseAction<FilterClass extends SearchFilterDTO>
32                 extends Action {
33
34         /**
35          * Serial version ID.
36          */
37         private static final long serialVersionUID = 7863055790228544510L;
38         /**
39          * Search result key in the session.
40          */
41         public static final String RESULT_KEY = "search.result";
42         /**
43          * Context type index, when selected.
44          */
45         protected transient String _ctype = null;
46         /**
47          * Context value index, when selected.
48          */
49         protected transient String _cvalue = null;
50         /**
51          * Context index, when removed.
52          */
53         protected transient String _cindex = "";
54         /**
55          * Search criteria.
56          */
57         private FilterClass _filter;
58         /**
59          * List of users who can create studies.
60          */
61         protected List<Name> _candidates = null;
62         /**
63          * Context type to be valued.
64          */
65         protected transient SimulationContextType _newtype;
66         /**
67          * Context value to be selected.
68          */
69         protected transient List<SimulationContext> _newvalue;
70         /**
71          * Addable context types.
72          */
73         protected transient List<SimulationContextType> _critext;
74         /**
75          * List of found objects.
76          */
77         protected transient List<Proxy> _result;
78         /**
79          * Injected simulation context service.
80          */
81         private SimulationContextService _simulationContextService;
82
83         /**
84          * Injected user service.
85          */
86         private UserService _userService;
87
88         /**
89          * Search action modes enumeration.
90          */
91         enum UserAction {
92                 refreshResult, selectContextType, selectContextValue, cancelSelect, removeContext
93         }
94
95         // ==============================================================================================================================
96         // Action methods
97         // ==============================================================================================================================
98
99         /**
100          * Perform actions according to the current mode.
101          * 
102          * @return action result or ERROR if failed
103          */
104         public String doSubmitForm() {
105                 // Identification of the user action
106                 UserAction action = UserAction.refreshResult;
107                 if (_ctype != null && Integer.valueOf(_ctype) > 0) {
108                         action = UserAction.selectContextType;
109                 } else if (_cvalue != null && Integer.valueOf(_cvalue) > 0) {
110                         action = UserAction.selectContextValue;
111                 } else if (_cindex.length() > 0) {
112                         long index = Long.valueOf(_cindex);
113                         if (index > 0) {
114                                 action = UserAction.removeContext;
115                         } else if (index < 0) {
116                                 action = UserAction.cancelSelect;
117                         }
118                 }
119                 // Execution of the user action
120                 String done;
121                 try {
122                         saveFilter(); // Also reinitializes the form, if needed
123
124                         if (action == UserAction.selectContextType) {
125                                 done = doSelectContextType();
126                         } else if (action == UserAction.selectContextValue) {
127                                 done = doAddContext();
128                         } else if (action == UserAction.removeContext) {
129                                 done = doRemoveContext();
130                         } else if (action == UserAction.cancelSelect) {
131                                 done = doCancel();
132                         } else { // UserAction.refreshResult
133                                 done = doSearch();
134                                 setContextTypeOptions(getInvolvedContexts()); // Done in other do functions, when required
135                         }
136                         setCandidates();
137                 } catch (Exception error) {
138                         // No need to roll back the transaction as it is read only
139                         LOG.error("Reason: ", error);
140                         done = ERROR;
141                 }
142                 return done;
143         }
144
145         /**
146          * Add a selected context type to the search filter. Obsolete the current result if necessary.
147          * 
148          * @return "selectype"
149          */
150         @SuppressWarnings(Constants.UNCHECKED)
151         protected String doSelectContextType() {
152                 SimulationContext.Properties sprop = new SimulationContext.Properties();
153
154                 _newtype = getSimulationContextService().selectType(
155                                 Integer.valueOf(_ctype));
156                 _newvalue = getSimulationContextService()
157                                 .selectSimulationContextsWhere(sprop.setType(_newtype));
158                 if (_cindex.length() > 0 && Long.valueOf(_cindex) == 0) {
159                         getSession().remove(RESULT_KEY);
160                 } else {
161                         // We keep the previous result search, if valid
162                         _result = (List<Proxy>) getSession().get(RESULT_KEY);
163                 }
164                 setActionType("setContext");
165                 return "selectype";
166         }
167
168         /**
169          * Add a selected context to the search filter. Obsolete the current result.
170          * 
171          * @return "refresh"
172          */
173         protected String doAddContext() {
174                 SimulationContext selected = getSimulationContextService()
175                                 .selectSimulationContext(Integer.valueOf(_cvalue));
176
177                 getFilter().getSimContexts().add(selected);
178                 setContextTypeOptions(getInvolvedContexts()); // Sets critext
179                 getSession().remove(RESULT_KEY); // The current result is obsolete
180                 return "refresh";
181         }
182
183         /**
184          * Remove context from the search filter.
185          * 
186          * @return "refresh"
187          */
188         protected String doRemoveContext() {
189                 long index = Long.valueOf(_cindex);
190                 for (Iterator<SimulationContext> selected = getFilter()
191                                 .getSimContexts().iterator(); selected.hasNext();) {
192                         if (selected.next().getIndex() == index) {
193                                 selected.remove();
194                                 break;
195                         }
196                 }
197                 setContextTypeOptions(getInvolvedContexts()); // Sets critext
198                 getSession().remove(RESULT_KEY); // The current result is obsolete
199                 return "refresh";
200         }
201
202         /**
203          * Cancel simulation context selection.
204          * 
205          * @return "refresh"
206          */
207         @SuppressWarnings(Constants.UNCHECKED)
208         protected String doCancel() {
209                 _result = (List<Proxy>) getSession().get(RESULT_KEY); // Current result search
210                 setContextTypeOptions(getInvolvedContexts()); // Sets critext
211                 return "refresh";
212         }
213
214         // ==============================================================================================================================
215         // Getters
216         // ==============================================================================================================================
217
218         /**
219          * Get date format string.
220          * 
221          * @return date format string
222          */
223         public String getFormat() {
224                 return getText("date.format");
225         }
226
227         /**
228          * Get formatted today date as a string.
229          * 
230          * @return current date as a string
231          */
232         public String getToday() {
233                 SimpleDateFormat tostring = new SimpleDateFormat(getFormat(),
234                                 getApplicationSettings().getCurrentLocale());
235                 return tostring.format(java.util.Calendar.getInstance().getTime());
236         }
237
238         /**
239          * Get search result state.
240          * 
241          * @return "obsolete" if there is no results in the session, otherwise "uptodate"
242          */
243         public String getResultState() {
244                 String result;
245                 if (getSession().get(RESULT_KEY) == null) {
246                         result = "obsolete";
247                 } else {
248                         result = "uptodate";
249                 }
250                 return result;
251         }
252
253         public List<Name> getCandidates() {
254                 return _candidates;
255         }
256
257         public List<SimulationContextType> getContextTypeOptions() {
258                 return _critext;
259         }
260
261         public List<SimulationContext> getContextValueOptions() {
262                 return _newvalue;
263         }
264
265         public SimulationContextType getSelectedContextType() {
266                 return _newtype;
267         }
268
269         /**
270          * Get list of found objects.
271          * 
272          * @return list of found objects
273          */
274         public List<Proxy> getResult() {
275                 return _result;
276         }
277
278         // ==============================================================================================================================
279         // Setters
280         // ==============================================================================================================================
281
282         /**
283          * Set applied simulation context type id to search.
284          * 
285          * @param type
286          *            persistent simulation context type id
287          */
288         public void setContextType(final String type) {
289                 this._ctype = type;
290         }
291
292         /**
293          * Set value of simulation context to search.
294          * 
295          * @param value
296          *            the simulation context value
297          */
298         public void setContextValue(final String value) {
299                 this._cvalue = value;
300         }
301
302         /**
303          * Set simulation context value id.
304          * 
305          * @param value
306          *            the persistent id as string
307          */
308         public void setContextIndex(final String value) {
309                 this._cindex = value;
310         }
311
312         /**
313          * Build the list of study authors. If the current user also can create <BR>
314          * a study then it is placed on the top of the list.
315          */
316         protected void setCandidates() {
317                 _candidates = new ArrayList<Name>();
318                 List<User> users = getUserService().selectAllUsers();
319                 User me = getConnectedUser(); // May be null
320                 for (Iterator<User> i = users.iterator(); i.hasNext();) {
321                         User next = i.next();
322                         ApplicationRights he = new ApplicationRights(next);
323                         if (he.canCreateStudy()) {
324                                 if (next.equals(me)) {
325                                         _candidates.add(0, new ValidationFacade.ByManager(me,
326                                                         getApplicationSettings().getCurrentLocale()));
327                                 } else {
328                                         _candidates.add(next);
329                                 }
330                         }
331                 }
332         }
333
334         /**
335          * Build available context types list with localized names.
336          * 
337          * @param critext
338          *            context types already used in the search filter
339          */
340         protected void setContextTypeOptions(
341                         final List<SimulationContextType> critext) {
342                 for (SimulationContext ctx : getFilter().getSimContexts()) {
343                         critext.remove(ctx.getType()); // Already used context type
344                 }
345                 // Ordering by alphabetical order of localized context types
346                 SimulationContextType[] types = critext
347                                 .toArray(new SimulationContextType[critext.size()]);
348                 ContextTypeComparator compare = new ContextTypeComparator();
349                 ProjectSettingsService.Step step = getSimulationContextService()
350                                 .getAttachedStep(types[0]);
351                 int from = 0;
352                 int to = 0;
353                 while (to < types.length - 1) {
354                         to += 1;
355                         if (!types[to].isAttachedTo(step)) {
356                                 if (to > from + 1) {
357                                         Arrays.sort(types, from, to, compare);
358                                 }
359                                 from = to;
360                                 step = getSimulationContextService().getAttachedStep(types[to]);
361                         }
362                 }
363                 if (to > from) {
364                         Arrays.sort(types, from, to + 1, compare);
365                 }
366                 this._critext = Arrays.asList(types);
367         }
368
369         /**
370          * Load the search filter. The filter is taken from the session by its name.
371          * 
372          * @see #getFilterName()
373          * @return the loaded filter
374          */
375         @SuppressWarnings(Constants.UNCHECKED)
376         protected Map<String, Object> loadFilter() {
377                 Map<String, Object> filter = (Map<String, Object>) getSession().get(
378                                 getFilterName()); // A default filter is supposed being set at start
379
380                 setFilter((FilterClass) filter.get("criteria"));
381                 return filter;
382         }
383
384         /**
385          * Save search criteria in the session as a map with the defined name.
386          * 
387          * @see #getFilterName()
388          * @return the saved filter
389          */
390         @SuppressWarnings(Constants.UNCHECKED)
391         protected Map<String, Object> saveFilter() {
392                 Map<String, Object> filter = (Map<String, Object>) getSession().get(
393                                 getFilterName()); // A default filter is supposed being set at start
394
395                 FilterClass savedCriteria = (FilterClass) filter.get("criteria");
396                 FilterClass newCriteria = getFilter();
397                 if (savedCriteria != null) {
398                         // Only contexts are not part of the form so keep them between requests
399                         newCriteria.setSimContexts(savedCriteria.getSimContexts());
400                 }
401
402                 filter.put("criteria", getFilter());
403                 return filter;
404         }
405
406         // ==============================================================================================================================
407         // Abstract services
408         // ==============================================================================================================================
409
410         /**
411          * Search objects according to the given criteria.
412          * 
413          * @return string result key
414          * @throws InvalidPropertyException
415          *             if some criteria values are incorrect
416          */
417         protected abstract String doSearch() throws InvalidPropertyException;
418
419         /**
420          * List of context types available for filtering.
421          * 
422          * @return list of simulation context types
423          */
424         protected abstract List<SimulationContextType> getInvolvedContexts();
425
426         /**
427          * Get the name of the search criteria filter saved as a map of objects in the session.
428          * 
429          * @return the search filter name in the session
430          */
431         protected abstract String getFilterName();
432
433         /**
434          * Get search filter implementation.
435          * 
436          * @return the search filter
437          */
438         protected abstract FilterClass getNewFilter();
439
440         // ==============================================================================================================================
441         // Getters and Setters
442         // ==============================================================================================================================
443
444         /**
445          * Get match options.
446          * 
447          * @return array of options with key and value properties
448          */
449         public Map<String, String> getMatchOptions() {
450                 Map<String, String> options = new LinkedHashMap<String, String>();
451                 options.put("all", getText("field.matchall"));
452                 options.put("any", getText("field.matchany"));
453                 return options;
454         }
455
456         /**
457          * Get the simulationContextService.
458          * 
459          * @return the simulationContextService
460          */
461         public SimulationContextService getSimulationContextService() {
462                 return _simulationContextService;
463         }
464
465         /**
466          * Set the simulationContextService.
467          * 
468          * @param simulationContextService
469          *            the simulationContextService to set
470          */
471         public void setSimulationContextService(
472                         final SimulationContextService simulationContextService) {
473                 _simulationContextService = simulationContextService;
474         }
475
476         /**
477          * Get the userService.
478          * 
479          * @return the userService
480          */
481         public UserService getUserService() {
482                 return _userService;
483         }
484
485         /**
486          * Set the userService.
487          * 
488          * @param userService
489          *            the userService to set
490          */
491         public void setUserService(final UserService userService) {
492                 _userService = userService;
493         }
494
495         /**
496          * Get the filter.
497          * 
498          * @return the filter
499          */
500         public FilterClass getFilter() {
501                 if (_filter == null) {
502                         _filter = getNewFilter();
503                 }
504                 return _filter;
505         }
506
507         /**
508          * Set the filter.
509          * 
510          * @param filter
511          *            the filter to set
512          */
513         public void setFilter(final FilterClass filter) {
514                 if (filter == null) {
515                         _filter = getNewFilter();
516                 } else {
517                         _filter = filter;
518                 }
519         }
520 }