]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java
Salome HOME
Title of the chart is set from input file.
[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 chartTitle = "";
1191                 String resultPath = "";
1192                 
1193                 XYSeriesCollection dataset = new XYSeriesCollection();
1194                 
1195                 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1196                 
1197                 for (; docListIter.hasNext();) {
1198                         
1199                         DocToCompareDTO docDTO = docListIter.next();
1200                         String pathToFile = docDTO.getPathToFile();
1201                         File compDocFile = new File(pathToFile);
1202                         
1203                         resultPath = pathToFile.substring(0, pathToFile.indexOf("vault")) + "downloads" + File.separator + userName + File.separator + "ComparisonResult.pdf";
1204                         
1205                         XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle());
1206                         
1207                         //read the file and get points information.
1208                         try {
1209                                 Scanner input = new Scanner(compDocFile);
1210                                 
1211                                 //get the title of the chart.
1212                                 if (input.hasNext()) {
1213                                         chartTitle = input.nextLine();
1214                                 }
1215                                 
1216                                 //get the name of the axis.
1217                                 if (input.hasNext()) {
1218                                         String[] tokens = input.nextLine().split(",");
1219                                                                                 
1220                                         if (tokens.length < 2)
1221                                                 throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
1222                                         
1223                                         if ("".equals(axis1Name)) {
1224                                                 axis1Name = tokens[0];
1225                                         } else if (!axis1Name.equals(tokens[0])) {
1226                                                 LOG.debug("Axis must be the same for all documents");
1227                                                 throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
1228                                         }
1229                                         
1230                                         if ("".equals(axis2Name)) {
1231                                                 axis2Name = tokens[1];
1232                                         } else if (!axis2Name.equals(tokens[1])) {
1233                                                 LOG.debug("Axis must be the same for all documents");
1234                                                 throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
1235                                         }
1236                                 }
1237                                 
1238                                 //Get the XY points series.
1239                                 while(input.hasNext()) {
1240                                         
1241                                         String currentString = input.nextLine();
1242                                         
1243                                         if ("".equals(currentString)) {
1244                                                 continue;
1245                                         }
1246                                         else {
1247                                                 String[] tokens = currentString.split(" ");
1248                                                 series.add(Double.valueOf(tokens[0]), Double.valueOf(tokens[1]));
1249                                         }                   
1250                                   
1251                                 } //while
1252                                 
1253                                 dataset.addSeries(series);
1254                                 
1255                         } catch (FileNotFoundException e) {
1256                                 // TODO Auto-generated catch block
1257                                 e.printStackTrace();
1258                                 return "ERROR";
1259                         }
1260                 } //for
1261                 
1262                 JFreeChart chart = ChartFactory.createXYLineChart(
1263                                 chartTitle, // Title
1264                                 axis1Name, // x-axis Label
1265                                 axis2Name, // y-axis Label
1266                                 dataset, // Dataset
1267                                 PlotOrientation.VERTICAL, // Plot Orientation
1268                                 true, // Show Legend
1269                                 true, // Use tooltips
1270                                 false // Configure chart to generate URLs?
1271                                 );
1272                 
1273                 //export to PDF - file.                 
1274                 int x = 500;
1275                 int y = 300;
1276                 Rectangle pagesize = new Rectangle(x, y);
1277                 Document document = new Document(pagesize, 50, 50, 50, 50);
1278         PdfWriter writer;
1279                 try {
1280                         File resFile = new File(resultPath);
1281                         File resFolder = new File(resultPath.substring(0, resultPath.lastIndexOf(File.separator)));
1282                         resFolder.mkdirs();
1283                         writer = PdfWriter.getInstance(document, new FileOutputStream(resFile));
1284                 
1285                 document.open();
1286                 PdfContentByte cb = writer.getDirectContent();
1287                 PdfTemplate tp = cb.createTemplate(x, y);
1288                 Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1289                 chart.draw(g2, new java.awt.Rectangle(x,y));
1290                 g2.dispose();
1291                 cb.addTemplate(tp, 0, 0);
1292                 document.close(); 
1293         
1294                 } catch (FileNotFoundException e) {
1295                         // TODO Auto-generated catch block
1296                         e.printStackTrace();
1297                 } catch (DocumentException e) {
1298                         // TODO Auto-generated catch block
1299                         e.printStackTrace();
1300                 }
1301                 
1302                 return resultPath;
1303         }
1304         
1305         /**
1306          * Get project settings.
1307          * 
1308          * @return Project settings service
1309          */
1310         private ProjectSettingsService getProjectSettings() {
1311                 return _projectSettings;
1312         }
1313
1314         /**
1315          * Set project settings service.
1316          * 
1317          * @param projectSettingsService
1318          *            project settings service
1319          */
1320         public void setProjectSettings(
1321                         final ProjectSettingsService projectSettingsService) {
1322                 _projectSettings = projectSettingsService;
1323         }
1324
1325         /**
1326          * Get the projectElementService.
1327          * 
1328          * @return the projectElementService
1329          */
1330         public ProjectElementService getProjectElementService() {
1331                 return _projectElementService;
1332         }
1333
1334         /**
1335          * Set the projectElementService.
1336          * 
1337          * @param projectElementService
1338          *            the projectElementService to set
1339          */
1340         public void setProjectElementService(
1341                         final ProjectElementService projectElementService) {
1342                 _projectElementService = projectElementService;
1343         }
1344
1345         /**
1346          * Get the stepService.
1347          * 
1348          * @return the stepService
1349          */
1350         public StepService getStepService() {
1351                 return _stepService;
1352         }
1353
1354         /**
1355          * Set the stepService.
1356          * 
1357          * @param stepService
1358          *            the stepService to set
1359          */
1360         public void setStepService(final StepService stepService) {
1361                 _stepService = stepService;
1362         }
1363
1364         /**
1365          * Get the indexService.
1366          * 
1367          * @return the indexService
1368          */
1369         public IndexService getIndexService() {
1370                 return _indexService;
1371         }
1372
1373         /**
1374          * Set the indexService.
1375          * 
1376          * @param indexService
1377          *            the indexService to set
1378          */
1379         public void setIndexService(final IndexService indexService) {
1380                 _indexService = indexService;
1381         }
1382
1383         /**
1384          * Get the studyDAO.
1385          * 
1386          * @return the studyDAO
1387          */
1388         public StudyDAO getStudyDAO() {
1389                 return _studyDAO;
1390         }
1391
1392         /**
1393          * Set the studyDAO.
1394          * 
1395          * @param studyDAO
1396          *            the studyDAO to set
1397          */
1398         public void setStudyDAO(final StudyDAO studyDAO) {
1399                 _studyDAO = studyDAO;
1400         }
1401
1402         /**
1403          * Get the iDBuilderDAO.
1404          * 
1405          * @return the iDBuilderDAO
1406          */
1407         public IDBuilderDAO getIDBuilderDAO() {
1408                 return _iDBuilderDAO;
1409         }
1410
1411         /**
1412          * Set the iDBuilderDAO.
1413          * 
1414          * @param builderDAO
1415          *            the iDBuilderDAO to set
1416          */
1417         public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1418                 _iDBuilderDAO = builderDAO;
1419         }
1420
1421         /**
1422          * Get the scenarioDAO.
1423          * 
1424          * @return the scenarioDAO
1425          */
1426         public ScenarioDAO getScenarioDAO() {
1427                 return _scenarioDAO;
1428         }
1429
1430         /**
1431          * Set the scenarioDAO.
1432          * 
1433          * @param scenarioDAO
1434          *            the scenarioDAO to set
1435          */
1436         public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1437                 _scenarioDAO = scenarioDAO;
1438         }
1439
1440         /**
1441          * Get the validationCycleDAO.
1442          * 
1443          * @return the validationCycleDAO
1444          */
1445         public ValidationCycleDAO getValidationCycleDAO() {
1446                 return _validationCycleDAO;
1447         }
1448
1449         /**
1450          * Set the validationCycleDAO.
1451          * 
1452          * @param validationCycleDAO
1453          *            the validationCycleDAO to set
1454          */
1455         public void setValidationCycleDAO(
1456                         final ValidationCycleDAO validationCycleDAO) {
1457                 _validationCycleDAO = validationCycleDAO;
1458         }
1459
1460         /**
1461          * Get the documentTypeService.
1462          * 
1463          * @return the documentTypeService
1464          */
1465         public DocumentTypeService getDocumentTypeService() {
1466                 return _documentTypeService;
1467         }
1468
1469         /**
1470          * Set the documentTypeService.
1471          * 
1472          * @param documentTypeService
1473          *            the documentTypeService to set
1474          */
1475         public void setDocumentTypeService(
1476                         final DocumentTypeService documentTypeService) {
1477                 _documentTypeService = documentTypeService;
1478         }
1479
1480         /**
1481          * Get the userService.
1482          * 
1483          * @return the userService
1484          */
1485         public UserService getUserService() {
1486                 return _userService;
1487         }
1488
1489         /**
1490          * Set the userService.
1491          * 
1492          * @param userService
1493          *            the userService to set
1494          */
1495         public void setUserService(final UserService userService) {
1496                 _userService = userService;
1497         }
1498         
1499         /**
1500          * {@inheritDoc}
1501          * 
1502          * @see org.splat.service.StudyService#getComparableStudies()
1503          */
1504         @Transactional(readOnly = true)
1505         public List<StudyFacadeDTO> getComparableStudies(final long userId) throws MismatchException {
1506                 //retrieve the number of the "Analyze the results" step 
1507                 List<Step> allSteps = _projectSettings.getAllSteps();
1508                 Step theAnalyzeStep = null;
1509                 for(Step step : allSteps) {
1510                         if(step.getKey().equals("postprocessing")) {
1511                                 theAnalyzeStep = step;
1512                         }
1513                 }
1514                 if(theAnalyzeStep == null) {    //TODO: throw some other exception
1515                         throw new MismatchException("no step with key 'postprocessing' found." +
1516                                         "Probably, customization settings have been changed.");
1517                 }
1518
1519                 List<Publication> publications = _publicationDAO.getFilteredList("mydoc",
1520                                 Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber())));
1521
1522                 //split retrieved publications into groups by studies and scenarios
1523                 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1524                 Map<ProjectElement, List<Publication>> scenarioMap = 
1525                                 new HashMap<ProjectElement, List<Publication>>();
1526                 
1527                 for(Publication publication : publications) {                   
1528                         //filter out publications corresponding to a document of given step which is not a _result_ document
1529                         if(!publication.value().getType().isResultOf(theAnalyzeStep)
1530                                         || !"srd".equals(publication.getSourceFile().getFormat())) {
1531                                 continue;
1532                         }
1533                         
1534                         //check the study visibility to the user
1535                         if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId))
1536                                         && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) {
1537                                 continue;
1538                         }
1539         
1540                         Study study = publication.getOwnerStudy();
1541                         ProjectElement scenario = publication.getOwner();
1542                         
1543                         Hibernate.initialize(scenario);
1544                     if (scenario instanceof HibernateProxy) {
1545                         scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer()
1546                                 .getImplementation();
1547                     }
1548                         
1549                         if(!(scenario instanceof Scenario)) {
1550                                 throw new MismatchException(
1551                                                 "publications from postprocessing step are supposed to have owner scenario");
1552                         }
1553
1554                         if(!studyMap.containsKey(study)) {
1555                                 studyMap.put(study, new ArrayList<ProjectElement>());
1556                         }
1557                         
1558                         if(!studyMap.get(study).contains(scenario)) {
1559                                 studyMap.get(study).add(scenario);
1560                         }
1561
1562                         if(!scenarioMap.containsKey(scenario)) {
1563                                 scenarioMap.put(scenario, new ArrayList<Publication>());
1564                         }
1565                         scenarioMap.get(scenario).add(publication);
1566                 }
1567                 
1568                 //Create the result DTOs
1569                 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1570                 for(Study study : studyMap.keySet()) {
1571                         
1572                         StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1573                         studyDTO.setName(study.getTitle());
1574                         studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1575                         result.add(studyDTO);
1576                         
1577                         for(ProjectElement scenario : studyMap.get(study)) {
1578                                 
1579                                 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1580                                 scenarioDTO.setName(scenario.getTitle());
1581                                 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1582                                 studyDTO.getScenarios().add(scenarioDTO);
1583
1584                                 for(Publication publication : scenarioMap.get(scenario)) {
1585
1586                                         DocumentDTO documentDTO = new DocumentDTO();
1587                                         documentDTO.setId(publication.getIndex());
1588                                         documentDTO.setTitle(publication.value().getTitle());
1589                                         
1590                                         scenarioDTO.getDocs().add(documentDTO);
1591                                 }
1592                         }
1593                 }               
1594                 return result;
1595         }
1596         
1597         /**
1598          * Get the publicationDAO.
1599          * @return the publicationDAO
1600          */
1601         public PublicationDAO getPublicationDAO() {
1602                 return _publicationDAO;
1603         }
1604
1605         /**
1606          * Set the publicationDAO.
1607          * @param publicationDAO the publicationDAO to set
1608          */
1609         public void setPublicationDAO(final PublicationDAO publicationDAO) {
1610                 _publicationDAO = publicationDAO;
1611         }
1612
1613         /**
1614          * Get the repositoryService.
1615          * @return the repositoryService
1616          */
1617         public RepositoryService getRepositoryService() {
1618                 return _repositoryService;
1619         }
1620
1621         /**
1622          * Set the repositoryService.
1623          * @param repositoryService the repositoryService to set
1624          */
1625         public void setRepositoryService(final RepositoryService repositoryService) {
1626                 _repositoryService = repositoryService;
1627         }
1628
1629         /**
1630          * Get the documentDAO.
1631          * @return the documentDAO
1632          */
1633         public DocumentDAO getDocumentDAO() {
1634                 return _documentDAO;
1635         }
1636
1637         /**
1638          * Set the documentDAO.
1639          * @param documentDAO the documentDAO to set
1640          */
1641         public void setDocumentDAO(final DocumentDAO documentDAO) {
1642                 _documentDAO = documentDAO;
1643         }
1644
1645         /**
1646          * Get the descriptionAttributeDAO.
1647          * @return the descriptionAttributeDAO
1648          */
1649         public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1650                 return _descriptionAttributeDAO;
1651         }
1652
1653         /**
1654          * Set the descriptionAttributeDAO.
1655          * @param descriptionAttributeDAO the descriptionAttributeDAO to set
1656          */
1657         public void setDescriptionAttributeDAO(
1658                         final DescriptionAttributeDAO descriptionAttributeDAO) {
1659                 _descriptionAttributeDAO = descriptionAttributeDAO;
1660         }
1661 }