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