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