1 /*****************************************************************************
5 * Creation date 02.10.2012
6 * @author Author: Maria KRUCHININA
8 *****************************************************************************/
10 package org.splat.service;
12 import java.awt.Graphics2D;
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;
28 import java.util.Scanner;
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;
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;
99 * This class defines all methods for creation, modification the study.
101 * @author Maria KRUCHININA
104 public class StudyServiceImpl implements StudyService {
107 * logger for the service.
109 public final static AppLogger LOG = AppLogger
110 .getLogger(StudyServiceImpl.class);
112 * "studyId" parameter name.
114 public final static String PARAM_STUDY_ID = "studyId";
117 * Injected index service.
119 private IndexService _indexService;
122 * Injected step service.
124 private StepService _stepService;
127 * Injected project service.
129 private ProjectSettingsService _projectSettings;
132 * Injected project element service.
134 private ProjectElementService _projectElementService;
137 * Injected study DAO.
139 private StudyDAO _studyDAO;
142 * Injected usedBy relations DAO.
144 private UsedByRelationDAO _usedByRelationDAO;
147 * Injected scenario DAO.
149 private ScenarioDAO _scenarioDAO;
152 * Injected validation cycle DAO.
154 private ValidationCycleDAO _validationCycleDAO;
157 * Injected IDBuilder DAO.
159 private IDBuilderDAO _iDBuilderDAO;
162 * Injected document type service.
164 private DocumentTypeService _documentTypeService;
167 * Injected user service.
169 private UserService _userService;
172 * Injected publication DAO.
174 private PublicationDAO _publicationDAO;
177 * Injected repository service.
179 private RepositoryService _repositoryService;
182 * Injected document DAO.
184 private DocumentDAO _documentDAO;
187 * Injected description attribute DAO.
189 private DescriptionAttributeDAO _descriptionAttributeDAO;
194 * @see org.splat.service.StudyService#selectStudy(long)
197 public Study selectStudy(final long index) {
198 Study result = getStudyDAO().get(index);
199 loadWorkflow(result);
206 * @see org.splat.service.StudyService#removeStudy(long)
209 public void removeStudy(final Long index) {
210 Study study = getStudyDAO().get(index);
211 Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
213 // Select all documents published in the study and study's scenarios.
214 DetachedCriteria query = DetachedCriteria.forClass(
215 Publication.class, "pub");
217 .createCriteria("pub.owner", "projelem",
219 .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
222 .or(Restrictions.eq("projelem.rid", index),
223 Restrictions.eq("study.rid", index)))
224 .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
226 if (LOG.isDebugEnabled()) {
227 LOG.debug("Find study documents: " + query.toString());
229 for (Publication pub : getPublicationDAO().getFilteredList(query)) {
230 docums.add(pub.value());
231 // Find also all previous versions of the document
232 for (org.splat.dal.bo.som.Document prev = pub.value()
233 .getPreviousVersion(); prev != null; prev = prev
234 .getPreviousVersion()) {
239 // Delete the study with its relations, scenarios and publications
240 getStudyDAO().delete(study);
242 // Remove all relations of study documents
243 for (org.splat.dal.bo.som.Document doc : docums) {
244 LOG.debug("Found doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
245 doc.getAllRelations().clear();
247 getDocumentDAO().flush();
249 // Remove all documents of the study
250 for (org.splat.dal.bo.som.Document doc : docums) {
251 LOG.debug("Remove doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
252 getDocumentDAO().delete(doc);
258 * Get study by its reference.
261 * the study reference
262 * @return found study or null
264 @Transactional(readOnly = true)
265 public Study selectStudy(final String refid) {
266 Study result = getStudyDAO().findByCriteria(
267 Restrictions.eq("sid", refid));
268 loadWorkflow(result);
275 * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
278 public Study createStudy(final Study.Properties sprop)
279 throws MissedPropertyException, InvalidPropertyException,
280 MultiplyDefinedException {
281 sprop.setReference(getProjectSettings().getReferencePattern());
282 Study study = new Study(sprop);
284 buildReference(study);
285 getStudyDAO().create(study);
287 // IndexService lucin = getIndex();
289 // } catch (IOException error) {
290 // LOG.error("Unable to index the study '" + study.getIndex()
291 // + "', reason:", error);
292 // // Continue and try to index later
300 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
303 public SimulationContext addProjectContext(final Study aStudy,
304 final SimulationContext.Properties cprop)
305 throws MissedPropertyException, InvalidPropertyException,
306 MultiplyDefinedException {
307 SimulationContext added = getStepService().addSimulationContext(
308 getProjectElementService().getFirstStep(aStudy), cprop);
316 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
319 public SimulationContext addProjectContext(final Study aStudy,
320 final SimulationContext context) {
321 SimulationContext added = getStepService().addSimulationContext(
322 getProjectElementService().getFirstStep(aStudy), context);
330 * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
333 public boolean addContributor(final Study aStudy, final User user) {
334 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
335 for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
336 User present = i.next();
337 if (present.equals(user)) {
341 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
343 aStudy.addRelation(new ContributorRelation(aStudy, user));
345 update(aStudy); // Else, useless to re-index the study
351 * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
352 * previously be approved.
356 * @return true if the move succeeded.
357 * @see #moveToPublic()
359 * @see Publication#approve(Date)
361 public boolean moveToReference(final Study aStudy) {
362 if (aStudy.getProgressState() != ProgressState.APPROVED) {
365 if (aStudy.getVisibility() != Visibility.PUBLIC) {
369 aStudy.setVisibility(Visibility.REFERENCE);
370 if (update(aStudy)) {
371 return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
379 * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
381 public boolean update(final Study aStudy, final Properties sprop)
382 throws InvalidPropertyException {
383 if (sprop.getTitle() != null) {
384 aStudy.setTitle(sprop.getTitle());
386 if (sprop.getSummary() != null) {
387 aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
390 // TODO: To be completed
391 return update(aStudy);
395 * Check if the document is published in the study.
401 * @return true if the document is published in the study
403 /* private boolean publishes(final Study aStudy, final Document doc) {
404 if (!aStudy.publishes(doc)) {
405 Scenario[] scene = aStudy.getScenarii();
406 for (int i = 0; i < scene.length; i++) {
407 if (scene[i].publishes(doc)) {
418 * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
421 public boolean removeContributor(final Study aStudy, final User... users) {
422 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
423 Boolean done = false;
424 for (int i = 0; i < users.length; i++) {
425 User user = users[i];
426 for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
427 User present = j.next();
428 if (!present.equals(user)) {
432 aStudy.removeRelation(ContributorRelation.class, user);
433 j.remove(); // Updates the contributor shortcut
447 * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
449 public boolean removeProjectContext(final Study aStudy,
450 final SimulationContext context) {
451 boolean done = getStepService().removeSimulationContext(
452 getProjectElementService().getFirstStep(aStudy), context);
460 * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
461 * org.splat.dal.bo.som.ValidationCycle.Properties)
464 public void setValidationCycle(final Study aStudyDTO,
465 final DocumentType type, final ValidationCycle.Properties vprop) {
466 Map<String, ValidationCycle> validactor = aStudyDTO
467 .getValidationCycles();
468 if (validactor == null) {
469 setShortCuts(aStudyDTO); // Initializes validactor and actor
472 Study aStudy = selectStudy(aStudyDTO.getIndex());
474 String cname = type.getName();
475 ValidationCycle cycle = validactor.get(cname);
477 if (cycle != null && cycle.isAssigned()) {
478 resetActors(cycle, vprop);
481 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
483 getValidationCycleDAO().create(cycle); // RKV
485 ValidationCycleRelation link = cycle.getContext();
486 aStudy.addRelation(link);
487 aStudyDTO.getAllRelations().add(link); // RKV
489 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
490 } catch (BusinessException error) {
491 LOG.error("Unable to create validation cycle, reason:",
496 resetActorsShortCut(aStudyDTO);
497 update(aStudy); // Re-index the study, just in case
501 * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
502 * document of the study.
506 * @return true if the demotion succeeded.
508 public boolean demote(final Study aStudy) {
509 if (aStudy.getProgressState() == ProgressState.inCHECK) {
510 aStudy.setProgressState(ProgressState.inDRAFT);
511 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
512 aStudy.setProgressState(ProgressState.inWORK);
516 return update(aStudy);
522 * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
525 public int generateLocalIndex(final Study aStudy) {
526 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
527 return aStudy.getLastLocalIndex();
531 * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
532 * final result document of the study.
536 * @return true if the demotion succeeded.
539 public boolean promote(final Study aStudy) {
540 if (aStudy.getProgressState() == ProgressState.inWORK) {
541 aStudy.setProgressState(ProgressState.inDRAFT);
542 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
543 aStudy.setProgressState(ProgressState.inCHECK);
544 Revision myvers = new Revision(aStudy.getVersion());
545 if (myvers.isMinor()) {
546 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
549 } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
550 aStudy.setProgressState(ProgressState.APPROVED);
555 return update(aStudy);
559 * Moves this study from the Private to the Public area of the repository.
563 * @return true if the move succeeded.
567 public boolean moveToPublic(final Study aStudy) {
568 boolean isOk = false;
569 if (aStudy.getVisibility() == Visibility.PRIVATE) {
570 aStudy.setVisibility(Visibility.PUBLIC);
571 if (update(aStudy)) {
572 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
579 * Moves this study from the Public to the Private area of the repository.
583 * @return true if the move succeeded.
586 public boolean moveToPrivate(final Study aStudy) {
587 boolean isOk = false;
588 if (aStudy.getVisibility() == Visibility.PUBLIC) {
589 aStudy.setVisibility(Visibility.PRIVATE);
590 if (update(aStudy)) {
591 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
598 * Update a study in the database.
601 * the study to update
602 * @return true if the study is updated successfully
605 private boolean update(final Study aStudy) {
606 boolean isOk = false;
608 getStudyDAO().merge(aStudy); // Update of relational base
609 setShortCuts(aStudy); // RKV: initialize transient actors set
610 // RKV: getIndex().update(aStudy); // Update of Lucene index
612 } catch (Exception e) {
613 LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
619 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
623 * @return true if reference building is succeded
626 private boolean buildReference(final Study aStudy) {
627 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
628 IDBuilder tool = selectIDBuilder(aStudy.getDate());
630 tool = new IDBuilder(aStudy.getDate());
631 getIDBuilderDAO().create(tool);
633 aStudy.setReference(buildReference(tool, pattern, aStudy));
638 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
645 * the reference pattern
646 * @return true if reference building is succeded
649 public String buildReference(final IDBuilder aBuilder,
650 final String pattern, final Study study) {
651 char[] format = pattern.toCharArray();
652 char[] ref = new char[80]; // Better evaluate the length of the generated string
653 int next = aBuilder.getBase() + 1;
656 for (int i = 0; i < format.length; i++) {
658 // Insertion of attribute values
659 if (format[i] == '%') {
662 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
664 while (format[i] == 'y') {
666 if (i == format.length) {
670 SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
671 String year = tostring.format(study.getDate());
672 year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
673 for (int j = 0; j < year.length(); j++) {
674 ref[count] = year.charAt(j);
677 i -= 1; // Back to the last 'y' character
678 } else if (format[i] == '0') { // Insertion of the index
680 while (format[i] == '0') {
682 if (i == format.length) {
686 DecimalFormat tostring = new DecimalFormat(pattern
688 String number = tostring.format(next);
689 for (int j = 0; j < number.length(); j++) {
690 ref[count] = number.charAt(j);
693 i -= 1; // Back to the last '0' character
695 // Keep the character
697 ref[count] = format[i];
701 // Incrementation of the number of study
702 aBuilder.setBase(next);
703 getIDBuilderDAO().update(aBuilder);
704 return String.copyValueOf(ref, 0, count);
708 * Find an id builder by date.
712 * @return found id builder
714 private IDBuilder selectIDBuilder(final Date date) {
715 Calendar aDate = Calendar.getInstance();
717 return getIDBuilderDAO().findByCriteria(
718 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
722 * Fill transient collection ModifiableActors of the study.
727 private void resetActorsShortCut(final Study aStudy) {
728 getModifiableActors(aStudy).clear();
729 // Get all actors involved in validation cycles
730 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
731 .values().iterator(); i.hasNext();) {
732 ValidationCycle cycle = i.next();
733 User[] user = cycle.getAllActors();
734 for (int j = 0; j < user.length; j++) {
735 getModifiableActors(aStudy).add(user[j]);
738 // Get all other actors
739 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
741 Relation link = i.next();
742 Class<?> kindof = link.getClass().getSuperclass();
743 if (!kindof.equals(ActorRelation.class)) {
746 getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
751 * Update lucene index for the study knowledge elements.
755 * @return true if reindexing succeeded
757 private boolean updateKnowledgeElementsIndex(final Study aStudy) {
758 // boolean isOk = false;
760 // IndexService lucin = getIndex();
762 // for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
764 // Scenario scene = i.next();
765 // for (Iterator<KnowledgeElement> j = scene
766 // .getAllKnowledgeElements().iterator(); j.hasNext();) {
767 // KnowledgeElement kelm = j.next();
768 // lucin.update(kelm);
772 // } catch (Exception error) {
773 // LOG.error("Unable to re-index Knowledge Elements, reason:",
781 * Get lucene index service. Create a lucene index if it does not exist.
783 * @return index service
784 * @throws IOException
785 * if error occurs during lucene index creation
787 private IndexService getIndex() throws IOException {
788 IndexService lucin = getIndexService();
789 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
790 .getRepositoryIndexDirectory()))) {
791 IndexWriter.unlock(FSDirectory.open(getRepositoryService()
792 .getRepositoryIndexDirectory()));
794 if (!lucin.exists()) {
795 lucin.create(); // Happens when re-indexing all studies
801 * Create a new validation cycle for documents of the given study.
806 * the cycle description
807 * @return the new validation cycle
809 protected ValidationCycle createValidationCycle(
811 final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
812 Actor[] actype = cycle.getActorTypes();
813 User.Properties uprop = new User.Properties();
815 ValidationCycle aValidationCycle = new ValidationCycle();
816 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
817 cycle.getName())); // Null in case of default validation cycle
818 // context = new ValidationCycleRelation(from, vprop);
819 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
820 for (int i = 0; i < actype.length; i++) {
822 if (actype[i] != null) {
824 if (actype[i] == Actor.manager) {
825 actor = from.getAuthor();
826 } else if (actype[i] == Actor.Nx1) {
827 List<User> manager = getUserService().selectUsersWhere(
828 uprop.setOrganizationName("Nx1"));
829 if (manager.size() == 1) {
830 actor = manager.get(0);
832 } else if (actype[i] == Actor.Nx2) {
833 List<User> manager = getUserService().selectUsersWhere(
834 uprop.setOrganizationName("Nx2"));
835 if (manager.size() == 1) {
836 actor = manager.get(0);
838 } else { /* Actor.customer */
839 actor = from.getAuthor();
840 // TODO: Get the customer of the study, if exists
842 } catch (Exception e) { // Should not happen
847 aValidationCycle.setReviewer(actor);
849 aValidationCycle.setApprover(actor);
851 aValidationCycle.setSignatory(actor);
854 return aValidationCycle;
858 * Remove a validation step from the validation cycle.
860 * @param aValidationCycle
861 * the validation cycle
863 * the validation step to remove
866 protected void remove(final ValidationCycle aValidationCycle,
867 final ValidationStep step) {
868 if (step == ValidationStep.REVIEW) {
869 aValidationCycle.setReviewer(null);
870 } else if (step == ValidationStep.APPROVAL) {
871 aValidationCycle.setApprover(null);
872 } else if (step == ValidationStep.ACCEPTANCE
873 || step == ValidationStep.REFUSAL) {
874 aValidationCycle.setSignatory(null);
876 if (aValidationCycle.isSaved()) {
877 getValidationCycleDAO().update(aValidationCycle);
882 * Reset actors for the validation cycle.
884 * @param aValidationCycle
885 * the validation cycle to update
887 * new validation cycle properties containing new actors
890 public void resetActors(final ValidationCycle aValidationCycle,
891 final ValidationCycle.Properties vprop) {
892 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
893 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
894 aValidationCycle.setApprover(vprop.getApprover()); // May be null
895 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
896 if (aValidationCycle.isSaved()) {
897 getValidationCycleDAO().merge(aValidationCycle);
902 * Set actor for the given validation cycle and validation step.
904 * @param aValidationCycle
905 * the validation cycle
907 * the validation step
912 protected void setActor(final ValidationCycle aValidationCycle,
913 final ValidationStep step, final User actor) {
914 if (step == ValidationStep.PROMOTION) {
915 aValidationCycle.setPublisher(actor);
916 } else if (step == ValidationStep.REVIEW) {
917 aValidationCycle.setReviewer(actor);
918 } else if (step == ValidationStep.APPROVAL) {
919 aValidationCycle.setApprover(actor);
920 } else if (step == ValidationStep.ACCEPTANCE
921 || step == ValidationStep.REFUSAL) {
922 aValidationCycle.setSignatory(actor);
924 if (aValidationCycle.isSaved()) {
925 getValidationCycleDAO().update(aValidationCycle);
930 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
934 * @return the actors of this study
935 * @see #hasActor(User)
937 public Set<User> getActors(final Study aStudy) {
938 if (aStudy.getActor() == null) {
939 setShortCuts(aStudy);
941 return Collections.unmodifiableSet(aStudy.getActor());
945 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
949 * @return the modifiable set of actors of this study
950 * @see #hasActor(User)
952 public Set<User> getModifiableActors(final Study aStudy) {
953 if (aStudy.getActor() == null) {
954 setShortCuts(aStudy);
956 return aStudy.getActor();
960 * Returns unmodifiable initialized transient list of contributors of this study.
964 * @return the unmodifiable not null transient list of contributors of this study
966 public List<User> getContributors(final Study aStudy) {
967 if (aStudy.getContributor() == null) {
968 setShortCuts(aStudy);
970 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
974 * Returns modifiable initialized transient list of contributors of this study.
978 * @return the modifiable not null transient list of contributors of this study
980 public List<User> getModifiableContributors(final Study aStudy) {
981 if (aStudy.getContributor() == null) {
982 setShortCuts(aStudy);
984 return aStudy.getContributor(); // May be empty
988 * Returns the validation cycle of the given document type.
993 * the document type being subject of validation
994 * @return the validation cycle of the document, or null if not defined.
996 public ValidationCycle getValidationCycleOf(final Study aStudy,
997 final DocumentType type) {
998 if (aStudy.getValidationCycles() == null
999 || aStudy.getValidationCycles().isEmpty()) {
1000 setShortCuts(aStudy);
1002 ValidationCycle result = aStudy.getValidationCycles().get(
1004 if (result == null) {
1005 if (type.isStepResult()) {
1006 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
1008 if (result == null) {
1009 result = aStudy.getValidationCycles().get("built-in");
1016 * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
1021 * the user to look for
1022 * @return true if the given user is actor of this study.
1025 public boolean hasActor(final Study aStudy, final User user) {
1029 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
1030 User involved = i.next();
1031 if (involved.equals(user)) {
1039 * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1044 * the user to look for
1045 * @return true if the given user is actor of this study.
1046 * @see #getContributors()
1048 public boolean isStaffedBy(final Study aStudy, final User user) {
1052 if (aStudy == null) {
1055 if (aStudy.getAuthor() == null) {
1058 if (aStudy.getAuthor().equals(user)) {
1061 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1062 if (i.next().equals(user)) {
1070 * Initialize shortcuts of the study as its transient collections.
1075 public void loadWorkflow(final Study aStudy) {
1076 setShortCuts(aStudy);
1080 * Initialize shortcuts of the study as its transient collections.
1085 public void setShortCuts(final Study aStudy) {
1086 aStudy.getContributor().clear();
1087 aStudy.getValidationCycles().clear();
1088 aStudy.getActor().clear();
1090 // Get the contributors
1091 for (Iterator<Relation> i = aStudy.getRelations(
1092 ContributorRelation.class).iterator(); i.hasNext();) {
1093 ContributorRelation link = (ContributorRelation) i.next();
1094 aStudy.getContributor().add(link.getTo());
1096 // Get the validation cycles specific to this study
1097 for (Iterator<Relation> i = aStudy.getRelations(
1098 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1099 ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1100 aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1101 link.getTo()); // The associated document type is necessarily not null in this
1104 // Get the validation cycles coming from the configured workflow and not overridden in this study
1105 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1106 .getAllValidationCycles().iterator(); i.hasNext();) {
1107 ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1109 String type = cycle.getName();
1110 if (!aStudy.getValidationCycles().containsKey(type)) {
1111 aStudy.getValidationCycles().put(type,
1112 createValidationCycle(aStudy, cycle));
1115 // Get all corresponding actors
1116 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1117 .values().iterator(); i.hasNext();) {
1118 ValidationCycle cycle = i.next();
1119 User[] user = cycle.getAllActors();
1120 for (int j = 0; j < user.length; j++) {
1121 aStudy.getActor().add(user[j]);
1124 // Get all other actors
1125 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1127 Relation link = i.next();
1128 Class<?> kindof = link.getClass().getSuperclass();
1129 if (!kindof.equals(ActorRelation.class)) {
1132 aStudy.getActor().add(((ActorRelation) link).getTo());
1140 * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
1144 public void markStudyAsReference(final Study aStudy) {
1146 aStudy.setMarkreference(1);
1147 aStudy.setProgressState(ProgressState.TEMPLATE);
1148 getStudyDAO().merge(aStudy);
1155 * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
1159 public void removeStudyAsReference(final Study aStudy) {
1161 aStudy.setMarkreference(0);
1162 aStudy.setProgressState(ProgressState.APPROVED);
1163 getStudyDAO().merge(aStudy);
1169 * @see org.splat.service.StudyService#getDescription(java.lang.Long)
1172 @Transactional(readOnly = true)
1173 public String getDescription(final Long studyId)
1174 throws InvalidParameterException {
1175 if (studyId == null) {
1176 throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1178 Study study = _studyDAO.get(studyId);
1179 if (study == null) {
1180 throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString());
1182 return study.getDescription();
1188 * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
1192 public void setDescription(final Long studyId, final String descriptionText)
1193 throws InvalidParameterException {
1194 if (studyId == null) {
1195 throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1197 Study study = _studyDAO.get(studyId);
1198 if (study == null) {
1199 throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString());
1201 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1207 * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
1211 public boolean removeDescription(final Long studyId)
1212 throws InvalidParameterException {
1213 if (studyId == null) {
1214 throw new InvalidParameterException(PARAM_STUDY_ID, String
1217 Study study = _studyDAO.get(studyId);
1218 if (study == null) {
1219 throw new InvalidParameterException(PARAM_STUDY_ID, String
1222 return study.removeAttribute(study
1223 .getAttribute(DescriptionAttribute.class));
1230 * @see org.splat.service.StudyService#compare(java.util.List)
1233 public String compare(final List<DocToCompareDTO> docsList,
1234 final String userName) throws IncompatibleDataException {
1236 String axis1Name = "";
1237 String axis2Name = "";
1238 String chartTitle = "";
1239 String resultPath = "";
1241 XYSeriesCollection dataset = new XYSeriesCollection();
1243 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1245 for (; docListIter.hasNext();) {
1247 DocToCompareDTO docDTO = docListIter.next();
1248 String pathToFile = docDTO.getPathToFile();
1249 File compDocFile = new File(pathToFile);
1251 resultPath = pathToFile.substring(0, pathToFile.indexOf("vault"))
1252 + "downloads" + File.separator + userName + File.separator
1253 + "ComparisonResult.pdf";
1255 XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle());
1257 // read the file and get points information.
1259 Scanner input = new Scanner(compDocFile);
1261 //get the title of the chart.
1262 if (input.hasNext()) {
1263 chartTitle = input.nextLine();
1266 // get the name of the axis.
1267 if (input.hasNext()) {
1268 String[] tokens = input.nextLine().split(",");
1270 if (tokens.length < 2) {
1271 throw new IncompatibleDataException(
1272 MessageKeyEnum.IDT_000001.toString());
1275 if ("".equals(axis1Name)) {
1276 axis1Name = tokens[0];
1277 } else if (!axis1Name.equals(tokens[0])) {
1278 LOG.debug("Axis must be the same for all documents");
1279 throw new IncompatibleDataException(
1280 MessageKeyEnum.IDT_000001.toString());
1283 if ("".equals(axis2Name)) {
1284 axis2Name = tokens[1];
1285 } else if (!axis2Name.equals(tokens[1])) {
1286 LOG.debug("Axis must be the same for all documents");
1287 throw new IncompatibleDataException(
1288 MessageKeyEnum.IDT_000001.toString());
1292 // Get the XY points series.
1293 while (input.hasNext()) {
1295 String currentString = input.nextLine();
1297 if (!("".equals(currentString))) {
1298 String[] tokens = currentString.split(" ");
1299 series.add(Double.valueOf(tokens[0]), Double
1300 .valueOf(tokens[1]));
1305 dataset.addSeries(series);
1307 } catch (FileNotFoundException e) {
1308 LOG.error("Sorry, the file is not found.", e);
1312 JFreeChart chart = ChartFactory.createXYLineChart(
1313 chartTitle, // Title
1314 axis1Name, // x-axis Label
1315 axis2Name, // y-axis Label
1317 PlotOrientation.VERTICAL, // Plot Orientation
1318 true, // Show Legend
1319 true, // Use tooltips
1320 false // Configure chart to generate URLs?
1323 // export to PDF - file.
1326 Rectangle pagesize = new Rectangle(x, y);
1327 Document document = new Document(pagesize, 50, 50, 50, 50);
1330 File resFile = new File(resultPath);
1331 File resFolder = new File(resultPath.substring(0, resultPath
1332 .lastIndexOf(File.separator)));
1334 writer = PdfWriter.getInstance(document, new FileOutputStream(
1338 PdfContentByte cb = writer.getDirectContent();
1339 PdfTemplate tp = cb.createTemplate(x, y);
1340 Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1341 chart.draw(g2, new java.awt.Rectangle(x, y));
1343 cb.addTemplate(tp, 0, 0);
1346 } catch (FileNotFoundException e) {
1347 LOG.error("Sorry, the file is not found.", e);
1348 } catch (DocumentException e) {
1349 LOG.error("Sorry, the DocumentException is thrown.", e);
1356 * Get project settings.
1358 * @return Project settings service
1360 private ProjectSettingsService getProjectSettings() {
1361 return _projectSettings;
1365 * Set project settings service.
1367 * @param projectSettingsService
1368 * project settings service
1370 public void setProjectSettings(
1371 final ProjectSettingsService projectSettingsService) {
1372 _projectSettings = projectSettingsService;
1376 * Get the projectElementService.
1378 * @return the projectElementService
1380 public ProjectElementService getProjectElementService() {
1381 return _projectElementService;
1385 * Set the projectElementService.
1387 * @param projectElementService
1388 * the projectElementService to set
1390 public void setProjectElementService(
1391 final ProjectElementService projectElementService) {
1392 _projectElementService = projectElementService;
1396 * Get the stepService.
1398 * @return the stepService
1400 public StepService getStepService() {
1401 return _stepService;
1405 * Set the stepService.
1407 * @param stepService
1408 * the stepService to set
1410 public void setStepService(final StepService stepService) {
1411 _stepService = stepService;
1415 * Get the indexService.
1417 * @return the indexService
1419 public IndexService getIndexService() {
1420 return _indexService;
1424 * Set the indexService.
1426 * @param indexService
1427 * the indexService to set
1429 public void setIndexService(final IndexService indexService) {
1430 _indexService = indexService;
1436 * @return the studyDAO
1438 public StudyDAO getStudyDAO() {
1446 * the studyDAO to set
1448 public void setStudyDAO(final StudyDAO studyDAO) {
1449 _studyDAO = studyDAO;
1453 * Get the iDBuilderDAO.
1455 * @return the iDBuilderDAO
1457 public IDBuilderDAO getIDBuilderDAO() {
1458 return _iDBuilderDAO;
1462 * Set the iDBuilderDAO.
1465 * the iDBuilderDAO to set
1467 public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1468 _iDBuilderDAO = builderDAO;
1472 * Get the scenarioDAO.
1474 * @return the scenarioDAO
1476 public ScenarioDAO getScenarioDAO() {
1477 return _scenarioDAO;
1481 * Set the scenarioDAO.
1483 * @param scenarioDAO
1484 * the scenarioDAO to set
1486 public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1487 _scenarioDAO = scenarioDAO;
1491 * Get the validationCycleDAO.
1493 * @return the validationCycleDAO
1495 public ValidationCycleDAO getValidationCycleDAO() {
1496 return _validationCycleDAO;
1500 * Set the validationCycleDAO.
1502 * @param validationCycleDAO
1503 * the validationCycleDAO to set
1505 public void setValidationCycleDAO(
1506 final ValidationCycleDAO validationCycleDAO) {
1507 _validationCycleDAO = validationCycleDAO;
1511 * Get the documentTypeService.
1513 * @return the documentTypeService
1515 public DocumentTypeService getDocumentTypeService() {
1516 return _documentTypeService;
1520 * Set the documentTypeService.
1522 * @param documentTypeService
1523 * the documentTypeService to set
1525 public void setDocumentTypeService(
1526 final DocumentTypeService documentTypeService) {
1527 _documentTypeService = documentTypeService;
1531 * Get the userService.
1533 * @return the userService
1535 public UserService getUserService() {
1536 return _userService;
1540 * Set the userService.
1542 * @param userService
1543 * the userService to set
1545 public void setUserService(final UserService userService) {
1546 _userService = userService;
1552 * @see org.splat.service.StudyService#getComparableStudies()
1554 @Transactional(readOnly = true)
1555 public List<StudyFacadeDTO> getComparableStudies(final long userId) throws MismatchException {
1556 //retrieve the number of the "Analyze the results" step
1557 List<Step> allSteps = _projectSettings.getAllSteps();
1558 Step theAnalyzeStep = null;
1559 for(Step step : allSteps) {
1560 if(step.getKey().equals("postprocessing")) {
1561 theAnalyzeStep = step;
1564 if(theAnalyzeStep == null) { //TODO: throw some other exception
1565 throw new MismatchException("no step with key 'postprocessing' found." +
1566 "Probably, customization settings have been changed.");
1569 List<Publication> publications = _publicationDAO.getFilteredList("mydoc",
1570 Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber())));
1572 //split retrieved publications into groups by studies and scenarios
1573 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1574 Map<ProjectElement, List<Publication>> scenarioMap =
1575 new HashMap<ProjectElement, List<Publication>>();
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())) {
1584 //check the study visibility to the user
1585 if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId))
1586 && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) {
1590 Study study = publication.getOwnerStudy();
1591 ProjectElement scenario = publication.getOwner();
1593 Hibernate.initialize(scenario);
1594 if (scenario instanceof HibernateProxy) {
1595 scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer()
1596 .getImplementation();
1599 if(!(scenario instanceof Scenario)) {
1600 throw new MismatchException(
1601 "publications from postprocessing step are supposed to have owner scenario");
1604 if(!studyMap.containsKey(study)) {
1605 studyMap.put(study, new ArrayList<ProjectElement>());
1608 if(!studyMap.get(study).contains(scenario)) {
1609 studyMap.get(study).add(scenario);
1612 if(!scenarioMap.containsKey(scenario)) {
1613 scenarioMap.put(scenario, new ArrayList<Publication>());
1615 scenarioMap.get(scenario).add(publication);
1618 //Create the result DTOs
1619 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1620 for(Study study : studyMap.keySet()) {
1622 StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1623 studyDTO.setName(study.getTitle());
1624 studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1625 result.add(studyDTO);
1627 for(ProjectElement scenario : studyMap.get(study)) {
1629 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1630 scenarioDTO.setName(scenario.getTitle());
1631 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1632 studyDTO.getScenarios().add(scenarioDTO);
1634 for(Publication publication : scenarioMap.get(scenario)) {
1636 DocumentDTO documentDTO = new DocumentDTO();
1637 documentDTO.setId(publication.getIndex());
1638 documentDTO.setTitle(publication.value().getTitle());
1640 scenarioDTO.getDocs().add(documentDTO);
1648 * Get the publicationDAO.
1650 * @return the publicationDAO
1652 public PublicationDAO getPublicationDAO() {
1653 return _publicationDAO;
1657 * Set the publicationDAO.
1659 * @param publicationDAO
1660 * the publicationDAO to set
1662 public void setPublicationDAO(final PublicationDAO publicationDAO) {
1663 _publicationDAO = publicationDAO;
1667 * Get the repositoryService.
1669 * @return the repositoryService
1671 public RepositoryService getRepositoryService() {
1672 return _repositoryService;
1676 * Set the repositoryService.
1678 * @param repositoryService
1679 * the repositoryService to set
1681 public void setRepositoryService(final RepositoryService repositoryService) {
1682 _repositoryService = repositoryService;
1686 * Get the documentDAO.
1688 * @return the documentDAO
1690 public DocumentDAO getDocumentDAO() {
1691 return _documentDAO;
1695 * Set the documentDAO.
1697 * @param documentDAO
1698 * the documentDAO to set
1700 public void setDocumentDAO(final DocumentDAO documentDAO) {
1701 _documentDAO = documentDAO;
1705 * Get the descriptionAttributeDAO.
1707 * @return the descriptionAttributeDAO
1709 public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1710 return _descriptionAttributeDAO;
1714 * Set the descriptionAttributeDAO.
1716 * @param descriptionAttributeDAO
1717 * the descriptionAttributeDAO to set
1719 public void setDescriptionAttributeDAO(
1720 final DescriptionAttributeDAO descriptionAttributeDAO) {
1721 _descriptionAttributeDAO = descriptionAttributeDAO;
1725 * Get the usedByRelationDAO.
1727 * @return the usedByRelationDAO
1729 public UsedByRelationDAO getUsedByRelationDAO() {
1730 return _usedByRelationDAO;
1734 * Set the usedByRelationDAO.
1736 * @param usedByRelationDAO
1737 * the usedByRelationDAO to set
1739 public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
1740 _usedByRelationDAO = usedByRelationDAO;