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