Salome HOME
Fix for mantis #0022060: Cannot Promote a document: update the popup menu after impor...
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / StudyServiceImpl.java
1 /*****************************************************************************
2  * Company         OPEN CASCADE
3  * Application     SIMAN
4  * File            Id: 
5  * Creation date   02.10.2012
6  * @author         Author: Maria KRUCHININA
7  * @version        Revision: 
8  *****************************************************************************/
9
10 package org.splat.service;
11
12 import java.io.IOException;
13 import java.text.DecimalFormat;
14 import java.text.SimpleDateFormat;
15 import java.util.Calendar;
16 import java.util.Collections;
17 import java.util.Date;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22
23 import org.hibernate.criterion.Restrictions;
24 import org.splat.dal.bo.kernel.Relation;
25 import org.splat.dal.bo.kernel.User;
26 import org.splat.dal.bo.som.ActorRelation;
27 import org.splat.dal.bo.som.ContributorRelation;
28 import org.splat.dal.bo.som.DescriptionAttribute;
29 import org.splat.dal.bo.som.DocumentType;
30 import org.splat.dal.bo.som.IDBuilder;
31 import org.splat.dal.bo.som.KnowledgeElement;
32 import org.splat.dal.bo.som.ProgressState;
33 import org.splat.dal.bo.som.Publication;
34 import org.splat.dal.bo.som.Scenario;
35 import org.splat.dal.bo.som.SimulationContext;
36 import org.splat.dal.bo.som.Study;
37 import org.splat.dal.bo.som.ValidationCycle;
38 import org.splat.dal.bo.som.ValidationCycleRelation;
39 import org.splat.dal.bo.som.ValidationStep;
40 import org.splat.dal.bo.som.Visibility;
41 import org.splat.dal.bo.som.Study.Properties;
42 import org.splat.dal.bo.som.ValidationCycle.Actor;
43 import org.splat.dal.dao.som.IDBuilderDAO;
44 import org.splat.dal.dao.som.ScenarioDAO;
45 import org.splat.dal.dao.som.StudyDAO;
46 import org.splat.dal.dao.som.ValidationCycleDAO;
47 import org.splat.kernel.InvalidPropertyException;
48 import org.splat.kernel.MissedPropertyException;
49 import org.splat.kernel.MultiplyDefinedException;
50 import org.splat.log.AppLogger;
51 import org.splat.service.technical.IndexService;
52 import org.splat.service.technical.ProjectSettingsService;
53 import org.splat.service.technical.ProjectSettingsServiceImpl;
54 import org.splat.som.Revision;
55 import org.springframework.transaction.annotation.Transactional;
56
57 /**
58  * This class defines all methods for creation, modification the study.
59  * 
60  * @author Maria KRUCHININA
61  * 
62  */
63 public class StudyServiceImpl implements StudyService {
64
65         /**
66          * logger for the service.
67          */
68         public final static AppLogger LOG = AppLogger
69                         .getLogger(StudyServiceImpl.class);
70
71         /**
72          * Injected index service.
73          */
74         private IndexService _indexService;
75
76         /**
77          * Injected step service.
78          */
79         private StepService _stepService;
80
81         /**
82          * Injected project service.
83          */
84         private ProjectSettingsService _projectSettingsService;
85
86         /**
87          * Injected project element service.
88          */
89         private ProjectElementService _projectElementService;
90
91         /**
92          * Injected study DAO.
93          */
94         private StudyDAO _studyDAO;
95
96         /**
97          * Injected scenario DAO.
98          */
99         private ScenarioDAO _scenarioDAO;
100
101         /**
102          * Injected validation cycle DAO.
103          */
104         private ValidationCycleDAO _validationCycleDAO;
105
106         /**
107          * Injected IDBuilder DAO.
108          */
109         private IDBuilderDAO _iDBuilderDAO;
110
111         /**
112          * Injected document type service.
113          */
114         private DocumentTypeService _documentTypeService;
115
116         /**
117          * Injected user service.
118          */
119         private UserService _userService;
120
121         /**
122          * {@inheritDoc}
123          * 
124          * @see org.splat.service.StudyService#selectStudy(long)
125          */
126         @Transactional
127         public Study selectStudy(final long index) {
128                 Study result = getStudyDAO().get(index);
129                 loadWorkflow(result);
130                 return result;
131         }
132
133         /**
134          * Get study by its reference.
135          * 
136          * @param refid
137          *            the study reference
138          * @return found study or null
139          */
140         @Transactional(readOnly = true)
141         public Study selectStudy(final String refid) {
142                 Study result = getStudyDAO().findByCriteria(
143                                 Restrictions.eq("sid", refid));
144                 loadWorkflow(result);
145                 return result;
146         }
147
148         /**
149          * {@inheritDoc}
150          * 
151          * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
152          */
153         @Transactional
154         public Study createStudy(final Study.Properties sprop)
155                         throws MissedPropertyException, InvalidPropertyException,
156                         MultiplyDefinedException {
157                 sprop.setReference(getProjectSettings().getReferencePattern());
158                 Study study = new Study(sprop);
159
160                 buildReference(study);
161                 getStudyDAO().create(study);
162                 try {
163                         IndexService lucin = getIndex();
164                         lucin.add(study);
165                 } catch (IOException error) {
166                         LOG.error("Unable to index the study '" + study.getIndex()
167                                         + "', reason:", error);
168                         // Continue and try to index later
169                 }
170                 return study;
171         }
172
173         /**
174          * {@inheritDoc}
175          * 
176          * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
177          */
178         @Transactional
179         public SimulationContext addProjectContext(final Study aStudy,
180                         final SimulationContext.Properties cprop)
181                         throws MissedPropertyException, InvalidPropertyException,
182                         MultiplyDefinedException {
183                 SimulationContext added = getStepService().addSimulationContext(
184                                 getProjectElementService().getFirstStep(aStudy), cprop);
185                 update(aStudy);
186                 return added;
187         }
188
189         /**
190          * {@inheritDoc}
191          * 
192          * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
193          */
194         @Transactional
195         public SimulationContext addProjectContext(final Study aStudy,
196                         final SimulationContext context) {
197                 SimulationContext added = getStepService().addSimulationContext(
198                                 getProjectElementService().getFirstStep(aStudy), context);
199                 update(aStudy);
200                 return added;
201         }
202
203         /**
204          * {@inheritDoc}
205          * 
206          * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
207          */
208         public boolean addContributor(final Study aStudy, final User user) {
209                 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
210                 for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
211                         User present = i.next();
212                         if (present.equals(user)) {
213                                 return false;
214                         }
215                 }
216                 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
217
218                 aStudy.addRelation(new ContributorRelation(aStudy, user));
219                 if (absent) {
220                         update(aStudy); // Else, useless to re-index the study
221                 }
222                 contributor.add(user);
223                 return true;
224         }
225
226         /**
227          * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
228          * previously be approved.
229          * 
230          * @param aStudy
231          *            the study to move
232          * @return true if the move succeeded.
233          * @see #moveToPublic()
234          * @see #isPublic()
235          * @see Publication#approve(Date)
236          */
237         public boolean moveToReference(final Study aStudy) {
238                 if (aStudy.getProgressState() != ProgressState.APPROVED) {
239                         return false;
240                 }
241                 if (aStudy.getVisibility() != Visibility.PUBLIC) {
242                         return false;
243                 }
244
245                 aStudy.setVisibility(Visibility.REFERENCE);
246                 if (update(aStudy)) {
247                         return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
248                 }
249                 return false;
250         }
251
252         /**
253          * {@inheritDoc}
254          * 
255          * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
256          */
257         public boolean update(final Study aStudy, final Properties sprop)
258                         throws InvalidPropertyException {
259                 if (sprop.getTitle() != null) {
260                         aStudy.setTitle(sprop.getTitle());
261                 }
262                 if (sprop.getSummary() != null) {
263                         aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
264                                         .getSummary()));
265                 }
266                 // TODO: To be completed
267                 return update(aStudy);
268         }
269
270         /**
271          * Check if the document is published in the study.
272          * 
273          * @param aStudy
274          *            the study
275          * @param doc
276          *            the document
277          * @return true if the document is published in the study
278          */
279 /*      private boolean publishes(final Study aStudy, final Document doc) {
280                 if (!aStudy.publishes(doc)) {
281                         Scenario[] scene = aStudy.getScenarii();
282                         for (int i = 0; i < scene.length; i++) {
283                                 if (scene[i].publishes(doc)) {
284                                         return true;
285                                 }
286                         }
287                 }
288                 return false;
289         }
290 */
291         /**
292          * {@inheritDoc}
293          * 
294          * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
295          */
296         public boolean removeContributor(final Study aStudy, final User... users) {
297                 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
298                 Boolean done = false;
299                 for (int i = 0; i < users.length; i++) {
300                         User user = users[i];
301                         for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
302                                 User present = j.next();
303                                 if (!present.equals(user)) {
304                                         continue;
305                                 }
306
307                                 aStudy.removeRelation(ContributorRelation.class, user);
308                                 j.remove(); // Updates the contributor shortcut
309                                 done = true;
310                                 break;
311                         }
312                 }
313                 if (done) {
314                         update(aStudy);
315                 }
316                 return done;
317         }
318
319         /**
320          * {@inheritDoc}
321          * 
322          * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
323          */
324         public boolean removeProjectContext(final Study aStudy,
325                         final SimulationContext context) {
326                 boolean done = getStepService().removeSimulationContext(
327                                 getProjectElementService().getFirstStep(aStudy), context);
328                 update(aStudy);
329                 return done;
330         }
331
332         /**
333          * {@inheritDoc}
334          * 
335          * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
336          *      org.splat.dal.bo.som.ValidationCycle.Properties)
337          */
338         @Transactional
339         public void setValidationCycle(final Study aStudyDTO, final DocumentType type,
340                         final ValidationCycle.Properties vprop) {
341                 Map<String, ValidationCycle> validactor = aStudyDTO.getValidationCycles();
342                 if (validactor == null) {
343                         setShortCuts(aStudyDTO); // Initializes validactor and actor
344                 }
345
346                 Study aStudy = selectStudy(aStudyDTO.getIndex());
347                 
348                 String cname = type.getName();
349                 ValidationCycle cycle = validactor.get(cname);
350
351                 if (cycle != null && cycle.isAssigned()) {
352                         resetActors(cycle, vprop);
353                 } else {
354                         try {
355                                 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
356
357                                 getValidationCycleDAO().create(cycle); // RKV
358
359                                 ValidationCycleRelation link = cycle.getContext();
360                                 aStudy.addRelation(link);
361                                 aStudyDTO.getAllRelations().add(link); // RKV
362
363                                 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
364                         } catch (Exception error) {
365                                 LOG.error("Unable to re-index Knowledge Elements, reason:",
366                                                 error);
367                                 return;
368                         }
369                 }
370                 resetActorsShortCut(aStudyDTO);
371                 update(aStudy); // Re-index the study, just in case
372         }
373
374         /**
375          * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
376          * document of the study.
377          * 
378          * @param aStudy
379          *            a study to demote
380          * @return true if the demotion succeeded.
381          */
382         public boolean demote(final Study aStudy) {
383                 if (aStudy.getProgressState() == ProgressState.inCHECK) {
384                         aStudy.setProgressState(ProgressState.inDRAFT);
385                 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
386                         aStudy.setProgressState(ProgressState.inWORK);
387                 } else {
388                         return false;
389                 }
390                 return update(aStudy);
391         }
392
393         /**
394          * {@inheritDoc}
395          * 
396          * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
397          */
398         @Transactional
399         public int generateLocalIndex(final Study aStudy) {
400                 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
401                 return aStudy.getLastLocalIndex();
402         }
403
404         /**
405          * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
406          * final result document of the study.
407          * 
408          * @param aStudy
409          *            a study to promote
410          * @return true if the demotion succeeded.
411          */
412         public boolean promote(final Study aStudy) {
413                 if (aStudy.getProgressState() == ProgressState.inWORK) {
414                         aStudy.setProgressState(ProgressState.inDRAFT);
415                 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
416                         aStudy.setProgressState(ProgressState.inCHECK);
417                         Revision myvers = new Revision(aStudy.getVersion());
418                         if (myvers.isMinor()) {
419                                 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
420                                                 .toString());
421                         }
422                 } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
423                         aStudy.setProgressState(ProgressState.APPROVED);
424                 } else {
425                         return false;
426                 }
427
428                 return update(aStudy);
429         }
430
431         /**
432          * Moves this study from the Private to the Public area of the repository.
433          * 
434          * @param aStudy
435          *            a study to move
436          * @return true if the move succeeded.
437          * @see #isPublic()
438          */
439         public boolean moveToPublic(final Study aStudy) {
440                 boolean isOk = false;
441                 if (aStudy.getVisibility() == Visibility.PRIVATE) {
442                         aStudy.setVisibility(Visibility.PUBLIC);
443                         if (update(aStudy)) {
444                                 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
445                         }
446                 }
447                 return isOk;
448         }
449
450         /**
451          * Update a study in the database.
452          * 
453          * @param aStudy
454          *            the study to update
455          * @return true if the study is updated successfully
456          */
457         @Transactional
458         private boolean update(final Study aStudy) {
459                 boolean isOk = false;
460                 try {
461                         getStudyDAO().update(aStudy); // Update of relational base
462                         setShortCuts(aStudy); // RKV: initialize transient actors set
463                         getIndex().update(aStudy); // Update of Lucene index
464                         isOk = true;
465                 } catch (Exception e) {
466                         LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
467                 }
468                 return isOk;
469         }
470
471         /**
472          * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
473          * 
474          * @param aStudy
475          *            the study
476          * @return true if reference building is succeded
477          */
478         @Transactional
479         private boolean buildReference(final Study aStudy) {
480                 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
481                 IDBuilder tool = selectIDBuilder(aStudy.getDate());
482                 if (tool == null) {
483                         tool = new IDBuilder(aStudy.getDate());
484                         getIDBuilderDAO().create(tool);
485                 }
486                 aStudy.setReference(buildReference(tool, pattern, aStudy));
487                 return true;
488         }
489
490         /**
491          * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
492          * 
493          * @param aBuilder
494          *            the id builder
495          * @param study
496          *            the study
497          * @param pattern
498          *            the reference pattern
499          * @return true if reference building is succeded
500          */
501         @Transactional
502         public String buildReference(final IDBuilder aBuilder,
503                         final String pattern, final Study study) {
504                 char[] format = pattern.toCharArray();
505                 char[] ref = new char[80]; // Better evaluate the length of the generated string
506                 int next = aBuilder.getBase() + 1;
507
508                 int count = 0;
509                 for (int i = 0; i < format.length; i++) {
510
511                         // Insertion of attribute values
512                         if (format[i] == '%') {
513                                 i += 1;
514
515                                 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
516                                         int n = i;
517                                         while (format[i] == 'y') {
518                                                 i += 1;
519                                                 if (i == format.length) {
520                                                         break;
521                                                 }
522                                         }
523                                         SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); //RKV: NOPMD: TODO: Use locale here?
524                                         String year = tostring.format(study.getDate());
525                                         year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
526                                         for (int j = 0; j < year.length(); j++) {
527                                                 ref[count] = year.charAt(j);
528                                                 count += 1;
529                                         }
530                                         i -= 1; // Back to the last 'y' character
531                                 } else if (format[i] == '0') { // Insertion of the index
532                                         int n = i;
533                                         while (format[i] == '0') {
534                                                 i += 1;
535                                                 if (i == format.length) {
536                                                         break;
537                                                 }
538                                         }
539                                         DecimalFormat tostring = new DecimalFormat(pattern
540                                                         .substring(n, i));
541                                         String number = tostring.format(next);
542                                         for (int j = 0; j < number.length(); j++) {
543                                                 ref[count] = number.charAt(j);
544                                                 count += 1;
545                                         }
546                                         i -= 1; // Back to the last '0' character
547                                 }
548                                 // Keep the character
549                         } else {
550                                 ref[count] = format[i];
551                                 count += 1;
552                         }
553                 }
554                 // Incrementation of the number of study
555                 aBuilder.setBase(next);
556                 getIDBuilderDAO().update(aBuilder);
557                 return String.copyValueOf(ref, 0, count);
558         }
559
560         /**
561          * Find an id builder by date.
562          * 
563          * @param date
564          *            the date
565          * @return found id builder
566          */
567         private IDBuilder selectIDBuilder(final Date date) {
568                 Calendar aDate = Calendar.getInstance();
569                 aDate.setTime(date);
570                 return getIDBuilderDAO().findByCriteria(
571                                 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
572         }
573
574         /**
575          * Fill transient collection ModifiableActors of the study.
576          * 
577          * @param aStudy
578          *            the study
579          */
580         private void resetActorsShortCut(final Study aStudy) {
581                 getModifiableActors(aStudy).clear();
582                 // Get all actors involved in validation cycles
583                 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
584                                 .values().iterator(); i.hasNext();) {
585                         ValidationCycle cycle = i.next();
586                         User[] user = cycle.getAllActors();
587                         for (int j = 0; j < user.length; j++) {
588                                 getModifiableActors(aStudy).add(user[j]);
589                         }
590                 }
591                 // Get all other actors
592                 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
593                                 .hasNext();) {
594                         Relation link = i.next();
595                         Class<?> kindof = link.getClass().getSuperclass();
596                         if (!kindof.equals(ActorRelation.class)) {
597                                 continue;
598                         }
599                         getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
600                 }
601         }
602
603         /**
604          * Update lucene index for the study knowledge elements.
605          * 
606          * @param aStudy
607          *            the study
608          * @return true if reindexing succeeded
609          */
610         private boolean updateKnowledgeElementsIndex(final Study aStudy) {
611                 boolean isOk = false;
612                 try {
613                         IndexService lucin = getIndex();
614
615                         for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
616                                         .hasNext();) {
617                                 Scenario scene = i.next();
618                                 for (Iterator<KnowledgeElement> j = scene
619                                                 .getAllKnowledgeElements().iterator(); j.hasNext();) {
620                                         KnowledgeElement kelm = j.next();
621                                         lucin.update(kelm);
622                                 }
623                         }
624                         isOk = true;
625                 } catch (Exception error) {
626                         LOG.error("Unable to re-index Knowledge Elements, reason:",
627                                         error);
628                 }
629                 return isOk;
630         }
631
632         /**
633          * Get lucene index service. Create a lucene index if it does not exist.
634          * 
635          * @return index service
636          * @throws IOException
637          *             if error occurs during lucene index creation
638          */
639         private IndexService getIndex() throws IOException {
640                 IndexService lucin = getIndexService();
641                 if (!lucin.exists()) {
642                         lucin.create(); // Happens when re-indexing all studies
643                 }
644                 return lucin;
645         }
646
647         /**
648          * Create a new validation cycle for documents of the given study.
649          * 
650          * @param from
651          *            the study
652          * @param cycle
653          *            the cycle description
654          * @return the new validation cycle
655          */
656         protected ValidationCycle createValidationCycle(
657                         final Study from,
658                         final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
659                 Actor[] actype = cycle.getActorTypes();
660                 User.Properties uprop = new User.Properties();
661
662                 ValidationCycle aValidationCycle = new ValidationCycle();
663                 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
664                                 cycle.getName())); // Null in case of default validation cycle
665                 // context = new ValidationCycleRelation(from, vprop);
666                 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
667                 for (int i = 0; i < actype.length; i++) {
668                         User actor = null;
669                         if (actype[i] != null) {
670                                 try {
671                                         if (actype[i] == Actor.manager) {
672                                                 actor = from.getAuthor();
673                                         } else if (actype[i] == Actor.Nx1) {
674                                                 List<User> manager = getUserService().selectUsersWhere(
675                                                                 uprop.setOrganizationName("Nx1"));
676                                                 if (manager.size() == 1) {
677                                                         actor = manager.get(0);
678                                                 }
679                                         } else if (actype[i] == Actor.Nx2) {
680                                                 List<User> manager = getUserService().selectUsersWhere(
681                                                                 uprop.setOrganizationName("Nx2"));
682                                                 if (manager.size() == 1) {
683                                                         actor = manager.get(0);
684                                                 }
685                                         } else { /* Actor.customer */
686                                                 actor = from.getAuthor();
687                                                 // TODO: Get the customer of the study, if exists
688                                         }
689                                 } catch (Exception e) { // Should not happen
690                                         actor = null;
691                                 }
692                         }
693                         if (i == 0) {
694                                 aValidationCycle.setReviewer(actor);
695                         } else if (i == 1) {
696                                 aValidationCycle.setApprover(actor);
697                         } else if (i == 2) {
698                                 aValidationCycle.setSignatory(actor);
699                         }
700                 }
701                 return aValidationCycle;
702         }
703
704         /**
705          * Remove a validation step from the validation cycle.
706          * 
707          * @param aValidationCycle
708          *            the validation cycle
709          * @param step
710          *            the validation step to remove
711          */
712         @Transactional
713         protected void remove(final ValidationCycle aValidationCycle,
714                         final ValidationStep step) {
715                 if (step == ValidationStep.REVIEW) {
716                         aValidationCycle.setReviewer(null);
717                 } else if (step == ValidationStep.APPROVAL) {
718                         aValidationCycle.setApprover(null);
719                 } else if (step == ValidationStep.ACCEPTANCE
720                                 || step == ValidationStep.REFUSAL) {
721                         aValidationCycle.setSignatory(null);
722                 }
723                 if (aValidationCycle.isSaved()) {
724                         getValidationCycleDAO().update(aValidationCycle);
725                 }
726         }
727
728         /**
729          * Reset actors for the validation cycle.
730          * 
731          * @param aValidationCycle
732          *            the validation cycle to update
733          * @param vprop
734          *            new validation cycle properties containing new actors
735          */
736         @Transactional
737         public void resetActors(final ValidationCycle aValidationCycle,
738                         final ValidationCycle.Properties vprop) {
739                 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
740                 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
741                 aValidationCycle.setApprover(vprop.getApprover()); // May be null
742                 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
743                 if (aValidationCycle.isSaved()) {
744                         getValidationCycleDAO().merge(aValidationCycle);
745                 }
746         }
747
748         /**
749          * Set actor for the given validation cycle and validation step.
750          * 
751          * @param aValidationCycle
752          *            the validation cycle
753          * @param step
754          *            the validation step
755          * @param actor
756          *            the actor to set
757          */
758         @Transactional
759         protected void setActor(final ValidationCycle aValidationCycle,
760                         final ValidationStep step, final User actor) {
761                 if (step == ValidationStep.PROMOTION) {
762                         aValidationCycle.setPublisher(actor);
763                 } else if (step == ValidationStep.REVIEW) {
764                         aValidationCycle.setReviewer(actor);
765                 } else if (step == ValidationStep.APPROVAL) {
766                         aValidationCycle.setApprover(actor);
767                 } else if (step == ValidationStep.ACCEPTANCE
768                                 || step == ValidationStep.REFUSAL) {
769                         aValidationCycle.setSignatory(actor);
770                 }
771                 if (aValidationCycle.isSaved()) {
772                         getValidationCycleDAO().update(aValidationCycle);
773                 }
774         }
775
776         /**
777          * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
778          * 
779          * @param aStudy
780          *            the study
781          * @return the actors of this study
782          * @see #hasActor(User)
783          */
784         public Set<User> getActors(final Study aStudy) {
785                 if (aStudy.getActor() == null) {
786                         setShortCuts(aStudy);
787                 }
788                 return Collections.unmodifiableSet(aStudy.getActor());
789         }
790
791         /**
792          * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
793          * 
794          * @param aStudy
795          *            the study
796          * @return the modifiable set of actors of this study
797          * @see #hasActor(User)
798          */
799         public Set<User> getModifiableActors(final Study aStudy) {
800                 if (aStudy.getActor() == null) {
801                         setShortCuts(aStudy);
802                 }
803                 return aStudy.getActor();
804         }
805
806         /**
807          * Returns unmodifiable initialized transient list of contributors of this study.
808          * 
809          * @param aStudy
810          *            the study
811          * @return the unmodifiable not null transient list of contributors of this study
812          */
813         public List<User> getContributors(final Study aStudy) {
814                 if (aStudy.getContributor() == null) {
815                         setShortCuts(aStudy);
816                 }
817                 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
818         }
819
820         /**
821          * Returns modifiable initialized transient list of contributors of this study.
822          * 
823          * @param aStudy
824          *            the study
825          * @return the modifiable not null transient list of contributors of this study
826          */
827         public List<User> getModifiableContributors(final Study aStudy) {
828                 if (aStudy.getContributor() == null) {
829                         setShortCuts(aStudy);
830                 }
831                 return aStudy.getContributor(); // May be empty
832         }
833
834         /**
835          * Returns the validation cycle of the given document type.
836          * 
837          * @param aStudy
838          *            the study
839          * @param type
840          *            the document type being subject of validation
841          * @return the validation cycle of the document, or null if not defined.
842          */
843         public ValidationCycle getValidationCycleOf(final Study aStudy,
844                         final DocumentType type) {
845                 if (aStudy.getValidationCycles() == null || aStudy.getValidationCycles().isEmpty()) {
846                         setShortCuts(aStudy);
847                 }
848                 ValidationCycle result = aStudy.getValidationCycles().get(
849                                 type.getName());
850                 if (result == null) {
851                         if (type.isStepResult()) {
852                                 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
853                         }
854                         if (result == null) {
855                                 result = aStudy.getValidationCycles().get("built-in");
856                         }
857                 }
858                 return result;
859         }
860
861         /**
862          * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
863          * 
864          * @param aStudy
865          *            the study
866          * @param user
867          *            the user to look for
868          * @return true if the given user is actor of this study.
869          * @see #getActors()
870          */
871         public boolean hasActor(final Study aStudy, final User user) {
872                 if (user == null) {
873                         return false;
874                 }
875                 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
876                         User involved = i.next();
877                         if (involved.equals(user)) {
878                                 return true;
879                         }
880                 }
881                 return false;
882         }
883
884         /**
885          * Checks if the given user participates to this study. The Study staff includes the author and contributors.
886          * 
887          * @param aStudy
888          *            the study
889          * @param user
890          *            the user to look for
891          * @return true if the given user is actor of this study.
892          * @see #getContributors()
893          */
894         public boolean isStaffedBy(final Study aStudy, final User user) {
895                 if (user == null) {
896                         return false;
897                 }
898                 if (aStudy == null) {
899                         return false;
900                 }
901                 if (aStudy.getAuthor() == null) {
902                         return false;
903                 }
904                 if (aStudy.getAuthor().equals(user)) {
905                         return true;
906                 }
907                 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
908                         if (i.next().equals(user)) {
909                                 return true;
910                         }
911                 }
912                 return false;
913         }
914
915         /**
916          * Initialize shortcuts of the study as its transient collections.
917          * 
918          * @param aStudy
919          *            the study
920          */
921         public void loadWorkflow(final Study aStudy) {
922                 setShortCuts(aStudy);
923         }
924
925         /**
926          * Initialize shortcuts of the study as its transient collections.
927          * 
928          * @param aStudy
929          *            the study
930          */
931         public void setShortCuts(final Study aStudy) {
932                 aStudy.getContributor().clear();
933                 aStudy.getValidationCycles().clear();
934                 aStudy.getActor().clear();
935
936                 // Get the contributors
937                 for (Iterator<Relation> i = aStudy.getRelations(
938                                 ContributorRelation.class).iterator(); i.hasNext();) {
939                         ContributorRelation link = (ContributorRelation) i.next();
940                         aStudy.getContributor().add(link.getTo());
941                 }
942                 // Get the validation cycles specific to this study
943                 for (Iterator<Relation> i = aStudy.getRelations(
944                                 ValidationCycleRelation.class).iterator(); i.hasNext();) {
945                         ValidationCycleRelation link = (ValidationCycleRelation) i.next();
946                         aStudy.getValidationCycles().put(link.getDocumentType().getName(),
947                                         link.getTo()); // The associated document type is necessarily not null in this
948                         // context
949                 }
950                 // Get the validation cycles coming from the configured workflow and not overridden in this study
951                 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
952                                 .getAllValidationCycles().iterator(); i.hasNext();) {
953                         ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
954                                         .next();
955                         String type = cycle.getName();
956                         if (!aStudy.getValidationCycles().containsKey(type)) {
957                                 aStudy.getValidationCycles().put(type,
958                                                 createValidationCycle(aStudy, cycle));
959                         }
960                 }
961                 // Get all corresponding actors
962                 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
963                                 .values().iterator(); i.hasNext();) {
964                         ValidationCycle cycle = i.next();
965                         User[] user = cycle.getAllActors();
966                         for (int j = 0; j < user.length; j++) {
967                                 aStudy.getActor().add(user[j]);
968                         }
969                 }
970                 // Get all other actors
971                 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
972                                 .hasNext();) {
973                         Relation link = i.next();
974                         Class<?> kindof = link.getClass().getSuperclass();
975                         if (!kindof.equals(ActorRelation.class)) {
976                                 continue;
977                         }
978                         aStudy.getActor().add(((ActorRelation) link).getTo());
979                 }
980         }
981
982         /**
983          * Get project settings.
984          * 
985          * @return Project settings service
986          */
987         private ProjectSettingsService getProjectSettings() {
988                 return _projectSettingsService;
989         }
990
991         /**
992          * Set project settings service.
993          * 
994          * @param projectSettingsService
995          *            project settings service
996          */
997         public void setProjectSettings(
998                         final ProjectSettingsService projectSettingsService) {
999                 _projectSettingsService = projectSettingsService;
1000         }
1001
1002         /**
1003          * Get the projectElementService.
1004          * 
1005          * @return the projectElementService
1006          */
1007         public ProjectElementService getProjectElementService() {
1008                 return _projectElementService;
1009         }
1010
1011         /**
1012          * Set the projectElementService.
1013          * 
1014          * @param projectElementService
1015          *            the projectElementService to set
1016          */
1017         public void setProjectElementService(
1018                         final ProjectElementService projectElementService) {
1019                 _projectElementService = projectElementService;
1020         }
1021
1022         /**
1023          * Get the stepService.
1024          * 
1025          * @return the stepService
1026          */
1027         public StepService getStepService() {
1028                 return _stepService;
1029         }
1030
1031         /**
1032          * Set the stepService.
1033          * 
1034          * @param stepService
1035          *            the stepService to set
1036          */
1037         public void setStepService(final StepService stepService) {
1038                 _stepService = stepService;
1039         }
1040
1041         /**
1042          * Get the indexService.
1043          * 
1044          * @return the indexService
1045          */
1046         public IndexService getIndexService() {
1047                 return _indexService;
1048         }
1049
1050         /**
1051          * Set the indexService.
1052          * 
1053          * @param indexService
1054          *            the indexService to set
1055          */
1056         public void setIndexService(final IndexService indexService) {
1057                 _indexService = indexService;
1058         }
1059
1060         /**
1061          * Get the studyDAO.
1062          * 
1063          * @return the studyDAO
1064          */
1065         public StudyDAO getStudyDAO() {
1066                 return _studyDAO;
1067         }
1068
1069         /**
1070          * Set the studyDAO.
1071          * 
1072          * @param studyDAO
1073          *            the studyDAO to set
1074          */
1075         public void setStudyDAO(final StudyDAO studyDAO) {
1076                 _studyDAO = studyDAO;
1077         }
1078
1079         /**
1080          * Get the iDBuilderDAO.
1081          * 
1082          * @return the iDBuilderDAO
1083          */
1084         public IDBuilderDAO getIDBuilderDAO() {
1085                 return _iDBuilderDAO;
1086         }
1087
1088         /**
1089          * Set the iDBuilderDAO.
1090          * 
1091          * @param builderDAO
1092          *            the iDBuilderDAO to set
1093          */
1094         public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1095                 _iDBuilderDAO = builderDAO;
1096         }
1097
1098         /**
1099          * Get the scenarioDAO.
1100          * 
1101          * @return the scenarioDAO
1102          */
1103         public ScenarioDAO getScenarioDAO() {
1104                 return _scenarioDAO;
1105         }
1106
1107         /**
1108          * Set the scenarioDAO.
1109          * 
1110          * @param scenarioDAO
1111          *            the scenarioDAO to set
1112          */
1113         public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1114                 _scenarioDAO = scenarioDAO;
1115         }
1116
1117         /**
1118          * Get the validationCycleDAO.
1119          * 
1120          * @return the validationCycleDAO
1121          */
1122         public ValidationCycleDAO getValidationCycleDAO() {
1123                 return _validationCycleDAO;
1124         }
1125
1126         /**
1127          * Set the validationCycleDAO.
1128          * 
1129          * @param validationCycleDAO
1130          *            the validationCycleDAO to set
1131          */
1132         public void setValidationCycleDAO(
1133                         final ValidationCycleDAO validationCycleDAO) {
1134                 _validationCycleDAO = validationCycleDAO;
1135         }
1136
1137         /**
1138          * Get the documentTypeService.
1139          * 
1140          * @return the documentTypeService
1141          */
1142         public DocumentTypeService getDocumentTypeService() {
1143                 return _documentTypeService;
1144         }
1145
1146         /**
1147          * Set the documentTypeService.
1148          * 
1149          * @param documentTypeService
1150          *            the documentTypeService to set
1151          */
1152         public void setDocumentTypeService(
1153                         final DocumentTypeService documentTypeService) {
1154                 _documentTypeService = documentTypeService;
1155         }
1156
1157         /**
1158          * Get the userService.
1159          * 
1160          * @return the userService
1161          */
1162         public UserService getUserService() {
1163                 return _userService;
1164         }
1165
1166         /**
1167          * Set the userService.
1168          * 
1169          * @param userService
1170          *            the userService to set
1171          */
1172         public void setUserService(final UserService userService) {
1173                 _userService = userService;
1174         }
1175 }