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