Salome HOME
2e4079229c690686a26a58012ed64b4bbf722599
[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                 ValidationCycle cycle = getValidationCycleOf(aStudy,
511                                 getStudyResultType(aStudy));
512
513                 if (aStudy.getProgressState() == ProgressState.inWORK
514                                 && cycle.enables(ValidationStep.REVIEW)
515                                 && canBePromoted(aStudy)) {
516                         aStudy.setProgressState(ProgressState.inDRAFT);
517                 } else if (((!cycle.enables(ValidationStep.REVIEW) && ((aStudy
518                                 .getProgressState() == ProgressState.inWORK) || (aStudy
519                                 .getProgressState() == ProgressState.inDRAFT))) || (cycle
520                                 .enables(ValidationStep.REVIEW) && (aStudy.getProgressState() == ProgressState.inDRAFT)))
521                                 && canBeReviewed(aStudy)) {
522                         aStudy.setProgressState(ProgressState.inCHECK);
523                         Revision myvers = new Revision(aStudy.getVersion());
524                         if (myvers.isMinor()) {
525                                 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
526                                                 .toString());
527                         }
528                 } else if (aStudy.getProgressState() == ProgressState.inCHECK
529                                 && canBeApproved(aStudy)) {
530                         aStudy.setProgressState(ProgressState.APPROVED);
531                         updateKnowledgeElementsState(aStudy);
532                 } else {
533                         res = false;
534                 }
535                 if (res) {
536                         res = update(aStudy);
537                 }
538
539                 return res;
540         }
541
542         /**
543          * Demotes this study from In-Check or In-Draft to In-Work states.
544          * 
545          * @param aStudy
546          *            a study to demote
547          * @return true if the demotion succeeded.
548          */
549         @Transactional
550         public boolean demote(final Study aStudy) {
551                 boolean res;
552
553                 if (aStudy.getProgressState() == ProgressState.inCHECK
554                                 || aStudy.getProgressState() == ProgressState.inDRAFT) {
555                         aStudy.setProgressState(ProgressState.inWORK);
556                         res = update(aStudy);
557                 } else {
558                         res = false;
559                 }
560                 return res;
561         }
562
563         /**
564          * Moves this study from the Private to the Public area of the repository.
565          * 
566          * @param aStudy
567          *            a study to move
568          * @return true if the move succeeded.
569          * @see #isPublic()
570          */
571         @Transactional
572         public boolean moveToPublic(final Study aStudy) {
573                 boolean isOk = false;
574                 if (aStudy.getVisibility() == Visibility.PRIVATE) {
575                         aStudy.setVisibility(Visibility.PUBLIC);
576                         if (update(aStudy)) {
577                                 isOk = updateKnowledgeElementsState(aStudy); // If fails, the database roll-back is under responsibility of the caller
578                         }
579                 }
580                 return isOk;
581         }
582
583         /**
584          * Moves this study from the Public to the Private area of the repository.
585          * 
586          * @param aStudy
587          *            a study to move
588          * @return true if the move succeeded.
589          */
590         @Transactional
591         public boolean moveToPrivate(final Study aStudy) {
592                 boolean isOk = false;
593                 if (aStudy.getVisibility() == Visibility.PUBLIC) {
594                         aStudy.setVisibility(Visibility.PRIVATE);
595                         if (update(aStudy)) {
596                                 isOk = updateKnowledgeElementsState(aStudy); // If fails, the database roll-back is under responsibility of the caller
597                         }
598                 }
599                 return isOk;
600         }
601
602         /**
603          * Update a study in the database.
604          * 
605          * @param aStudy
606          *            the study to update
607          * @return true if the study is updated successfully
608          */
609         private boolean update(final Study aStudy) {
610                 boolean isOk = false;
611                 try {
612                         getStudyDAO().merge(aStudy); // Update of relational base
613                         setShortCuts(aStudy); // RKV: initialize transient actors set
614                         // RKV: getIndex().update(aStudy); // Update of Lucene index
615                         isOk = true;
616                 } catch (Exception e) {
617                         LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
618                 }
619                 return isOk;
620         }
621
622         /**
623          * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
624          * 
625          * @param aStudy
626          *            the study
627          * @return true if reference building is succeded
628          */
629         @Transactional
630         private boolean buildReference(final Study aStudy) {
631                 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
632                 IDBuilder tool = selectIDBuilder(aStudy.getDate());
633                 if (tool == null) {
634                         tool = new IDBuilder(aStudy.getDate());
635                         getIDBuilderDAO().create(tool);
636                 }
637                 aStudy.setReference(buildReference(tool, pattern, aStudy));
638                 return true;
639         }
640
641         /**
642          * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
643          * 
644          * @param aBuilder
645          *            the id builder
646          * @param study
647          *            the study
648          * @param pattern
649          *            the reference pattern
650          * @return true if reference building is succeded
651          */
652         @Transactional
653         public String buildReference(final IDBuilder aBuilder,
654                         final String pattern, final Study study) {
655                 char[] format = pattern.toCharArray();
656                 char[] ref = new char[80]; // Better evaluate the length of the generated string
657                 int next = aBuilder.getBase() + 1;
658
659                 int count = 0;
660                 for (int i = 0; i < format.length; i++) {
661
662                         // Insertion of attribute values
663                         if (format[i] == '%') {
664                                 i += 1;
665
666                                 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
667                                         int n = i;
668                                         while (format[i] == 'y') {
669                                                 i += 1;
670                                                 if (i == format.length) {
671                                                         break;
672                                                 }
673                                         }
674                                         SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
675                                         String year = tostring.format(study.getDate());
676                                         year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
677                                         for (int j = 0; j < year.length(); j++) {
678                                                 ref[count] = year.charAt(j);
679                                                 count += 1;
680                                         }
681                                         i -= 1; // Back to the last 'y' character
682                                 } else if (format[i] == '0') { // Insertion of the index
683                                         int n = i;
684                                         while (format[i] == '0') {
685                                                 i += 1;
686                                                 if (i == format.length) {
687                                                         break;
688                                                 }
689                                         }
690                                         DecimalFormat tostring = new DecimalFormat(pattern
691                                                         .substring(n, i));
692                                         String number = tostring.format(next);
693                                         for (int j = 0; j < number.length(); j++) {
694                                                 ref[count] = number.charAt(j);
695                                                 count += 1;
696                                         }
697                                         i -= 1; // Back to the last '0' character
698                                 }
699                                 // Keep the character
700                         } else {
701                                 ref[count] = format[i];
702                                 count += 1;
703                         }
704                 }
705                 // Incrementation of the number of study
706                 aBuilder.setBase(next);
707                 getIDBuilderDAO().update(aBuilder);
708                 return String.copyValueOf(ref, 0, count);
709         }
710
711         /**
712          * Find an id builder by date.
713          * 
714          * @param date
715          *            the date
716          * @return found id builder
717          */
718         private IDBuilder selectIDBuilder(final Date date) {
719                 Calendar aDate = Calendar.getInstance();
720                 aDate.setTime(date);
721                 return getIDBuilderDAO().findByCriteria(
722                                 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
723         }
724
725         /**
726          * Fill transient collection ModifiableActors of the study.
727          * 
728          * @param aStudy
729          *            the study
730          */
731         private void resetActorsShortCut(final Study aStudy) {
732                 getModifiableActors(aStudy).clear();
733                 // Get all actors involved in validation cycles
734                 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
735                                 .values().iterator(); i.hasNext();) {
736                         ValidationCycle cycle = i.next();
737                         User[] user = cycle.getAllActors();
738                         for (int j = 0; j < user.length; j++) {
739                                 getModifiableActors(aStudy).add(user[j]);
740                         }
741                 }
742                 // Get all other actors
743                 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
744                                 .hasNext();) {
745                         Relation link = i.next();
746                         Class<?> kindof = link.getClass().getSuperclass();
747                         if (!kindof.equals(ActorRelation.class)) {
748                                 continue;
749                         }
750                         getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
751                 }
752         }
753
754         /**
755          * Update knowledge elements states.
756          * 
757          * @param aStudy
758          *            the study
759          * @return true if succeeded
760          */
761         private boolean updateKnowledgeElementsState(final Study aStudy) {
762                 for (Scenario scenario : aStudy.getScenariiList()) {
763                         for (KnowledgeElement element : scenario.getAllKnowledgeElements()) {
764                                 element.setProgressState(aStudy.getProgressState());
765                         }
766                 }
767                 return true;
768         }
769
770         /**
771          * Get lucene index service. Create a lucene index if it does not exist.
772          * 
773          * @return index service
774          * @throws IOException
775          *             if error occurs during lucene index creation
776          */
777         private IndexService getIndex() throws IOException {
778                 IndexService lucin = getIndexService();
779                 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
780                                 .getRepositoryIndexDirectory()))) {
781                         IndexWriter.unlock(FSDirectory.open(getRepositoryService()
782                                         .getRepositoryIndexDirectory()));
783                 }
784                 if (!lucin.exists()) {
785                         lucin.create(); // Happens when re-indexing all studies
786                 }
787                 return lucin;
788         }
789
790         /**
791          * Create a new validation cycle for documents of the given study.
792          * 
793          * @param from
794          *            the study
795          * @param cycle
796          *            the cycle description
797          * @return the new validation cycle
798          */
799         protected ValidationCycle createValidationCycle(
800                         final Study from,
801                         final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
802                 Actor[] actype = cycle.getActorTypes();
803                 User.Properties uprop = new User.Properties();
804
805                 ValidationCycle aValidationCycle = new ValidationCycle();
806                 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
807                                 cycle.getName())); // Null in case of default validation cycle
808                 // context = new ValidationCycleRelation(from, vprop);
809                 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
810                 for (int i = 0; i < actype.length; i++) {
811                         User actor = null;
812                         if (actype[i] != null) {
813                                 try {
814                                         if (actype[i] == Actor.manager) {
815                                                 actor = from.getAuthor();
816                                         } else if (actype[i] == Actor.Nx1) {
817                                                 List<User> manager = getUserService().selectUsersWhere(
818                                                                 uprop.setOrganizationName("Nx1"));
819                                                 if (manager.size() == 1) {
820                                                         actor = manager.get(0);
821                                                 }
822                                         } else if (actype[i] == Actor.Nx2) {
823                                                 List<User> manager = getUserService().selectUsersWhere(
824                                                                 uprop.setOrganizationName("Nx2"));
825                                                 if (manager.size() == 1) {
826                                                         actor = manager.get(0);
827                                                 }
828                                         } else { /* Actor.customer */
829                                                 actor = from.getAuthor();
830                                                 // TODO: Get the customer of the study, if exists
831                                         }
832                                 } catch (Exception e) { // Should not happen
833                                         actor = null;
834                                 }
835                         }
836                         if (i == 0) {
837                                 aValidationCycle.setReviewer(actor);
838                         } else if (i == 1) {
839                                 aValidationCycle.setApprover(actor);
840                         } else if (i == 2) {
841                                 aValidationCycle.setSignatory(actor);
842                         }
843                 }
844                 return aValidationCycle;
845         }
846
847         /**
848          * Remove a validation step from the validation cycle.
849          * 
850          * @param aValidationCycle
851          *            the validation cycle
852          * @param step
853          *            the validation step to remove
854          */
855         @Transactional
856         protected void remove(final ValidationCycle aValidationCycle,
857                         final ValidationStep step) {
858                 if (step == ValidationStep.REVIEW) {
859                         aValidationCycle.setReviewer(null);
860                 } else if (step == ValidationStep.APPROVAL) {
861                         aValidationCycle.setApprover(null);
862                 } else if (step == ValidationStep.ACCEPTANCE
863                                 || step == ValidationStep.REFUSAL) {
864                         aValidationCycle.setSignatory(null);
865                 }
866                 if (aValidationCycle.isSaved()) {
867                         getValidationCycleDAO().update(aValidationCycle);
868                 }
869         }
870
871         /**
872          * Reset actors for the validation cycle.
873          * 
874          * @param aValidationCycle
875          *            the validation cycle to update
876          * @param vprop
877          *            new validation cycle properties containing new actors
878          */
879         @Transactional
880         public void resetActors(final ValidationCycle aValidationCycle,
881                         final ValidationCycle.Properties vprop) {
882                 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
883                 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
884                 aValidationCycle.setApprover(vprop.getApprover()); // May be null
885                 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
886                 if (aValidationCycle.isSaved()) {
887                         getValidationCycleDAO().merge(aValidationCycle);
888                 }
889         }
890
891         /**
892          * Set actor for the given validation cycle and validation step.
893          * 
894          * @param aValidationCycle
895          *            the validation cycle
896          * @param step
897          *            the validation step
898          * @param actor
899          *            the actor to set
900          */
901         @Transactional
902         protected void setActor(final ValidationCycle aValidationCycle,
903                         final ValidationStep step, final User actor) {
904                 if (step == ValidationStep.PROMOTION) {
905                         aValidationCycle.setPublisher(actor);
906                 } else if (step == ValidationStep.REVIEW) {
907                         aValidationCycle.setReviewer(actor);
908                 } else if (step == ValidationStep.APPROVAL) {
909                         aValidationCycle.setApprover(actor);
910                 } else if (step == ValidationStep.ACCEPTANCE
911                                 || step == ValidationStep.REFUSAL) {
912                         aValidationCycle.setSignatory(actor);
913                 }
914                 if (aValidationCycle.isSaved()) {
915                         getValidationCycleDAO().update(aValidationCycle);
916                 }
917         }
918
919         /**
920          * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
921          * 
922          * @param aStudy
923          *            the study
924          * @return the actors of this study
925          * @see #hasActor(User)
926          */
927         public Set<User> getActors(final Study aStudy) {
928                 if (aStudy.getActor() == null) {
929                         setShortCuts(aStudy);
930                 }
931                 return Collections.unmodifiableSet(aStudy.getActor());
932         }
933
934         /**
935          * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
936          * 
937          * @param aStudy
938          *            the study
939          * @return the modifiable set of actors of this study
940          * @see #hasActor(User)
941          */
942         public Set<User> getModifiableActors(final Study aStudy) {
943                 if (aStudy.getActor() == null) {
944                         setShortCuts(aStudy);
945                 }
946                 return aStudy.getActor();
947         }
948
949         /**
950          * Returns unmodifiable initialized transient list of contributors of this study.
951          * 
952          * @param aStudy
953          *            the study
954          * @return the unmodifiable not null transient list of contributors of this study
955          */
956         public List<User> getContributors(final Study aStudy) {
957                 if (aStudy.getContributor() == null) {
958                         setShortCuts(aStudy);
959                 }
960                 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
961         }
962
963         /**
964          * Returns modifiable initialized transient list of contributors of this study.
965          * 
966          * @param aStudy
967          *            the study
968          * @return the modifiable not null transient list of contributors of this study
969          */
970         public List<User> getModifiableContributors(final Study aStudy) {
971                 if (aStudy.getContributor() == null) {
972                         setShortCuts(aStudy);
973                 }
974                 return aStudy.getContributor(); // May be empty
975         }
976
977         /**
978          * Returns the validation cycle of the given document type.
979          * 
980          * @param aStudy
981          *            the study
982          * @param type
983          *            the document type being subject of validation
984          * @return the validation cycle of the document, or null if not defined.
985          */
986         public ValidationCycle getValidationCycleOf(final Study aStudy,
987                         final DocumentType type) {
988                 ValidationCycle result = null;
989                 if (aStudy != null) {
990                         if (aStudy.getValidationCycles() == null
991                                         || aStudy.getValidationCycles().isEmpty()) {
992                                 setShortCuts(aStudy);
993                         }
994                         if (type != null) {
995                                 result = aStudy.getValidationCycles().get(type.getName());
996                         }
997                 }
998                 if ((result == null) && (aStudy != null)) {
999                         if ((type == null) || type.isStepResult()) {
1000                                 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
1001                         }
1002                         if (result == null) {
1003                                 result = aStudy.getValidationCycles().get("built-in");
1004                         }
1005                 }
1006                 return result;
1007         }
1008
1009         /**
1010          * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
1011          * 
1012          * @param aStudy
1013          *            the study
1014          * @param user
1015          *            the user to look for
1016          * @return true if the given user is actor of this study.
1017          * @see #getActors()
1018          */
1019         public boolean hasActor(final Study aStudy, final User user) {
1020                 if (user == null) {
1021                         return false;
1022                 }
1023                 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
1024                         User involved = i.next();
1025                         if (involved.equals(user)) {
1026                                 return true;
1027                         }
1028                 }
1029                 return false;
1030         }
1031
1032         /**
1033          * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1034          * 
1035          * @param aStudy
1036          *            the study
1037          * @param user
1038          *            the user to look for
1039          * @return true if the given user is actor of this study.
1040          * @see #getContributors()
1041          */
1042         public boolean isStaffedBy(final Study aStudy, final User user) {
1043                 if (user == null) {
1044                         return false;
1045                 }
1046                 if (aStudy == null) {
1047                         return false;
1048                 }
1049                 if (aStudy.getAuthor() == null) {
1050                         return false;
1051                 }
1052                 if (aStudy.getAuthor().equals(user)) {
1053                         return true;
1054                 }
1055                 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1056                         if (i.next().equals(user)) {
1057                                 return true;
1058                         }
1059                 }
1060                 return false;
1061         }
1062
1063         /**
1064          * Initialize shortcuts of the study as its transient collections.
1065          * 
1066          * @param aStudy
1067          *            the study
1068          */
1069         public void loadWorkflow(final Study aStudy) {
1070                 setShortCuts(aStudy);
1071         }
1072
1073         /**
1074          * Initialize shortcuts of the study as its transient collections.
1075          * 
1076          * @param aStudy
1077          *            the study
1078          */
1079         public void setShortCuts(final Study aStudy) {
1080                 aStudy.getContributor().clear();
1081                 aStudy.getValidationCycles().clear();
1082                 aStudy.getActor().clear();
1083
1084                 // Get the contributors
1085                 for (Iterator<Relation> i = aStudy.getRelations(
1086                                 ContributorRelation.class).iterator(); i.hasNext();) {
1087                         ContributorRelation link = (ContributorRelation) i.next();
1088                         aStudy.getContributor().add(link.getTo());
1089                 }
1090                 // Get the validation cycles specific to this study
1091                 for (Iterator<Relation> i = aStudy.getRelations(
1092                                 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1093                         ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1094                         aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1095                                         link.getTo()); // The associated document type is necessarily not null in this
1096                         // context
1097                 }
1098                 // Get the validation cycles coming from the configured workflow and not overridden in this study
1099                 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1100                                 .getAllValidationCycles().iterator(); i.hasNext();) {
1101                         ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1102                                         .next();
1103                         String type = cycle.getName();
1104                         if (!aStudy.getValidationCycles().containsKey(type)) {
1105                                 aStudy.getValidationCycles().put(type,
1106                                                 createValidationCycle(aStudy, cycle));
1107                         }
1108                 }
1109                 // Get all corresponding actors
1110                 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1111                                 .values().iterator(); i.hasNext();) {
1112                         ValidationCycle cycle = i.next();
1113                         User[] user = cycle.getAllActors();
1114                         for (int j = 0; j < user.length; j++) {
1115                                 aStudy.getActor().add(user[j]);
1116                         }
1117                 }
1118                 // Get all other actors
1119                 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1120                                 .hasNext();) {
1121                         Relation link = i.next();
1122                         Class<?> kindof = link.getClass().getSuperclass();
1123                         if (!kindof.equals(ActorRelation.class)) {
1124                                 continue;
1125                         }
1126                         aStudy.getActor().add(((ActorRelation) link).getTo());
1127                 }
1128         }
1129
1130         /**
1131          * 
1132          * {@inheritDoc}
1133          * 
1134          * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
1135          */
1136         @Transactional
1137         public boolean markStudyAsReference(final Study aStudy) {
1138                 boolean res = false;
1139                 if (aStudy.getProgressState() == ProgressState.APPROVED) {
1140                         aStudy.setMarkreference(1);
1141                         aStudy.setProgressState(ProgressState.TEMPLATE);
1142                         res = updateKnowledgeElementsState(aStudy);
1143                         getStudyDAO().merge(aStudy);
1144                 }
1145                 return res;
1146         }
1147
1148         /**
1149          * 
1150          * {@inheritDoc}
1151          * 
1152          * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
1153          */
1154         @Transactional
1155         public void removeStudyAsReference(final Study aStudy) {
1156                 aStudy.setMarkreference(0);
1157                 aStudy.setProgressState(ProgressState.APPROVED);
1158                 updateKnowledgeElementsState(aStudy);
1159                 getStudyDAO().merge(aStudy);
1160         }
1161
1162         /**
1163          * {@inheritDoc}
1164          * 
1165          * @see org.splat.service.StudyService#getDescription(java.lang.Long)
1166          */
1167         @Override
1168         @Transactional(readOnly = true)
1169         public String getDescription(final Long studyId)
1170                         throws InvalidParameterException {
1171                 if (studyId == null) {
1172                         throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1173                 }
1174                 Study study = _studyDAO.get(studyId);
1175                 if (study == null) {
1176                         throw new InvalidParameterException(PARAM_STUDY_ID, studyId
1177                                         .toString());
1178                 }
1179                 return study.getDescription();
1180         }
1181
1182         /**
1183          * {@inheritDoc}
1184          * 
1185          * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
1186          */
1187         @Transactional
1188         public void setDescription(final Long studyId, final String descriptionText)
1189                         throws InvalidParameterException {
1190                 if (studyId == null) {
1191                         throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1192                 }
1193                 Study study = _studyDAO.get(studyId);
1194                 if (study == null) {
1195                         throw new InvalidParameterException(PARAM_STUDY_ID, studyId
1196                                         .toString());
1197                 }
1198                 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1199         }
1200
1201         /**
1202          * {@inheritDoc}
1203          * 
1204          * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
1205          */
1206         @Transactional
1207         public boolean removeDescription(final Long studyId)
1208                         throws InvalidParameterException {
1209                 if (studyId == null) {
1210                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1211                                         .valueOf(studyId));
1212                 }
1213                 Study study = _studyDAO.get(studyId);
1214                 if (study == null) {
1215                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1216                                         .valueOf(studyId));
1217                 }
1218                 return study.removeAttribute(study
1219                                 .getAttribute(DescriptionAttribute.class));
1220         }
1221
1222         /**
1223          * 
1224          * {@inheritDoc}
1225          * 
1226          * @see org.splat.service.StudyService#compare(java.util.List)
1227          */
1228         @Override
1229         public String compare(final List<DocToCompareDTO> docsList,
1230                         final String userName) throws IncompatibleDataException {
1231
1232                 String axis1Name = "";
1233                 String axis2Name = "";
1234                 String chartTitle = "";
1235                 String resultPath = "";
1236
1237                 XYSeriesCollection dataset = new XYSeriesCollection();
1238
1239                 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1240
1241                 for (; docListIter.hasNext();) {
1242
1243                         DocToCompareDTO docDTO = docListIter.next();
1244                         String pathToFile = docDTO.getPathToFile();
1245                         File compDocFile = new File(pathToFile);
1246
1247                         resultPath = pathToFile.substring(0, pathToFile.indexOf("vault"))
1248                                         + "downloads" + File.separator + userName + File.separator
1249                                         + "ComparisonResult.pdf";
1250
1251                         XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle()
1252                                         + " Scenario: " + docDTO.getScenarioTitle() + " Document: "
1253                                         + docDTO.getDocumentTitle());
1254
1255                         // read the file and get points information.
1256                         try {
1257                                 Scanner input = new Scanner(compDocFile);
1258
1259                                 // get the title of the chart.
1260                                 if (input.hasNext()) {
1261                                         chartTitle = input.nextLine();
1262                                 }
1263
1264                                 // get the name of the axis.
1265                                 if (input.hasNext()) {
1266                                         String[] tokens = input.nextLine().split(",");
1267
1268                                         if (tokens.length < 2) {
1269                                                 throw new IncompatibleDataException(
1270                                                                 MessageKeyEnum.IDT_000001.toString());
1271                                         }
1272
1273                                         if ("".equals(axis1Name)) {
1274                                                 axis1Name = tokens[0];
1275                                         } else if (!axis1Name.equals(tokens[0])) {
1276                                                 LOG.debug("Axis must be the same for all documents");
1277                                                 throw new IncompatibleDataException(
1278                                                                 MessageKeyEnum.IDT_000001.toString());
1279                                         }
1280
1281                                         if ("".equals(axis2Name)) {
1282                                                 axis2Name = tokens[1];
1283                                         } else if (!axis2Name.equals(tokens[1])) {
1284                                                 LOG.debug("Axis must be the same for all documents");
1285                                                 throw new IncompatibleDataException(
1286                                                                 MessageKeyEnum.IDT_000001.toString());
1287                                         }
1288                                 }
1289
1290                                 // Get the XY points series.
1291                                 while (input.hasNext()) {
1292
1293                                         String currentString = input.nextLine();
1294
1295                                         if (!("".equals(currentString))) {
1296                                                 String[] tokens = currentString.split(" ");
1297                                                 series.add(Double.valueOf(tokens[0]), Double
1298                                                                 .valueOf(tokens[1]));
1299                                         }
1300
1301                                 } // while
1302
1303                                 dataset.addSeries(series);
1304
1305                         } catch (FileNotFoundException e) {
1306                                 LOG.error("Sorry, the file is not found.", e);
1307                         }
1308                 } // for
1309
1310                 JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // Title
1311                                 axis1Name, // x-axis Label
1312                                 axis2Name, // y-axis Label
1313                                 dataset, // Dataset
1314                                 PlotOrientation.VERTICAL, // Plot Orientation
1315                                 true, // Show Legend
1316                                 true, // Use tooltips
1317                                 false // Configure chart to generate URLs?
1318                                 );
1319
1320                 // export to PDF - file.
1321                 int x = 500;
1322                 int y = 300;
1323                 Rectangle pagesize = new Rectangle(x, y);
1324                 Document document = new Document(pagesize, 50, 50, 50, 50);
1325                 PdfWriter writer;
1326                 try {
1327                         File resFile = new File(resultPath);
1328                         File resFolder = new File(resultPath.substring(0, resultPath
1329                                         .lastIndexOf(File.separator)));
1330                         resFolder.mkdirs();
1331                         writer = PdfWriter.getInstance(document, new FileOutputStream(
1332                                         resFile));
1333
1334                         document.open();
1335                         PdfContentByte cb = writer.getDirectContent();
1336                         PdfTemplate tp = cb.createTemplate(x, y);
1337                         Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1338                         chart.draw(g2, new java.awt.Rectangle(x, y));
1339                         g2.dispose();
1340                         cb.addTemplate(tp, 0, 0);
1341                         document.close();
1342
1343                 } catch (FileNotFoundException e) {
1344                         LOG.error("Sorry, the file is not found.", e);
1345                 } catch (DocumentException e) {
1346                         LOG.error("Sorry, the DocumentException is thrown.", e);
1347                 }
1348
1349                 return resultPath;
1350         }
1351
1352         /**
1353          * {@inheritDoc}
1354          * 
1355          * @see org.splat.service.StudyService#getReaders(long)
1356          */
1357         @Transactional(readOnly = true)
1358         public List<UserDTO> getReaders(final long studyId)
1359                         throws InvalidParameterException {
1360                 Study aStudy = selectStudy(studyId);
1361                 if (aStudy == null) {
1362                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1363                                         .valueOf(studyId));
1364                 }
1365                 List<Relation> relations = aStudy.getRelations(ReaderRelation.class);
1366                 List<UserDTO> result = new ArrayList<UserDTO>();
1367                 for (Relation relation : relations) {
1368                         result.add(BeanHelper.copyBean(relation.getTo(), UserDTO.class));
1369                 }
1370                 return Collections.unmodifiableList(result);
1371         }
1372
1373         /**
1374          * {@inheritDoc}
1375          * 
1376          * @see org.splat.service.StudyService#addReader(long, long)
1377          */
1378         @Transactional
1379         public boolean addReader(final long studyId, final long userId)
1380                         throws InvalidParameterException {
1381                 Study aStudy = selectStudy(studyId);
1382                 if (aStudy == null) {
1383                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1384                                         .valueOf(studyId));
1385                 }
1386                 User user = _userService.selectUser(userId);
1387                 if (user == null) {
1388                         throw new InvalidParameterException("userId", String
1389                                         .valueOf(userId));
1390                 }
1391
1392                 for (Relation relation : aStudy.getRelations(ReaderRelation.class)) {
1393                         if (user.equals(relation.getTo())) {
1394                                 return false;
1395                         }
1396                 }
1397                 aStudy.addRelation(new ReaderRelation(aStudy, user));
1398                 update(aStudy);
1399                 return true;
1400         }
1401
1402         /**
1403          * {@inheritDoc}
1404          * 
1405          * @see org.splat.service.StudyService#removeReader(long, long)
1406          */
1407         @Transactional
1408         public boolean removeReader(final long studyId, final long userId)
1409                         throws InvalidParameterException {
1410                 Study aStudy = selectStudy(studyId);
1411                 if (aStudy == null) {
1412                         throw new InvalidParameterException(PARAM_STUDY_ID, String
1413                                         .valueOf(studyId));
1414                 }
1415                 User user = _userService.selectUser(userId);
1416                 if (user == null) {
1417                         throw new InvalidParameterException("userId", String
1418                                         .valueOf(userId));
1419                 }
1420
1421                 Relation relation = aStudy.removeRelation(ReaderRelation.class, user);
1422                 update(aStudy);
1423                 return relation != null;
1424         }
1425
1426         /**
1427          * Get project settings.
1428          * 
1429          * @return Project settings service
1430          */
1431         private ProjectSettingsService getProjectSettings() {
1432                 return _projectSettings;
1433         }
1434
1435         /**
1436          * Set project settings service.
1437          * 
1438          * @param projectSettingsService
1439          *            project settings service
1440          */
1441         public void setProjectSettings(
1442                         final ProjectSettingsService projectSettingsService) {
1443                 _projectSettings = projectSettingsService;
1444         }
1445
1446         /**
1447          * Get the projectElementService.
1448          * 
1449          * @return the projectElementService
1450          */
1451         public ProjectElementService getProjectElementService() {
1452                 return _projectElementService;
1453         }
1454
1455         /**
1456          * Set the projectElementService.
1457          * 
1458          * @param projectElementService
1459          *            the projectElementService to set
1460          */
1461         public void setProjectElementService(
1462                         final ProjectElementService projectElementService) {
1463                 _projectElementService = projectElementService;
1464         }
1465
1466         /**
1467          * Get the stepService.
1468          * 
1469          * @return the stepService
1470          */
1471         public StepService getStepService() {
1472                 return _stepService;
1473         }
1474
1475         /**
1476          * Set the stepService.
1477          * 
1478          * @param stepService
1479          *            the stepService to set
1480          */
1481         public void setStepService(final StepService stepService) {
1482                 _stepService = stepService;
1483         }
1484
1485         /**
1486          * Get the indexService.
1487          * 
1488          * @return the indexService
1489          */
1490         public IndexService getIndexService() {
1491                 return _indexService;
1492         }
1493
1494         /**
1495          * Set the indexService.
1496          * 
1497          * @param indexService
1498          *            the indexService to set
1499          */
1500         public void setIndexService(final IndexService indexService) {
1501                 _indexService = indexService;
1502         }
1503
1504         /**
1505          * Get the studyDAO.
1506          * 
1507          * @return the studyDAO
1508          */
1509         public StudyDAO getStudyDAO() {
1510                 return _studyDAO;
1511         }
1512
1513         /**
1514          * Set the studyDAO.
1515          * 
1516          * @param studyDAO
1517          *            the studyDAO to set
1518          */
1519         public void setStudyDAO(final StudyDAO studyDAO) {
1520                 _studyDAO = studyDAO;
1521         }
1522
1523         /**
1524          * Get the iDBuilderDAO.
1525          * 
1526          * @return the iDBuilderDAO
1527          */
1528         public IDBuilderDAO getIDBuilderDAO() {
1529                 return _iDBuilderDAO;
1530         }
1531
1532         /**
1533          * Set the iDBuilderDAO.
1534          * 
1535          * @param builderDAO
1536          *            the iDBuilderDAO to set
1537          */
1538         public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1539                 _iDBuilderDAO = builderDAO;
1540         }
1541
1542         /**
1543          * Get the scenarioDAO.
1544          * 
1545          * @return the scenarioDAO
1546          */
1547         public ScenarioDAO getScenarioDAO() {
1548                 return _scenarioDAO;
1549         }
1550
1551         /**
1552          * Set the scenarioDAO.
1553          * 
1554          * @param scenarioDAO
1555          *            the scenarioDAO to set
1556          */
1557         public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1558                 _scenarioDAO = scenarioDAO;
1559         }
1560
1561         /**
1562          * Get the validationCycleDAO.
1563          * 
1564          * @return the validationCycleDAO
1565          */
1566         public ValidationCycleDAO getValidationCycleDAO() {
1567                 return _validationCycleDAO;
1568         }
1569
1570         /**
1571          * Set the validationCycleDAO.
1572          * 
1573          * @param validationCycleDAO
1574          *            the validationCycleDAO to set
1575          */
1576         public void setValidationCycleDAO(
1577                         final ValidationCycleDAO validationCycleDAO) {
1578                 _validationCycleDAO = validationCycleDAO;
1579         }
1580
1581         /**
1582          * Get the documentTypeService.
1583          * 
1584          * @return the documentTypeService
1585          */
1586         public DocumentTypeService getDocumentTypeService() {
1587                 return _documentTypeService;
1588         }
1589
1590         /**
1591          * Set the documentTypeService.
1592          * 
1593          * @param documentTypeService
1594          *            the documentTypeService to set
1595          */
1596         public void setDocumentTypeService(
1597                         final DocumentTypeService documentTypeService) {
1598                 _documentTypeService = documentTypeService;
1599         }
1600
1601         /**
1602          * Get the userService.
1603          * 
1604          * @return the userService
1605          */
1606         public UserService getUserService() {
1607                 return _userService;
1608         }
1609
1610         /**
1611          * Set the userService.
1612          * 
1613          * @param userService
1614          *            the userService to set
1615          */
1616         public void setUserService(final UserService userService) {
1617                 _userService = userService;
1618         }
1619
1620         /**
1621          * {@inheritDoc}
1622          * 
1623          * @see org.splat.service.StudyService#getComparableStudies()
1624          */
1625         @Transactional(readOnly = true)
1626         public List<StudyFacadeDTO> getComparableStudies(final long userId)
1627                         throws MismatchException {
1628                 // retrieve the number of the "Analyze the results" step
1629                 List<Step> allSteps = _projectSettings.getAllSteps();
1630                 Step theAnalyzeStep = null;
1631                 for (Step step : allSteps) {
1632                         if (step.getKey().equals("postprocessing")) {
1633                                 theAnalyzeStep = step;
1634                         }
1635                 }
1636                 if (theAnalyzeStep == null) { // TODO: throw some other exception
1637                         throw new MismatchException(
1638                                         "no step with key 'postprocessing' found."
1639                                                         + "Probably, customization settings have been changed.");
1640                 }
1641
1642                 List<Publication> publications = _publicationDAO.getFilteredList(
1643                                 "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep
1644                                                 .getNumber())));
1645
1646                 // split retrieved publications into groups by studies and scenarios
1647                 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1648                 Map<ProjectElement, List<Publication>> scenarioMap = new HashMap<ProjectElement, List<Publication>>();
1649
1650                 for (Publication publication : publications) {
1651                         // filter out publications corresponding to a document of given step which is not a _result_ document
1652                         if (!publication.value().getType().isResultOf(theAnalyzeStep)
1653                                         || !"srd".equals(publication.getSourceFile().getFormat())) {
1654                                 continue;
1655                         }
1656
1657                         // check the study visibility to the user
1658                         if (!isStaffedBy(publication.getOwnerStudy(), _userService
1659                                         .selectUser(userId))
1660                                         && Visibility.PUBLIC.equals(publication.getOwnerStudy()
1661                                                         .getVisibility())) {
1662                                 continue;
1663                         }
1664
1665                         Study study = publication.getOwnerStudy();
1666                         ProjectElement scenario = publication.getOwner();
1667
1668                         Hibernate.initialize(scenario);
1669                         if (scenario instanceof HibernateProxy) {
1670                                 scenario = (ProjectElement) ((HibernateProxy) scenario)
1671                                                 .getHibernateLazyInitializer().getImplementation();
1672                         }
1673
1674                         if (!(scenario instanceof Scenario)) {
1675                                 throw new MismatchException(
1676                                                 "publications from postprocessing step are supposed to have owner scenario");
1677                         }
1678
1679                         if (!studyMap.containsKey(study)) {
1680                                 studyMap.put(study, new ArrayList<ProjectElement>());
1681                         }
1682
1683                         if (!studyMap.get(study).contains(scenario)) {
1684                                 studyMap.get(study).add(scenario);
1685                         }
1686
1687                         if (!scenarioMap.containsKey(scenario)) {
1688                                 scenarioMap.put(scenario, new ArrayList<Publication>());
1689                         }
1690                         scenarioMap.get(scenario).add(publication);
1691                 }
1692
1693                 // Create the result DTOs
1694                 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1695                 for (Study study : studyMap.keySet()) {
1696
1697                         StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1698                         studyDTO.setName(study.getTitle());
1699                         studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1700                         result.add(studyDTO);
1701
1702                         for (ProjectElement scenario : studyMap.get(study)) {
1703
1704                                 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1705                                 scenarioDTO.setName(scenario.getTitle());
1706                                 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1707                                 studyDTO.getScenarios().add(scenarioDTO);
1708
1709                                 for (Publication publication : scenarioMap.get(scenario)) {
1710
1711                                         DocumentDTO documentDTO = new DocumentDTO();
1712                                         documentDTO.setId(publication.getIndex());
1713                                         documentDTO.setTitle(publication.value().getTitle());
1714
1715                                         scenarioDTO.getDocs().add(documentDTO);
1716                                 }
1717                         }
1718                 }
1719                 return result;
1720         }
1721
1722         /**
1723          * Get the publicationDAO.
1724          * 
1725          * @return the publicationDAO
1726          */
1727         public PublicationDAO getPublicationDAO() {
1728                 return _publicationDAO;
1729         }
1730
1731         /**
1732          * Set the publicationDAO.
1733          * 
1734          * @param publicationDAO
1735          *            the publicationDAO to set
1736          */
1737         public void setPublicationDAO(final PublicationDAO publicationDAO) {
1738                 _publicationDAO = publicationDAO;
1739         }
1740
1741         /**
1742          * Get the repositoryService.
1743          * 
1744          * @return the repositoryService
1745          */
1746         public RepositoryService getRepositoryService() {
1747                 return _repositoryService;
1748         }
1749
1750         /**
1751          * Set the repositoryService.
1752          * 
1753          * @param repositoryService
1754          *            the repositoryService to set
1755          */
1756         public void setRepositoryService(final RepositoryService repositoryService) {
1757                 _repositoryService = repositoryService;
1758         }
1759
1760         /**
1761          * Get the documentDAO.
1762          * 
1763          * @return the documentDAO
1764          */
1765         public DocumentDAO getDocumentDAO() {
1766                 return _documentDAO;
1767         }
1768
1769         /**
1770          * Set the documentDAO.
1771          * 
1772          * @param documentDAO
1773          *            the documentDAO to set
1774          */
1775         public void setDocumentDAO(final DocumentDAO documentDAO) {
1776                 _documentDAO = documentDAO;
1777         }
1778
1779         /**
1780          * Get the descriptionAttributeDAO.
1781          * 
1782          * @return the descriptionAttributeDAO
1783          */
1784         public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1785                 return _descriptionAttributeDAO;
1786         }
1787
1788         /**
1789          * Set the descriptionAttributeDAO.
1790          * 
1791          * @param descriptionAttributeDAO
1792          *            the descriptionAttributeDAO to set
1793          */
1794         public void setDescriptionAttributeDAO(
1795                         final DescriptionAttributeDAO descriptionAttributeDAO) {
1796                 _descriptionAttributeDAO = descriptionAttributeDAO;
1797         }
1798
1799         /**
1800          * Get the usedByRelationDAO.
1801          * 
1802          * @return the usedByRelationDAO
1803          */
1804         public UsedByRelationDAO getUsedByRelationDAO() {
1805                 return _usedByRelationDAO;
1806         }
1807
1808         /**
1809          * Set the usedByRelationDAO.
1810          * 
1811          * @param usedByRelationDAO
1812          *            the usedByRelationDAO to set
1813          */
1814         public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
1815                 _usedByRelationDAO = usedByRelationDAO;
1816         }
1817
1818         /**
1819          * {@inheritDoc}
1820          * 
1821          * @see org.splat.service.StudyService#getStudyResultType(org.splat.dal.bo.som.Study)
1822          */
1823         @Override
1824         @Transactional(readOnly = true)
1825         public DocumentType getStudyResultType(final Study study) {
1826                 DetachedCriteria query = DetachedCriteria.forClass(DocumentType.class)
1827                                 .addOrder(Order.desc("result"));
1828                 return getDocumentTypeDAO().getFirstResult(query);
1829         }
1830
1831         /**
1832          * Get the documentTypeDAO.
1833          * 
1834          * @return the documentTypeDAO
1835          */
1836         public DocumentTypeDAO getDocumentTypeDAO() {
1837                 return _documentTypeDAO;
1838         }
1839
1840         /**
1841          * Set the documentTypeDAO.
1842          * 
1843          * @param documentTypeDAO
1844          *            the documentTypeDAO to set
1845          */
1846         public void setDocumentTypeDAO(final DocumentTypeDAO documentTypeDAO) {
1847                 _documentTypeDAO = documentTypeDAO;
1848         }
1849
1850         /**
1851          * {@inheritDoc}
1852          * 
1853          * @see org.splat.service.StudyService#canBeApproved(org.splat.dal.bo.som.Study)
1854          */
1855         @Override
1856         @Transactional(readOnly = true)
1857         public boolean canBeApproved(final Study study) {
1858                 return resultDocsAtLeast(study, ProgressState.APPROVED);
1859         }
1860
1861         /**
1862          * {@inheritDoc}
1863          * 
1864          * @see org.splat.service.StudyService#canBePromoted(org.splat.dal.bo.som.Study)
1865          */
1866         @Override
1867         @Transactional(readOnly = true)
1868         public boolean canBePromoted(final Study study) {
1869                 boolean res;
1870                 if (study.getProgressState().compareTo(ProgressState.inDRAFT) < 0) {
1871                         res = resultDocsAtLeast(study, ProgressState.inDRAFT);
1872                 } else {
1873                         res = canBeReviewed(study);
1874                 }
1875                 return res;
1876         }
1877
1878         /**
1879          * {@inheritDoc}
1880          * 
1881          * @see org.splat.service.StudyService#canBeReviewed(org.splat.dal.bo.som.Study)
1882          */
1883         @Override
1884         @Transactional(readOnly = true)
1885         public boolean canBeReviewed(final Study study) {
1886                 return resultDocsAtLeast(study, ProgressState.inCHECK);
1887         }
1888
1889         /**
1890          * Check that all result documents of the study are at least in the given state.
1891          * 
1892          * @param study
1893          *            the study to check
1894          * @param state
1895          *            the minimal acceptable state
1896          * @return true if study result documents have acceptable states
1897          */
1898         private boolean resultDocsAtLeast(final Study study,
1899                         final ProgressState state) {
1900                 boolean res = true;
1901                 // Check that all study result documents have the state APPROVED or more.
1902                 for (Publication pub : getProjectElementService().getLastStep(study)
1903                                 .getResultDocuments()) {
1904                         res = pub.getProgressState().compareTo(state) >= 0;
1905                         if (!res) {
1906                                 break;
1907                         }
1908                 }
1909                 return res;
1910         }
1911 }