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