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