Salome HOME
86863e9829f107c5e9f56ea976c906ceb4ff4cac
[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.awt.Graphics2D;
13 import java.io.File;
14 import java.io.FileNotFoundException;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.text.DecimalFormat;
18 import java.text.SimpleDateFormat;
19 import java.util.ArrayList;
20 import java.util.Calendar;
21 import java.util.Collections;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Scanner;
29 import java.util.Set;
30
31 import org.apache.lucene.index.IndexWriter;
32 import org.apache.lucene.store.FSDirectory;
33 import org.hibernate.Criteria;
34 import org.hibernate.Hibernate;
35 import org.hibernate.criterion.DetachedCriteria;
36 import org.hibernate.criterion.Order;
37 import org.hibernate.criterion.Restrictions;
38 import org.hibernate.proxy.HibernateProxy;
39 import org.jfree.chart.ChartFactory;
40 import org.jfree.chart.JFreeChart;
41 import org.jfree.chart.plot.PlotOrientation;
42 import org.jfree.data.xy.XYSeries;
43 import org.jfree.data.xy.XYSeriesCollection;
44 import org.splat.common.properties.MessageKeyEnum;
45 import org.splat.dal.bo.kernel.Relation;
46 import org.splat.dal.bo.kernel.User;
47 import org.splat.dal.bo.som.ActorRelation;
48 import org.splat.dal.bo.som.ContributorRelation;
49 import org.splat.dal.bo.som.DescriptionAttribute;
50 import org.splat.dal.bo.som.DocumentType;
51 import org.splat.dal.bo.som.IDBuilder;
52 import org.splat.dal.bo.som.KnowledgeElement;
53 import org.splat.dal.bo.som.ProgressState;
54 import org.splat.dal.bo.som.ProjectElement;
55 import org.splat.dal.bo.som.Publication;
56 import org.splat.dal.bo.som.ReaderRelation;
57 import org.splat.dal.bo.som.Scenario;
58 import org.splat.dal.bo.som.SimulationContext;
59 import org.splat.dal.bo.som.Study;
60 import org.splat.dal.bo.som.ValidationCycle;
61 import org.splat.dal.bo.som.ValidationCycleRelation;
62 import org.splat.dal.bo.som.ValidationStep;
63 import org.splat.dal.bo.som.Visibility;
64 import org.splat.dal.bo.som.Study.Properties;
65 import org.splat.dal.bo.som.ValidationCycle.Actor;
66 import org.splat.dal.dao.som.DescriptionAttributeDAO;
67 import org.splat.dal.dao.som.DocumentDAO;
68 import org.splat.dal.dao.som.DocumentTypeDAO;
69 import org.splat.dal.dao.som.IDBuilderDAO;
70 import org.splat.dal.dao.som.PublicationDAO;
71 import org.splat.dal.dao.som.ScenarioDAO;
72 import org.splat.dal.dao.som.StudyDAO;
73 import org.splat.dal.dao.som.UsedByRelationDAO;
74 import org.splat.dal.dao.som.ValidationCycleDAO;
75 import org.splat.exception.BusinessException;
76 import org.splat.exception.IncompatibleDataException;
77 import org.splat.exception.InvalidParameterException;
78 import org.splat.kernel.InvalidPropertyException;
79 import org.splat.kernel.MismatchException;
80 import org.splat.kernel.MissedPropertyException;
81 import org.splat.kernel.MultiplyDefinedException;
82 import org.splat.log.AppLogger;
83 import org.splat.service.dto.DocToCompareDTO;
84 import org.splat.service.dto.DocumentDTO;
85 import org.splat.service.dto.StudyFacadeDTO;
86 import org.splat.service.dto.UserDTO;
87 import org.splat.service.technical.IndexService;
88 import org.splat.service.technical.ProjectSettingsService;
89 import org.splat.service.technical.ProjectSettingsServiceImpl;
90 import org.splat.service.technical.RepositoryService;
91 import org.splat.service.technical.ProjectSettingsService.Step;
92 import org.splat.som.Revision;
93 import org.splat.util.BeanHelper;
94 import org.springframework.transaction.annotation.Transactional;
95
96 import com.lowagie.text.Document;
97 import com.lowagie.text.DocumentException;
98 import com.lowagie.text.Rectangle;
99 import com.lowagie.text.pdf.DefaultFontMapper;
100 import com.lowagie.text.pdf.PdfContentByte;
101 import com.lowagie.text.pdf.PdfTemplate;
102 import com.lowagie.text.pdf.PdfWriter;
103
104 /**
105  * This class defines all methods for creation, modification the study.
106  * 
107  * @author Maria KRUCHININA
108  * 
109  */
110 public class StudyServiceImpl implements StudyService {
111
112         /**
113          * logger for the service.
114          */
115         public final static AppLogger LOG = AppLogger
116                         .getLogger(StudyServiceImpl.class);
117         /**
118          * "studyId" parameter name.
119          */
120         public final static String PARAM_STUDY_ID = "studyId";
121
122         /**
123          * Injected index service.
124          */
125         private IndexService _indexService;
126
127         /**
128          * Injected step service.
129          */
130         private StepService _stepService;
131
132         /**
133          * Injected project service.
134          */
135         private ProjectSettingsService _projectSettings;
136
137         /**
138          * Injected project element service.
139          */
140         private ProjectElementService _projectElementService;
141
142         /**
143          * Injected study DAO.
144          */
145         private StudyDAO _studyDAO;
146
147         /**
148          * Injected usedBy relations DAO.
149          */
150         private UsedByRelationDAO _usedByRelationDAO;
151
152         /**
153          * Injected scenario DAO.
154          */
155         private ScenarioDAO _scenarioDAO;
156
157         /**
158          * Injected validation cycle DAO.
159          */
160         private ValidationCycleDAO _validationCycleDAO;
161
162         /**
163          * Injected IDBuilder DAO.
164          */
165         private IDBuilderDAO _iDBuilderDAO;
166
167         /**
168          * Injected document type service.
169          */
170         private DocumentTypeService _documentTypeService;
171
172         /**
173          * Injected user service.
174          */
175         private UserService _userService;
176
177         /**
178          * Injected publication DAO.
179          */
180         private PublicationDAO _publicationDAO;
181
182         /**
183          * Injected repository service.
184          */
185         private RepositoryService _repositoryService;
186
187         /**
188          * Injected document DAO.
189          */
190         private DocumentDAO _documentDAO;
191
192         /**
193          * Injected description attribute DAO.
194          */
195         private DescriptionAttributeDAO _descriptionAttributeDAO;
196         /**
197          * Injected document type DAO.
198          */
199         private DocumentTypeDAO _documentTypeDAO;
200
201         /**
202          * {@inheritDoc}
203          * 
204          * @see org.splat.service.StudyService#selectStudy(long)
205          */
206         @Transactional
207         public Study selectStudy(final long index) {
208                 Study result = getStudyDAO().get(index);
209                 if (result != null) {
210                         loadWorkflow(result);
211                 }
212                 return result;
213         }
214
215         /**
216          * {@inheritDoc}
217          * 
218          * @see org.splat.service.StudyService#removeStudy(long)
219          */
220         @Transactional
221         public void removeStudy(final Long index) {
222                 Study study = getStudyDAO().get(index);
223                 Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
224                 if (study != null) {
225                         // Select all documents published in the study and study's scenarios.
226                         DetachedCriteria query = DetachedCriteria.forClass(
227                                         Publication.class, "pub");
228                         query
229                                         .createCriteria("pub.owner", "projelem",
230                                                         Criteria.INNER_JOIN)
231                                         .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
232                                         .add(
233                                                         Restrictions
234                                                                         .or(Restrictions.eq("projelem.rid", index),
235                                                                                         Restrictions.eq("study.rid", index)))
236                                         .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
237
238                         if (LOG.isDebugEnabled()) {
239                                 LOG.debug("Find study documents: " + query.toString());
240                         }
241                         for (Publication pub : getPublicationDAO().getFilteredList(query)) {
242                                 docums.add(pub.value());
243                                 // Find also all previous versions of the document
244                                 for (org.splat.dal.bo.som.Document prev = pub.value()
245                                                 .getPreviousVersion(); prev != null; prev = prev
246                                                 .getPreviousVersion()) {
247                                         docums.add(prev);
248                                 }
249                         }
250
251                         // Delete the study with its relations, scenarios and publications
252                         getStudyDAO().delete(study);
253
254                         // Remove all relations of study documents
255                         for (org.splat.dal.bo.som.Document doc : docums) {
256                                 LOG.debug("Found doc: " + doc.getTitle() + " ["
257                                                 + doc.getReference() + "]" + " [" + doc.getRid() + "]");
258                                 doc.getAllRelations().clear();
259                         }
260                         getDocumentDAO().flush();
261
262                         // Remove all documents of the study
263                         for (org.splat.dal.bo.som.Document doc : docums) {
264                                 LOG.debug("Remove doc: " + doc.getTitle() + " ["
265                                                 + doc.getReference() + "]" + " [" + doc.getRid() + "]");
266                                 getDocumentDAO().delete(doc);
267                         }
268                 }
269         }
270
271         /**
272          * Get study by its reference.
273          * 
274          * @param refid
275          *            the study reference
276          * @return found study or null
277          */
278         @Transactional(readOnly = true)
279         public Study selectStudy(final String refid) {
280                 Study result = getStudyDAO().findByCriteria(
281                                 Restrictions.eq("sid", refid));
282                 loadWorkflow(result);
283                 return result;
284         }
285
286         /**
287          * {@inheritDoc}
288          * 
289          * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
290          */
291         @Transactional
292         public Study createStudy(final Study.Properties sprop)
293                         throws MissedPropertyException, InvalidPropertyException,
294                         MultiplyDefinedException {
295                 sprop.setReference(getProjectSettings().getReferencePattern());
296                 Study study = new Study(sprop);
297
298                 buildReference(study);
299                 getStudyDAO().create(study);
300                 // try {
301                 // IndexService lucin = getIndex();
302                 // lucin.add(study);
303                 // } catch (IOException error) {
304                 // LOG.error("Unable to index the study '" + study.getIndex()
305                 // + "', reason:", error);
306                 // // Continue and try to index later
307                 // }
308                 return study;
309         }
310
311         /**
312          * {@inheritDoc}
313          * 
314          * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
315          */
316         @Transactional
317         public SimulationContext addProjectContext(final Study aStudy,
318                         final SimulationContext.Properties cprop)
319                         throws MissedPropertyException, InvalidPropertyException,
320                         MultiplyDefinedException {
321                 SimulationContext added = getStepService().addSimulationContext(
322                                 getProjectElementService().getFirstStep(aStudy), cprop);
323                 update(aStudy);
324                 return added;
325         }
326
327         /**
328          * {@inheritDoc}
329          * 
330          * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
331          */
332         @Transactional
333         public SimulationContext addProjectContext(final Study aStudy,
334                         final SimulationContext context) {
335                 SimulationContext added = getStepService().addSimulationContext(
336                                 getProjectElementService().getFirstStep(aStudy), context);
337                 update(aStudy);
338                 return added;
339         }
340
341         /**
342          * {@inheritDoc}
343          * 
344          * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
345          */
346         @Transactional
347         public boolean addContributor(final Study aStudy, final User user) {
348                 List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
349
350                 if (contributors.contains(user)) {
351                         return false;
352                 }
353
354                 // Remove user from readers
355                 try {
356                         List<UserDTO> readers = getReaders(aStudy.getIndex());
357                         for (UserDTO reader : readers) {
358                                 if (reader.getIndex() == user.getIndex()) {
359                                         // user must be the actual user in the relationship object in the aStudy object for this to work
360                                         aStudy.removeRelation(ReaderRelation.class, user);
361                                 }
362                         }
363                 } catch (InvalidParameterException e) {
364                         LOG.error(e.getMessage(), e);
365                 }
366
367                 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
368
369                 aStudy.addRelation(new ContributorRelation(aStudy, user));
370                 if (absent) {
371                         update(aStudy); // Else, useless to re-index the study
372                 }
373                 return true;
374         }
375
376         /**
377          * {@inheritDoc}
378          * 
379          * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
380          */
381         @Transactional
382         public boolean update(final Study aStudy, final Properties sprop)
383                         throws InvalidPropertyException {
384                 if (sprop.getTitle() != null) {
385                         aStudy.setTitle(sprop.getTitle());
386                 }
387                 if (sprop.getSummary() != null) {
388                         aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
389                                         .getSummary()));
390                 }
391                 // TODO: To be completed
392                 return update(aStudy);
393         }
394
395         /**
396          * Check if the document is published in the study.
397          * 
398          * @param aStudy
399          *            the study
400          * @param doc
401          *            the document
402          * @return true if the document is published in the study
403          */
404         /*
405          * private boolean publishes(final Study aStudy, final Document doc) { if (!aStudy.publishes(doc)) { Scenario[] scene =
406          * aStudy.getScenarii(); for (int i = 0; i < scene.length; i++) { if (scene[i].publishes(doc)) { return true; } } } return false; }
407          */
408         /**
409          * {@inheritDoc}
410          * 
411          * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
412          */
413         @Transactional
414         public boolean removeContributor(final Study aStudy, final User... users) {
415                 List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
416                 Boolean done = false;
417                 for (User user : users) {
418                         if (contributors.contains(user)) {
419                                 aStudy.removeRelation(ContributorRelation.class, user);
420                                 contributors.remove(user);
421                                 done = true;
422                         }
423                 }
424                 if (done) {
425                         update(aStudy);
426                 }
427                 return done;
428         }
429
430         /**
431          * {@inheritDoc}
432          * 
433          * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
434          */
435         @Transactional
436         public boolean removeProjectContext(final Study aStudy,
437                         final SimulationContext context) {
438                 boolean done = getStepService().removeSimulationContext(
439                                 getProjectElementService().getFirstStep(aStudy), context);
440                 update(aStudy);
441                 return done;
442         }
443
444         /**
445          * {@inheritDoc}
446          * 
447          * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
448          *      org.splat.dal.bo.som.ValidationCycle.Properties)
449          */
450         @Transactional
451         public void setValidationCycle(final Study aStudyDTO,
452                         final DocumentType type, final ValidationCycle.Properties vprop) {
453                 Map<String, ValidationCycle> validactor = aStudyDTO
454                                 .getValidationCycles();
455                 if (validactor == null) {
456                         setShortCuts(aStudyDTO); // Initializes validactor and actor
457                 }
458
459                 Study aStudy = selectStudy(aStudyDTO.getIndex());
460
461                 String cname = type.getName();
462                 ValidationCycle cycle = validactor.get(cname);
463
464                 if (cycle != null && cycle.isAssigned()) {
465                         resetActors(cycle, vprop);
466                 } else {
467                         try {
468                                 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
469
470                                 getValidationCycleDAO().create(cycle); // RKV
471
472                                 ValidationCycleRelation link = cycle.getContext();
473                                 aStudy.addRelation(link);
474                                 getValidationCycleDAO().flush();
475                                 aStudyDTO.getAllRelations().add(link); // RKV
476
477                                 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
478                         } catch (BusinessException error) {
479                                 LOG.error("Unable to create validation cycle, reason:", error);
480                                 return;
481                         }
482                 }
483                 resetActorsShortCut(aStudyDTO);
484                 update(aStudy); // Re-index the study, just in case
485         }
486
487         /**
488          * {@inheritDoc}
489          * 
490          * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
491          */
492         @Transactional
493         public int generateLocalIndex(final Study aStudy) {
494                 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
495                 return aStudy.getLastLocalIndex();
496         }
497
498         /**
499          * Promotes this study from In-Work to In-Draft then In-Check and APPROVED <BR>
500          * states. This function takes into account statuses of final result<BR>
501          * documents of the study.
502          * 
503          * @param aStudy
504          *            a study to promote
505          * @return true if the promotion succeeded.
506          */
507         @Transactional
508         public boolean promote(final Study aStudy) {
509                 boolean res = true;
510                 if (aStudy.getProgressState() == ProgressState.inWORK
511                                 && canBePromoted(aStudy)) {
512                         aStudy.setProgressState(ProgressState.inDRAFT);
513                 } else if (aStudy.getProgressState() == ProgressState.inDRAFT
514                                 && canBeReviewed(aStudy)) {
515                         aStudy.setProgressState(ProgressState.inCHECK);
516                         Revision myvers = new Revision(aStudy.getVersion());
517                         if (myvers.isMinor()) {
518                                 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
519                                                 .toString());
520                         }
521                 } else if (aStudy.getProgressState() == ProgressState.inCHECK
522                                 && canBeApproved(aStudy)) {
523                         aStudy.setProgressState(ProgressState.APPROVED);
524                         updateKnowledgeElementsState(aStudy);
525                 } else {
526                         res = false;
527                 }
528                 if (res) {
529                         res = update(aStudy);
530                 }
531
532                 return res;
533         }
534
535         /**
536          * Demotes this study from In-Check or In-Draft to In-Work states.
537          * 
538          * @param aStudy
539          *            a study to demote
540          * @return true if the demotion succeeded.
541          */
542         @Transactional
543         public boolean demote(final Study aStudy) {
544                 boolean res;
545                 if (aStudy.getProgressState() == ProgressState.inCHECK
546                                 || aStudy.getProgressState() == ProgressState.inDRAFT) {
547                         aStudy.setProgressState(ProgressState.inWORK);
548                         res = update(aStudy);
549                 } else {
550                         res = false;
551                 }
552                 return res;
553         }
554
555         /**
556          * Moves this study from the Private to the Public area of the repository.
557          * 
558          * @param aStudy
559          *            a study to move
560          * @return true if the move succeeded.
561          * @see #isPublic()
562          */
563         @Transactional
564         public boolean moveToPublic(final Study aStudy) {
565                 boolean isOk = false;
566                 if (aStudy.getVisibility() == Visibility.PRIVATE) {
567                         aStudy.setVisibility(Visibility.PUBLIC);
568                         if (update(aStudy)) {
569                                 isOk = updateKnowledgeElementsState(aStudy); // If fails, the database roll-back is under responsibility of the caller
570                         }
571                 }
572                 return isOk;
573         }
574
575         /**
576          * Moves this study from the Public to the Private area of the repository.
577          * 
578          * @param aStudy
579          *            a study to move
580          * @return true if the move succeeded.
581          */
582         @Transactional
583         public boolean moveToPrivate(final Study aStudy) {
584                 boolean isOk = false;
585                 if (aStudy.getVisibility() == Visibility.PUBLIC) {
586                         aStudy.setVisibility(Visibility.PRIVATE);
587                         if (update(aStudy)) {
588                                 isOk = updateKnowledgeElementsState(aStudy); // If fails, the database roll-back is under responsibility of the caller
589                         }
590                 }
591                 return isOk;
592         }
593
594         /**
595          * Update a study in the database.
596          * 
597          * @param aStudy
598          *            the study to update
599          * @return true if the study is updated successfully
600          */
601         private boolean update(final Study aStudy) {
602                 boolean isOk = false;
603                 try {
604                         getStudyDAO().merge(aStudy); // Update of relational base
605                         setShortCuts(aStudy); // RKV: initialize transient actors set
606                         // RKV: getIndex().update(aStudy); // Update of Lucene index
607                         isOk = true;
608                 } catch (Exception e) {
609                         LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
610                 }
611                 return isOk;
612         }
613
614         /**
615          * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
616          * 
617          * @param aStudy
618          *            the study
619          * @return true if reference building is succeded
620          */
621         @Transactional
622         private boolean buildReference(final Study aStudy) {
623                 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
624                 IDBuilder tool = selectIDBuilder(aStudy.getDate());
625                 if (tool == null) {
626                         tool = new IDBuilder(aStudy.getDate());
627                         getIDBuilderDAO().create(tool);
628                 }
629                 aStudy.setReference(buildReference(tool, pattern, aStudy));
630                 return true;
631         }
632
633         /**
634          * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
635          * 
636          * @param aBuilder
637          *            the id builder
638          * @param study
639          *            the study
640          * @param pattern
641          *            the reference pattern
642          * @return true if reference building is succeded
643          */
644         @Transactional
645         public String buildReference(final IDBuilder aBuilder,
646                         final String pattern, final Study study) {
647                 char[] format = pattern.toCharArray();
648                 char[] ref = new char[80]; // Better evaluate the length of the generated string
649                 int next = aBuilder.getBase() + 1;
650
651                 int count = 0;
652                 for (int i = 0; i < format.length; i++) {
653
654                         // Insertion of attribute values
655                         if (format[i] == '%') {
656                                 i += 1;
657
658                                 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
659                                         int n = i;
660                                         while (format[i] == 'y') {
661                                                 i += 1;
662                                                 if (i == format.length) {
663                                                         break;
664                                                 }
665                                         }
666                                         SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
667                                         String year = tostring.format(study.getDate());
668                                         year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
669                                         for (int j = 0; j < year.length(); j++) {
670                                                 ref[count] = year.charAt(j);
671                                                 count += 1;
672                                         }
673                                         i -= 1; // Back to the last 'y' character
674                                 } else if (format[i] == '0') { // Insertion of the index
675                                         int n = i;
676                                         while (format[i] == '0') {
677                                                 i += 1;
678                                                 if (i == format.length) {
679                                                         break;
680                                                 }
681                                         }
682                                         DecimalFormat tostring = new DecimalFormat(pattern
683                                                         .substring(n, i));
684                                         String number = tostring.format(next);
685                                         for (int j = 0; j < number.length(); j++) {
686                                                 ref[count] = number.charAt(j);
687                                                 count += 1;
688                                         }
689                                         i -= 1; // Back to the last '0' character
690                                 }
691                                 // Keep the character
692                         } else {
693                                 ref[count] = format[i];
694                                 count += 1;
695                         }
696                 }
697                 // Incrementation of the number of study
698                 aBuilder.setBase(next);
699                 getIDBuilderDAO().update(aBuilder);
700                 return String.copyValueOf(ref, 0, count);
701         }
702
703         /**
704          * Find an id builder by date.
705          * 
706          * @param date
707          *            the date
708          * @return found id builder
709          */
710         private IDBuilder selectIDBuilder(final Date date) {
711                 Calendar aDate = Calendar.getInstance();
712                 aDate.setTime(date);
713                 return getIDBuilderDAO().findByCriteria(
714                                 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
715         }
716
717         /**
718          * Fill transient collection ModifiableActors of the study.
719          * 
720          * @param aStudy
721          *            the study
722          */
723         private void resetActorsShortCut(final Study aStudy) {
724                 getModifiableActors(aStudy).clear();
725                 // Get all actors involved in validation cycles
726                 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
727                                 .values().iterator(); i.hasNext();) {
728                         ValidationCycle cycle = i.next();
729                         User[] user = cycle.getAllActors();
730                         for (int j = 0; j < user.length; j++) {
731                                 getModifiableActors(aStudy).add(user[j]);
732                         }
733                 }
734                 // Get all other actors
735                 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
736                                 .hasNext();) {
737                         Relation link = i.next();
738                         Class<?> kindof = link.getClass().getSuperclass();
739                         if (!kindof.equals(ActorRelation.class)) {
740                                 continue;
741                         }
742                         getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
743                 }
744         }
745
746         /**
747          * Update knowledge elements states.
748          * 
749          * @param aStudy
750          *            the study
751          * @return true if succeeded
752          */
753         private boolean updateKnowledgeElementsState(final Study aStudy) {
754                 for (Scenario scenario : aStudy.getScenariiList()) {
755                         for (KnowledgeElement element : scenario.getAllKnowledgeElements()) {
756                                 element.setProgressState(aStudy.getProgressState());
757                         }
758                 }
759                 return true;
760         }
761
762         /**
763          * Get lucene index service. Create a lucene index if it does not exist.
764          * 
765          * @return index service
766          * @throws IOException
767          *             if error occurs during lucene index creation
768          */
769         private IndexService getIndex() throws IOException {
770                 IndexService lucin = getIndexService();
771                 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
772                                 .getRepositoryIndexDirectory()))) {
773                         IndexWriter.unlock(FSDirectory.open(getRepositoryService()
774                                         .getRepositoryIndexDirectory()));
775                 }
776                 if (!lucin.exists()) {
777                         lucin.create(); // Happens when re-indexing all studies
778                 }
779                 return lucin;
780         }
781
782         /**
783          * Create a new validation cycle for documents of the given study.
784          * 
785          * @param from
786          *            the study
787          * @param cycle
788          *            the cycle description
789          * @return the new validation cycle
790          */
791         protected ValidationCycle createValidationCycle(
792                         final Study from,
793                         final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
794                 Actor[] actype = cycle.getActorTypes();
795                 User.Properties uprop = new User.Properties();
796
797                 ValidationCycle aValidationCycle = new ValidationCycle();
798                 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
799                                 cycle.getName())); // Null in case of default validation cycle
800                 // context = new ValidationCycleRelation(from, vprop);
801                 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
802                 for (int i = 0; i < actype.length; i++) {
803                         User actor = null;
804                         if (actype[i] != null) {
805                                 try {
806                                         if (actype[i] == Actor.manager) {
807                                                 actor = from.getAuthor();
808                                         } else if (actype[i] == Actor.Nx1) {
809                                                 List<User> manager = getUserService().selectUsersWhere(
810                                                                 uprop.setOrganizationName("Nx1"));
811                                                 if (manager.size() == 1) {
812                                                         actor = manager.get(0);
813                                                 }
814                                         } else if (actype[i] == Actor.Nx2) {
815                                                 List<User> manager = getUserService().selectUsersWhere(
816                                                                 uprop.setOrganizationName("Nx2"));
817                                                 if (manager.size() == 1) {
818                                                         actor = manager.get(0);
819                                                 }
820                                         } else { /* Actor.customer */
821                                                 actor = from.getAuthor();
822                                                 // TODO: Get the customer of the study, if exists
823                                         }
824                                 } catch (Exception e) { // Should not happen
825                                         actor = null;
826                                 }
827                         }
828                         if (i == 0) {
829                                 aValidationCycle.setReviewer(actor);
830                         } else if (i == 1) {
831                                 aValidationCycle.setApprover(actor);
832                         } else if (i == 2) {
833                                 aValidationCycle.setSignatory(actor);
834                         }
835                 }
836                 return aValidationCycle;
837         }
838
839         /**
840          * Remove a validation step from the validation cycle.
841          * 
842          * @param aValidationCycle
843          *            the validation cycle
844          * @param step
845          *            the validation step to remove
846          */
847         @Transactional
848         protected void remove(final ValidationCycle aValidationCycle,
849                         final ValidationStep step) {
850                 if (step == ValidationStep.REVIEW) {
851                         aValidationCycle.setReviewer(null);
852                 } else if (step == ValidationStep.APPROVAL) {
853                         aValidationCycle.setApprover(null);
854                 } else if (step == ValidationStep.ACCEPTANCE
855                                 || step == ValidationStep.REFUSAL) {
856                         aValidationCycle.setSignatory(null);
857                 }
858                 if (aValidationCycle.isSaved()) {
859                         getValidationCycleDAO().update(aValidationCycle);
860                 }
861         }
862
863         /**
864          * Reset actors for the validation cycle.
865          * 
866          * @param aValidationCycle
867          *            the validation cycle to update
868          * @param vprop
869          *            new validation cycle properties containing new actors
870          */
871         @Transactional
872         public void resetActors(final ValidationCycle aValidationCycle,
873                         final ValidationCycle.Properties vprop) {
874                 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
875                 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
876                 aValidationCycle.setApprover(vprop.getApprover()); // May be null
877                 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
878                 if (aValidationCycle.isSaved()) {
879                         getValidationCycleDAO().merge(aValidationCycle);
880                 }
881         }
882
883         /**
884          * Set actor for the given validation cycle and validation step.
885          * 
886          * @param aValidationCycle
887          *            the validation cycle
888          * @param step
889          *            the validation step
890          * @param actor
891          *            the actor to set
892          */
893         @Transactional
894         protected void setActor(final ValidationCycle aValidationCycle,
895                         final ValidationStep step, final User actor) {
896                 if (step == ValidationStep.PROMOTION) {
897                         aValidationCycle.setPublisher(actor);
898                 } else if (step == ValidationStep.REVIEW) {
899                         aValidationCycle.setReviewer(actor);
900                 } else if (step == ValidationStep.APPROVAL) {
901                         aValidationCycle.setApprover(actor);
902                 } else if (step == ValidationStep.ACCEPTANCE
903                                 || step == ValidationStep.REFUSAL) {
904                         aValidationCycle.setSignatory(actor);
905                 }
906                 if (aValidationCycle.isSaved()) {
907                         getValidationCycleDAO().update(aValidationCycle);
908                 }
909         }
910
911         /**
912          * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
913          * 
914          * @param aStudy
915          *            the study
916          * @return the actors of this study
917          * @see #hasActor(User)
918          */
919         public Set<User> getActors(final Study aStudy) {
920                 if (aStudy.getActor() == null) {
921                         setShortCuts(aStudy);
922                 }
923                 return Collections.unmodifiableSet(aStudy.getActor());
924         }
925
926         /**
927          * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
928          * 
929          * @param aStudy
930          *            the study
931          * @return the modifiable set of actors of this study
932          * @see #hasActor(User)
933          */
934         public Set<User> getModifiableActors(final Study aStudy) {
935                 if (aStudy.getActor() == null) {
936                         setShortCuts(aStudy);
937                 }
938                 return aStudy.getActor();
939         }
940
941         /**
942          * Returns unmodifiable initialized transient list of contributors of this study.
943          * 
944          * @param aStudy
945          *            the study
946          * @return the unmodifiable not null transient list of contributors of this study
947          */
948         public List<User> getContributors(final Study aStudy) {
949                 if (aStudy.getContributor() == null) {
950                         setShortCuts(aStudy);
951                 }
952                 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
953         }
954
955         /**
956          * Returns modifiable initialized transient list of contributors of this study.
957          * 
958          * @param aStudy
959          *            the study
960          * @return the modifiable not null transient list of contributors of this study
961          */
962         public List<User> getModifiableContributors(final Study aStudy) {
963                 if (aStudy.getContributor() == null) {
964                         setShortCuts(aStudy);
965                 }
966                 return aStudy.getContributor(); // May be empty
967         }
968
969         /**
970          * Returns the validation cycle of the given document type.
971          * 
972          * @param aStudy
973          *            the study
974          * @param type
975          *            the document type being subject of validation
976          * @return the validation cycle of the document, or null if not defined.
977          */
978         public ValidationCycle getValidationCycleOf(final Study aStudy,
979                         final DocumentType type) {
980                 ValidationCycle result = null;
981                 if (aStudy != null) {
982                         if (aStudy.getValidationCycles() == null
983                                         || aStudy.getValidationCycles().isEmpty()) {
984                                 setShortCuts(aStudy);
985                         }
986                         if (type != null) {
987                                 result = aStudy.getValidationCycles().get(type.getName());
988                         }
989                 }
990                 if ((result == null) && (aStudy != null)) {
991                         if ((type == null) || type.isStepResult()) {
992                                 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
993                         }
994                         if (result == null) {
995                                 result = aStudy.getValidationCycles().get("built-in");
996                         }
997                 }
998                 return result;
999         }
1000
1001         /**
1002          * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
1003          * 
1004          * @param aStudy
1005          *            the study
1006          * @param user
1007          *            the user to look for
1008          * @return true if the given user is actor of this study.
1009          * @see #getActors()
1010          */
1011         public boolean hasActor(final Study aStudy, final User user) {
1012                 if (user == null) {
1013                         return false;
1014                 }
1015                 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
1016                         User involved = i.next();
1017                         if (involved.equals(user)) {
1018                                 return true;
1019                         }
1020                 }
1021                 return false;
1022         }
1023
1024         /**
1025          * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1026          * 
1027          * @param aStudy
1028          *            the study
1029          * @param user
1030          *            the user to look for
1031          * @return true if the given user is actor of this study.
1032          * @see #getContributors()
1033          */
1034         public boolean isStaffedBy(final Study aStudy, final User user) {
1035                 if (user == null) {
1036                         return false;
1037                 }
1038                 if (aStudy == null) {
1039                         return false;
1040                 }
1041                 if (aStudy.getAuthor() == null) {
1042                         return false;
1043                 }
1044                 if (aStudy.getAuthor().equals(user)) {
1045                         return true;
1046                 }
1047                 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1048                         if (i.next().equals(user)) {
1049                                 return true;
1050                         }
1051                 }
1052                 return false;
1053         }
1054
1055         /**
1056          * Initialize shortcuts of the study as its transient collections.
1057          * 
1058          * @param aStudy
1059          *            the study
1060          */
1061         public void loadWorkflow(final Study aStudy) {
1062                 setShortCuts(aStudy);
1063         }
1064
1065         /**
1066          * Initialize shortcuts of the study as its transient collections.
1067          * 
1068          * @param aStudy
1069          *            the study
1070          */
1071         public void setShortCuts(final Study aStudy) {
1072                 aStudy.getContributor().clear();
1073                 aStudy.getValidationCycles().clear();
1074                 aStudy.getActor().clear();
1075
1076                 // Get the contributors
1077                 for (Iterator<Relation> i = aStudy.getRelations(
1078                                 ContributorRelation.class).iterator(); i.hasNext();) {
1079                         ContributorRelation link = (ContributorRelation) i.next();
1080                         aStudy.getContributor().add(link.getTo());
1081                 }
1082                 // Get the validation cycles specific to this study
1083                 for (Iterator<Relation> i = aStudy.getRelations(
1084                                 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1085                         ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1086                         aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1087                                         link.getTo()); // The associated document type is necessarily not null in this
1088                         // context
1089                 }
1090                 // Get the validation cycles coming from the configured workflow and not overridden in this study
1091                 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1092                                 .getAllValidationCycles().iterator(); i.hasNext();) {
1093                         ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1094                                         .next();
1095                         String type = cycle.getName();
1096                         if (!aStudy.getValidationCycles().containsKey(type)) {
1097                                 aStudy.getValidationCycles().put(type,
1098                                                 createValidationCycle(aStudy, cycle));
1099                         }
1100                 }
1101                 // Get all corresponding actors
1102                 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1103                                 .values().iterator(); i.hasNext();) {
1104                         ValidationCycle cycle = i.next();
1105                         User[] user = cycle.getAllActors();
1106                         for (int j = 0; j < user.length; j++) {
1107                                 aStudy.getActor().add(user[j]);
1108                         }
1109                 }
1110                 // Get all other actors
1111                 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1112                                 .hasNext();) {
1113                         Relation link = i.next();
1114                         Class<?> kindof = link.getClass().getSuperclass();
1115                         if (!kindof.equals(ActorRelation.class)) {
1116                                 continue;
1117                         }
1118                         aStudy.getActor().add(((ActorRelation) link).getTo());
1119                 }
1120         }
1121
1122         /**
1123          * 
1124          * {@inheritDoc}
1125          * 
1126          * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
1127          */
1128         @Transactional
1129         public boolean markStudyAsReference(final Study aStudy) {
1130                 boolean res = false;
1131                 if (aStudy.getProgressState() == ProgressState.APPROVED) {
1132                         aStudy.setMarkreference(1);
1133                         aStudy.setProgressState(ProgressState.TEMPLATE);
1134                         res = updateKnowledgeElementsState(aStudy);
1135                         getStudyDAO().merge(aStudy);
1136                 }
1137                 return res;
1138         }
1139
1140         /**
1141          * 
1142          * {@inheritDoc}
1143          * 
1144          * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
1145          */
1146         @Transactional
1147         public void removeStudyAsReference(final Study aStudy) {
1148                 aStudy.setMarkreference(0);
1149                 aStudy.setProgressState(ProgressState.APPROVED);
1150                 updateKnowledgeElementsState(aStudy);
1151                 getStudyDAO().merge(aStudy);
1152         }
1153
1154         /**
1155          * {@inheritDoc}
1156          * 
1157          * @see org.splat.service.StudyService#getDescription(java.lang.Long)
1158          */
1159         @Override
1160         @Transactional(readOnly = true)
1161         public String getDescription(final Long studyId)
1162                         throws InvalidParameterException {
1163                 if (studyId == null) {
1164                         throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1165                 }
1166                 Study study = _studyDAO.get(studyId);
1167                 if (study == null) {
1168                         throw new InvalidParameterException(PARAM_STUDY_ID, studyId
1169                                         .toString());
1170                 }
1171                 return study.getDescription();
1172         }
1173
1174         /**
1175          * {@inheritDoc}
1176          * 
1177          * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
1178          */
1179         @Transactional
1180         public void setDescription(final Long studyId, final String descriptionText)
1181                         throws InvalidParameterException {
1182                 if (studyId == null) {
1183                         throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1184                 }
1185                 Study study = _studyDAO.get(studyId);
1186                 if (study == null) {
1187                         throw new InvalidParameterException(PARAM_STUDY_ID, studyId
1188                                         .toString());
1189                 }
1190                 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1191         }
1192
1193         /**
1194          * {@inheritDoc}
1195          * 
1196          * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
1197          */
1198         @Transactional
1199         public boolean removeDescription(final Long studyId)
1200                         throws InvalidParameterException {
1201                 if (studyId == null) {
1202                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1203                                         .valueOf(studyId));
1204                 }
1205                 Study study = _studyDAO.get(studyId);
1206                 if (study == null) {
1207                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1208                                         .valueOf(studyId));
1209                 }
1210                 return study.removeAttribute(study
1211                                 .getAttribute(DescriptionAttribute.class));
1212         }
1213
1214         /**
1215          * 
1216          * {@inheritDoc}
1217          * 
1218          * @see org.splat.service.StudyService#compare(java.util.List)
1219          */
1220         @Override
1221         public String compare(final List<DocToCompareDTO> docsList,
1222                         final String userName) throws IncompatibleDataException {
1223
1224                 String axis1Name = "";
1225                 String axis2Name = "";
1226                 String chartTitle = "";
1227                 String resultPath = "";
1228
1229                 XYSeriesCollection dataset = new XYSeriesCollection();
1230
1231                 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1232
1233                 for (; docListIter.hasNext();) {
1234
1235                         DocToCompareDTO docDTO = docListIter.next();
1236                         String pathToFile = docDTO.getPathToFile();
1237                         File compDocFile = new File(pathToFile);
1238
1239                         resultPath = pathToFile.substring(0, pathToFile.indexOf("vault"))
1240                                         + "downloads" + File.separator + userName + File.separator
1241                                         + "ComparisonResult.pdf";
1242
1243                         XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle()
1244                                         + " Scenario: " + docDTO.getScenarioTitle() + " Document: "
1245                                         + docDTO.getDocumentTitle());
1246
1247                         // read the file and get points information.
1248                         try {
1249                                 Scanner input = new Scanner(compDocFile);
1250
1251                                 // get the title of the chart.
1252                                 if (input.hasNext()) {
1253                                         chartTitle = input.nextLine();
1254                                 }
1255
1256                                 // get the name of the axis.
1257                                 if (input.hasNext()) {
1258                                         String[] tokens = input.nextLine().split(",");
1259
1260                                         if (tokens.length < 2) {
1261                                                 throw new IncompatibleDataException(
1262                                                                 MessageKeyEnum.IDT_000001.toString());
1263                                         }
1264
1265                                         if ("".equals(axis1Name)) {
1266                                                 axis1Name = tokens[0];
1267                                         } else if (!axis1Name.equals(tokens[0])) {
1268                                                 LOG.debug("Axis must be the same for all documents");
1269                                                 throw new IncompatibleDataException(
1270                                                                 MessageKeyEnum.IDT_000001.toString());
1271                                         }
1272
1273                                         if ("".equals(axis2Name)) {
1274                                                 axis2Name = tokens[1];
1275                                         } else if (!axis2Name.equals(tokens[1])) {
1276                                                 LOG.debug("Axis must be the same for all documents");
1277                                                 throw new IncompatibleDataException(
1278                                                                 MessageKeyEnum.IDT_000001.toString());
1279                                         }
1280                                 }
1281
1282                                 // Get the XY points series.
1283                                 while (input.hasNext()) {
1284
1285                                         String currentString = input.nextLine();
1286
1287                                         if (!("".equals(currentString))) {
1288                                                 String[] tokens = currentString.split(" ");
1289                                                 series.add(Double.valueOf(tokens[0]), Double
1290                                                                 .valueOf(tokens[1]));
1291                                         }
1292
1293                                 } // while
1294
1295                                 dataset.addSeries(series);
1296
1297                         } catch (FileNotFoundException e) {
1298                                 LOG.error("Sorry, the file is not found.", e);
1299                         }
1300                 } // for
1301
1302                 JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // Title
1303                                 axis1Name, // x-axis Label
1304                                 axis2Name, // y-axis Label
1305                                 dataset, // Dataset
1306                                 PlotOrientation.VERTICAL, // Plot Orientation
1307                                 true, // Show Legend
1308                                 true, // Use tooltips
1309                                 false // Configure chart to generate URLs?
1310                                 );
1311
1312                 // export to PDF - file.
1313                 int x = 500;
1314                 int y = 300;
1315                 Rectangle pagesize = new Rectangle(x, y);
1316                 Document document = new Document(pagesize, 50, 50, 50, 50);
1317                 PdfWriter writer;
1318                 try {
1319                         File resFile = new File(resultPath);
1320                         File resFolder = new File(resultPath.substring(0, resultPath
1321                                         .lastIndexOf(File.separator)));
1322                         resFolder.mkdirs();
1323                         writer = PdfWriter.getInstance(document, new FileOutputStream(
1324                                         resFile));
1325
1326                         document.open();
1327                         PdfContentByte cb = writer.getDirectContent();
1328                         PdfTemplate tp = cb.createTemplate(x, y);
1329                         Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1330                         chart.draw(g2, new java.awt.Rectangle(x, y));
1331                         g2.dispose();
1332                         cb.addTemplate(tp, 0, 0);
1333                         document.close();
1334
1335                 } catch (FileNotFoundException e) {
1336                         LOG.error("Sorry, the file is not found.", e);
1337                 } catch (DocumentException e) {
1338                         LOG.error("Sorry, the DocumentException is thrown.", e);
1339                 }
1340
1341                 return resultPath;
1342         }
1343
1344         /**
1345          * {@inheritDoc}
1346          * 
1347          * @see org.splat.service.StudyService#getReaders(long)
1348          */
1349         @Transactional(readOnly = true)
1350         public List<UserDTO> getReaders(final long studyId)
1351                         throws InvalidParameterException {
1352                 Study aStudy = selectStudy(studyId);
1353                 if (aStudy == null) {
1354                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1355                                         .valueOf(studyId));
1356                 }
1357                 List<Relation> relations = aStudy.getRelations(ReaderRelation.class);
1358                 List<UserDTO> result = new ArrayList<UserDTO>();
1359                 for (Relation relation : relations) {
1360                         result.add(BeanHelper.copyBean(relation.getTo(), UserDTO.class));
1361                 }
1362                 return Collections.unmodifiableList(result);
1363         }
1364
1365         /**
1366          * {@inheritDoc}
1367          * 
1368          * @see org.splat.service.StudyService#addReader(long, long)
1369          */
1370         @Transactional
1371         public boolean addReader(final long studyId, final long userId)
1372                         throws InvalidParameterException {
1373                 Study aStudy = selectStudy(studyId);
1374                 if (aStudy == null) {
1375                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1376                                         .valueOf(studyId));
1377                 }
1378                 User user = _userService.selectUser(userId);
1379                 if (user == null) {
1380                         throw new InvalidParameterException("userId", String
1381                                         .valueOf(userId));
1382                 }
1383
1384                 for (Relation relation : aStudy.getRelations(ReaderRelation.class)) {
1385                         if (user.equals(relation.getTo())) {
1386                                 return false;
1387                         }
1388                 }
1389                 aStudy.addRelation(new ReaderRelation(aStudy, user));
1390                 update(aStudy);
1391                 return true;
1392         }
1393
1394         /**
1395          * {@inheritDoc}
1396          * 
1397          * @see org.splat.service.StudyService#removeReader(long, long)
1398          */
1399         @Transactional
1400         public boolean removeReader(final long studyId, final long userId)
1401                         throws InvalidParameterException {
1402                 Study aStudy = selectStudy(studyId);
1403                 if (aStudy == null) {
1404                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1405                                         .valueOf(studyId));
1406                 }
1407                 User user = _userService.selectUser(userId);
1408                 if (user == null) {
1409                         throw new InvalidParameterException("userId", String
1410                                         .valueOf(userId));
1411                 }
1412
1413                 Relation relation = aStudy.removeRelation(ReaderRelation.class, user);
1414                 update(aStudy);
1415                 return relation != null;
1416         }
1417
1418         /**
1419          * Get project settings.
1420          * 
1421          * @return Project settings service
1422          */
1423         private ProjectSettingsService getProjectSettings() {
1424                 return _projectSettings;
1425         }
1426
1427         /**
1428          * Set project settings service.
1429          * 
1430          * @param projectSettingsService
1431          *            project settings service
1432          */
1433         public void setProjectSettings(
1434                         final ProjectSettingsService projectSettingsService) {
1435                 _projectSettings = projectSettingsService;
1436         }
1437
1438         /**
1439          * Get the projectElementService.
1440          * 
1441          * @return the projectElementService
1442          */
1443         public ProjectElementService getProjectElementService() {
1444                 return _projectElementService;
1445         }
1446
1447         /**
1448          * Set the projectElementService.
1449          * 
1450          * @param projectElementService
1451          *            the projectElementService to set
1452          */
1453         public void setProjectElementService(
1454                         final ProjectElementService projectElementService) {
1455                 _projectElementService = projectElementService;
1456         }
1457
1458         /**
1459          * Get the stepService.
1460          * 
1461          * @return the stepService
1462          */
1463         public StepService getStepService() {
1464                 return _stepService;
1465         }
1466
1467         /**
1468          * Set the stepService.
1469          * 
1470          * @param stepService
1471          *            the stepService to set
1472          */
1473         public void setStepService(final StepService stepService) {
1474                 _stepService = stepService;
1475         }
1476
1477         /**
1478          * Get the indexService.
1479          * 
1480          * @return the indexService
1481          */
1482         public IndexService getIndexService() {
1483                 return _indexService;
1484         }
1485
1486         /**
1487          * Set the indexService.
1488          * 
1489          * @param indexService
1490          *            the indexService to set
1491          */
1492         public void setIndexService(final IndexService indexService) {
1493                 _indexService = indexService;
1494         }
1495
1496         /**
1497          * Get the studyDAO.
1498          * 
1499          * @return the studyDAO
1500          */
1501         public StudyDAO getStudyDAO() {
1502                 return _studyDAO;
1503         }
1504
1505         /**
1506          * Set the studyDAO.
1507          * 
1508          * @param studyDAO
1509          *            the studyDAO to set
1510          */
1511         public void setStudyDAO(final StudyDAO studyDAO) {
1512                 _studyDAO = studyDAO;
1513         }
1514
1515         /**
1516          * Get the iDBuilderDAO.
1517          * 
1518          * @return the iDBuilderDAO
1519          */
1520         public IDBuilderDAO getIDBuilderDAO() {
1521                 return _iDBuilderDAO;
1522         }
1523
1524         /**
1525          * Set the iDBuilderDAO.
1526          * 
1527          * @param builderDAO
1528          *            the iDBuilderDAO to set
1529          */
1530         public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1531                 _iDBuilderDAO = builderDAO;
1532         }
1533
1534         /**
1535          * Get the scenarioDAO.
1536          * 
1537          * @return the scenarioDAO
1538          */
1539         public ScenarioDAO getScenarioDAO() {
1540                 return _scenarioDAO;
1541         }
1542
1543         /**
1544          * Set the scenarioDAO.
1545          * 
1546          * @param scenarioDAO
1547          *            the scenarioDAO to set
1548          */
1549         public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1550                 _scenarioDAO = scenarioDAO;
1551         }
1552
1553         /**
1554          * Get the validationCycleDAO.
1555          * 
1556          * @return the validationCycleDAO
1557          */
1558         public ValidationCycleDAO getValidationCycleDAO() {
1559                 return _validationCycleDAO;
1560         }
1561
1562         /**
1563          * Set the validationCycleDAO.
1564          * 
1565          * @param validationCycleDAO
1566          *            the validationCycleDAO to set
1567          */
1568         public void setValidationCycleDAO(
1569                         final ValidationCycleDAO validationCycleDAO) {
1570                 _validationCycleDAO = validationCycleDAO;
1571         }
1572
1573         /**
1574          * Get the documentTypeService.
1575          * 
1576          * @return the documentTypeService
1577          */
1578         public DocumentTypeService getDocumentTypeService() {
1579                 return _documentTypeService;
1580         }
1581
1582         /**
1583          * Set the documentTypeService.
1584          * 
1585          * @param documentTypeService
1586          *            the documentTypeService to set
1587          */
1588         public void setDocumentTypeService(
1589                         final DocumentTypeService documentTypeService) {
1590                 _documentTypeService = documentTypeService;
1591         }
1592
1593         /**
1594          * Get the userService.
1595          * 
1596          * @return the userService
1597          */
1598         public UserService getUserService() {
1599                 return _userService;
1600         }
1601
1602         /**
1603          * Set the userService.
1604          * 
1605          * @param userService
1606          *            the userService to set
1607          */
1608         public void setUserService(final UserService userService) {
1609                 _userService = userService;
1610         }
1611
1612         /**
1613          * {@inheritDoc}
1614          * 
1615          * @see org.splat.service.StudyService#getComparableStudies()
1616          */
1617         @Transactional(readOnly = true)
1618         public List<StudyFacadeDTO> getComparableStudies(final long userId)
1619                         throws MismatchException {
1620                 // retrieve the number of the "Analyze the results" step
1621                 List<Step> allSteps = _projectSettings.getAllSteps();
1622                 Step theAnalyzeStep = null;
1623                 for (Step step : allSteps) {
1624                         if (step.getKey().equals("postprocessing")) {
1625                                 theAnalyzeStep = step;
1626                         }
1627                 }
1628                 if (theAnalyzeStep == null) { // TODO: throw some other exception
1629                         throw new MismatchException(
1630                                         "no step with key 'postprocessing' found."
1631                                                         + "Probably, customization settings have been changed.");
1632                 }
1633
1634                 List<Publication> publications = _publicationDAO.getFilteredList(
1635                                 "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep
1636                                                 .getNumber())));
1637
1638                 // split retrieved publications into groups by studies and scenarios
1639                 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1640                 Map<ProjectElement, List<Publication>> scenarioMap = new HashMap<ProjectElement, List<Publication>>();
1641
1642                 for (Publication publication : publications) {
1643                         // filter out publications corresponding to a document of given step which is not a _result_ document
1644                         if (!publication.value().getType().isResultOf(theAnalyzeStep)
1645                                         || !"srd".equals(publication.getSourceFile().getFormat())) {
1646                                 continue;
1647                         }
1648
1649                         // check the study visibility to the user
1650                         if (!isStaffedBy(publication.getOwnerStudy(), _userService
1651                                         .selectUser(userId))
1652                                         && Visibility.PUBLIC.equals(publication.getOwnerStudy()
1653                                                         .getVisibility())) {
1654                                 continue;
1655                         }
1656
1657                         Study study = publication.getOwnerStudy();
1658                         ProjectElement scenario = publication.getOwner();
1659
1660                         Hibernate.initialize(scenario);
1661                         if (scenario instanceof HibernateProxy) {
1662                                 scenario = (ProjectElement) ((HibernateProxy) scenario)
1663                                                 .getHibernateLazyInitializer().getImplementation();
1664                         }
1665
1666                         if (!(scenario instanceof Scenario)) {
1667                                 throw new MismatchException(
1668                                                 "publications from postprocessing step are supposed to have owner scenario");
1669                         }
1670
1671                         if (!studyMap.containsKey(study)) {
1672                                 studyMap.put(study, new ArrayList<ProjectElement>());
1673                         }
1674
1675                         if (!studyMap.get(study).contains(scenario)) {
1676                                 studyMap.get(study).add(scenario);
1677                         }
1678
1679                         if (!scenarioMap.containsKey(scenario)) {
1680                                 scenarioMap.put(scenario, new ArrayList<Publication>());
1681                         }
1682                         scenarioMap.get(scenario).add(publication);
1683                 }
1684
1685                 // Create the result DTOs
1686                 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1687                 for (Study study : studyMap.keySet()) {
1688
1689                         StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1690                         studyDTO.setName(study.getTitle());
1691                         studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1692                         result.add(studyDTO);
1693
1694                         for (ProjectElement scenario : studyMap.get(study)) {
1695
1696                                 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1697                                 scenarioDTO.setName(scenario.getTitle());
1698                                 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1699                                 studyDTO.getScenarios().add(scenarioDTO);
1700
1701                                 for (Publication publication : scenarioMap.get(scenario)) {
1702
1703                                         DocumentDTO documentDTO = new DocumentDTO();
1704                                         documentDTO.setId(publication.getIndex());
1705                                         documentDTO.setTitle(publication.value().getTitle());
1706
1707                                         scenarioDTO.getDocs().add(documentDTO);
1708                                 }
1709                         }
1710                 }
1711                 return result;
1712         }
1713
1714         /**
1715          * Get the publicationDAO.
1716          * 
1717          * @return the publicationDAO
1718          */
1719         public PublicationDAO getPublicationDAO() {
1720                 return _publicationDAO;
1721         }
1722
1723         /**
1724          * Set the publicationDAO.
1725          * 
1726          * @param publicationDAO
1727          *            the publicationDAO to set
1728          */
1729         public void setPublicationDAO(final PublicationDAO publicationDAO) {
1730                 _publicationDAO = publicationDAO;
1731         }
1732
1733         /**
1734          * Get the repositoryService.
1735          * 
1736          * @return the repositoryService
1737          */
1738         public RepositoryService getRepositoryService() {
1739                 return _repositoryService;
1740         }
1741
1742         /**
1743          * Set the repositoryService.
1744          * 
1745          * @param repositoryService
1746          *            the repositoryService to set
1747          */
1748         public void setRepositoryService(final RepositoryService repositoryService) {
1749                 _repositoryService = repositoryService;
1750         }
1751
1752         /**
1753          * Get the documentDAO.
1754          * 
1755          * @return the documentDAO
1756          */
1757         public DocumentDAO getDocumentDAO() {
1758                 return _documentDAO;
1759         }
1760
1761         /**
1762          * Set the documentDAO.
1763          * 
1764          * @param documentDAO
1765          *            the documentDAO to set
1766          */
1767         public void setDocumentDAO(final DocumentDAO documentDAO) {
1768                 _documentDAO = documentDAO;
1769         }
1770
1771         /**
1772          * Get the descriptionAttributeDAO.
1773          * 
1774          * @return the descriptionAttributeDAO
1775          */
1776         public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1777                 return _descriptionAttributeDAO;
1778         }
1779
1780         /**
1781          * Set the descriptionAttributeDAO.
1782          * 
1783          * @param descriptionAttributeDAO
1784          *            the descriptionAttributeDAO to set
1785          */
1786         public void setDescriptionAttributeDAO(
1787                         final DescriptionAttributeDAO descriptionAttributeDAO) {
1788                 _descriptionAttributeDAO = descriptionAttributeDAO;
1789         }
1790
1791         /**
1792          * Get the usedByRelationDAO.
1793          * 
1794          * @return the usedByRelationDAO
1795          */
1796         public UsedByRelationDAO getUsedByRelationDAO() {
1797                 return _usedByRelationDAO;
1798         }
1799
1800         /**
1801          * Set the usedByRelationDAO.
1802          * 
1803          * @param usedByRelationDAO
1804          *            the usedByRelationDAO to set
1805          */
1806         public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
1807                 _usedByRelationDAO = usedByRelationDAO;
1808         }
1809
1810         /**
1811          * {@inheritDoc}
1812          * 
1813          * @see org.splat.service.StudyService#getStudyResultType(org.splat.dal.bo.som.Study)
1814          */
1815         @Override
1816         @Transactional(readOnly = true)
1817         public DocumentType getStudyResultType(final Study study) {
1818                 DetachedCriteria query = DetachedCriteria.forClass(DocumentType.class)
1819                                 .addOrder(Order.desc("result"));
1820                 return getDocumentTypeDAO().getFirstResult(query);
1821         }
1822
1823         /**
1824          * Get the documentTypeDAO.
1825          * 
1826          * @return the documentTypeDAO
1827          */
1828         public DocumentTypeDAO getDocumentTypeDAO() {
1829                 return _documentTypeDAO;
1830         }
1831
1832         /**
1833          * Set the documentTypeDAO.
1834          * 
1835          * @param documentTypeDAO
1836          *            the documentTypeDAO to set
1837          */
1838         public void setDocumentTypeDAO(final DocumentTypeDAO documentTypeDAO) {
1839                 _documentTypeDAO = documentTypeDAO;
1840         }
1841
1842         /**
1843          * {@inheritDoc}
1844          * 
1845          * @see org.splat.service.StudyService#canBeApproved(org.splat.dal.bo.som.Study)
1846          */
1847         @Override
1848         @Transactional(readOnly = true)
1849         public boolean canBeApproved(final Study study) {
1850                 return resultDocsAtLeast(study, ProgressState.APPROVED);
1851         }
1852
1853         /**
1854          * {@inheritDoc}
1855          * 
1856          * @see org.splat.service.StudyService#canBePromoted(org.splat.dal.bo.som.Study)
1857          */
1858         @Override
1859         @Transactional(readOnly = true)
1860         public boolean canBePromoted(final Study study) {
1861                 return resultDocsAtLeast(study, ProgressState.inDRAFT);
1862         }
1863
1864         /**
1865          * {@inheritDoc}
1866          * 
1867          * @see org.splat.service.StudyService#canBeReviewed(org.splat.dal.bo.som.Study)
1868          */
1869         @Override
1870         @Transactional(readOnly = true)
1871         public boolean canBeReviewed(final Study study) {
1872                 return resultDocsAtLeast(study, ProgressState.inCHECK);
1873         }
1874
1875         /**
1876          * Check that all result documents of the study are at least in the given state.
1877          * 
1878          * @param study
1879          *            the study to check
1880          * @param state
1881          *            the minimal acceptable state
1882          * @return true if study result documents have acceptable states
1883          */
1884         private boolean resultDocsAtLeast(final Study study,
1885                         final ProgressState state) {
1886                 boolean res = true;
1887                 // Check that all study result documents have the state APPROVED or more.
1888                 for (Publication pub : getProjectElementService().getLastStep(study)
1889                                 .getResultDocuments()) {
1890                         res = pub.getProgressState().compareTo(ProgressState.APPROVED) >= 0;
1891                         if (!res) {
1892                                 break;
1893                         }
1894                 }
1895                 return res;
1896         }
1897 }