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