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.Iterator;
25 import java.util.List;
27 import java.util.Scanner;
30 import org.apache.lucene.index.IndexWriter;
31 import org.apache.lucene.store.FSDirectory;
32 import org.hibernate.Hibernate;
33 import org.hibernate.criterion.Restrictions;
34 import org.hibernate.proxy.HibernateProxy;
35 import org.jfree.chart.ChartFactory;
36 import org.jfree.chart.JFreeChart;
37 import org.jfree.chart.plot.PlotOrientation;
38 import org.jfree.data.xy.XYSeries;
39 import org.jfree.data.xy.XYSeriesCollection;
40 import org.splat.common.properties.MessageKeyEnum;
41 import org.splat.dal.bo.kernel.Relation;
42 import org.splat.dal.bo.kernel.User;
43 import org.splat.dal.bo.som.ActorRelation;
44 import org.splat.dal.bo.som.ContributorRelation;
45 import org.splat.dal.bo.som.DescriptionAttribute;
46 import org.splat.dal.bo.som.DocumentType;
47 import org.splat.dal.bo.som.IDBuilder;
48 import org.splat.dal.bo.som.ProgressState;
49 import org.splat.dal.bo.som.ProjectElement;
50 import org.splat.dal.bo.som.Publication;
51 import org.splat.dal.bo.som.Scenario;
52 import org.splat.dal.bo.som.SimulationContext;
53 import org.splat.dal.bo.som.Study;
54 import org.splat.dal.bo.som.Study.Properties;
55 import org.splat.dal.bo.som.ValidationCycle;
56 import org.splat.dal.bo.som.ValidationCycle.Actor;
57 import org.splat.dal.bo.som.ValidationCycleRelation;
58 import org.splat.dal.bo.som.ValidationStep;
59 import org.splat.dal.bo.som.Visibility;
60 import org.splat.dal.dao.som.DescriptionAttributeDAO;
61 import org.splat.dal.dao.som.DocumentDAO;
62 import org.splat.dal.dao.som.IDBuilderDAO;
63 import org.splat.dal.dao.som.PublicationDAO;
64 import org.splat.dal.dao.som.ScenarioDAO;
65 import org.splat.dal.dao.som.StudyDAO;
66 import org.splat.dal.dao.som.ValidationCycleDAO;
67 import org.splat.exception.IncompatibleDataException;
68 import org.splat.exception.InvalidParameterException;
69 import org.splat.kernel.InvalidPropertyException;
70 import org.splat.kernel.MismatchException;
71 import org.splat.kernel.MissedPropertyException;
72 import org.splat.kernel.MultiplyDefinedException;
73 import org.splat.log.AppLogger;
74 import org.splat.service.dto.DocToCompareDTO;
75 import org.splat.service.dto.DocumentDTO;
76 import org.splat.service.dto.StudyFacadeDTO;
77 import org.splat.service.technical.IndexService;
78 import org.splat.service.technical.ProjectSettingsService;
79 import org.splat.service.technical.ProjectSettingsService.Step;
80 import org.splat.service.technical.ProjectSettingsServiceImpl;
81 import org.splat.service.technical.RepositoryService;
82 import org.splat.som.Revision;
83 import org.springframework.transaction.annotation.Transactional;
85 import com.lowagie.text.Document;
86 import com.lowagie.text.DocumentException;
87 import com.lowagie.text.Rectangle;
88 import com.lowagie.text.pdf.DefaultFontMapper;
89 import com.lowagie.text.pdf.PdfContentByte;
90 import com.lowagie.text.pdf.PdfTemplate;
91 import com.lowagie.text.pdf.PdfWriter;
94 * This class defines all methods for creation, modification the study.
96 * @author Maria KRUCHININA
99 public class StudyServiceImpl implements StudyService {
102 * logger for the service.
104 public final static AppLogger LOG = AppLogger
105 .getLogger(StudyServiceImpl.class);
108 * Injected index service.
110 private IndexService _indexService;
113 * Injected step service.
115 private StepService _stepService;
118 * Injected project service.
120 private ProjectSettingsService _projectSettings;
123 * Injected project element service.
125 private ProjectElementService _projectElementService;
128 * Injected study DAO.
130 private StudyDAO _studyDAO;
133 * Injected scenario DAO.
135 private ScenarioDAO _scenarioDAO;
138 * Injected validation cycle DAO.
140 private ValidationCycleDAO _validationCycleDAO;
143 * Injected IDBuilder DAO.
145 private IDBuilderDAO _iDBuilderDAO;
148 * Injected document type service.
150 private DocumentTypeService _documentTypeService;
153 * Injected user service.
155 private UserService _userService;
158 * Injected publication DAO.
160 private PublicationDAO _publicationDAO;
163 * Injected repository service.
165 private RepositoryService _repositoryService;
168 * Injected document DAO.
170 private DocumentDAO _documentDAO;
173 * Injected description attribute DAO.
175 private DescriptionAttributeDAO _descriptionAttributeDAO;
180 * @see org.splat.service.StudyService#selectStudy(long)
184 public Study selectStudy(final long index) {
185 Study result = getStudyDAO().get(index);
186 loadWorkflow(result);
192 * @see org.splat.service.StudyService#removeStudy(long)
195 public void removeStudy(final long index) {
196 Study study = getStudyDAO().get(index);
198 getStudyDAO().delete(study);
203 * Get study by its reference.
206 * the study reference
207 * @return found study or null
209 @Transactional(readOnly = true)
210 public Study selectStudy(final String refid) {
211 Study result = getStudyDAO().findByCriteria(
212 Restrictions.eq("sid", refid));
213 loadWorkflow(result);
220 * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
224 public Study createStudy(final Study.Properties sprop)
225 throws MissedPropertyException, InvalidPropertyException,
226 MultiplyDefinedException {
227 sprop.setReference(getProjectSettings().getReferencePattern());
228 Study study = new Study(sprop);
230 buildReference(study);
231 getStudyDAO().create(study);
233 // IndexService lucin = getIndex();
235 // } catch (IOException error) {
236 // LOG.error("Unable to index the study '" + study.getIndex()
237 // + "', reason:", error);
238 // // Continue and try to index later
246 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
250 public SimulationContext addProjectContext(final Study aStudy,
251 final SimulationContext.Properties cprop)
252 throws MissedPropertyException, InvalidPropertyException,
253 MultiplyDefinedException {
254 SimulationContext added = getStepService().addSimulationContext(
255 getProjectElementService().getFirstStep(aStudy), cprop);
263 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
267 public SimulationContext addProjectContext(final Study aStudy,
268 final SimulationContext context) {
269 SimulationContext added = getStepService().addSimulationContext(
270 getProjectElementService().getFirstStep(aStudy), context);
278 * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
281 public boolean addContributor(final Study aStudy, final User user) {
282 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
283 for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
284 User present = i.next();
285 if (present.equals(user)) {
289 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
291 aStudy.addRelation(new ContributorRelation(aStudy, user));
293 update(aStudy); // Else, useless to re-index the study
295 contributor.add(user);
300 * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
301 * previously be approved.
305 * @return true if the move succeeded.
306 * @see #moveToPublic()
308 * @see Publication#approve(Date)
311 public boolean moveToReference(final Study aStudy) {
312 if (aStudy.getProgressState() != ProgressState.APPROVED) {
315 if (aStudy.getVisibility() != Visibility.PUBLIC) {
319 aStudy.setVisibility(Visibility.REFERENCE);
320 if (update(aStudy)) {
321 return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
329 * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
332 public boolean update(final Study aStudy, final Properties sprop)
333 throws InvalidPropertyException {
334 if (sprop.getTitle() != null) {
335 aStudy.setTitle(sprop.getTitle());
337 if (sprop.getSummary() != null) {
338 aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
341 // TODO: To be completed
342 return update(aStudy);
346 * Check if the document is published in the study.
352 * @return true if the document is published in the study
354 /* private boolean publishes(final Study aStudy, final Document doc) {
355 if (!aStudy.publishes(doc)) {
356 Scenario[] scene = aStudy.getScenarii();
357 for (int i = 0; i < scene.length; i++) {
358 if (scene[i].publishes(doc)) {
369 * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
372 public boolean removeContributor(final Study aStudy, final User... users) {
373 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
374 Boolean done = false;
375 for (int i = 0; i < users.length; i++) {
376 User user = users[i];
377 for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
378 User present = j.next();
379 if (!present.equals(user)) {
383 aStudy.removeRelation(ContributorRelation.class, user);
384 j.remove(); // Updates the contributor shortcut
398 * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
401 public boolean removeProjectContext(final Study aStudy,
402 final SimulationContext context) {
403 boolean done = getStepService().removeSimulationContext(
404 getProjectElementService().getFirstStep(aStudy), context);
412 * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
413 * org.splat.dal.bo.som.ValidationCycle.Properties)
417 public void setValidationCycle(final Study aStudyDTO, final DocumentType type,
418 final ValidationCycle.Properties vprop) {
419 Map<String, ValidationCycle> validactor = aStudyDTO.getValidationCycles();
420 if (validactor == null) {
421 setShortCuts(aStudyDTO); // Initializes validactor and actor
424 Study aStudy = selectStudy(aStudyDTO.getIndex());
426 String cname = type.getName();
427 ValidationCycle cycle = validactor.get(cname);
429 if (cycle != null && cycle.isAssigned()) {
430 resetActors(cycle, vprop);
433 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
435 getValidationCycleDAO().create(cycle); // RKV
437 ValidationCycleRelation link = cycle.getContext();
438 aStudy.addRelation(link);
439 aStudyDTO.getAllRelations().add(link); // RKV
441 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
442 } catch (Exception error) {
443 LOG.error("Unable to re-index Knowledge Elements, reason:",
448 resetActorsShortCut(aStudyDTO);
449 update(aStudy); // Re-index the study, just in case
453 * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
454 * document of the study.
458 * @return true if the demotion succeeded.
461 public boolean demote(final Study aStudy) {
462 if (aStudy.getProgressState() == ProgressState.inCHECK) {
463 aStudy.setProgressState(ProgressState.inDRAFT);
464 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
465 aStudy.setProgressState(ProgressState.inWORK);
469 return update(aStudy);
475 * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
479 public int generateLocalIndex(final Study aStudy) {
480 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
481 return aStudy.getLastLocalIndex();
485 * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
486 * final result document of the study.
490 * @return true if the demotion succeeded.
494 public boolean promote(final Study aStudy) {
495 if (aStudy.getProgressState() == ProgressState.inWORK) {
496 aStudy.setProgressState(ProgressState.inDRAFT);
497 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
498 aStudy.setProgressState(ProgressState.inCHECK);
499 Revision myvers = new Revision(aStudy.getVersion());
500 if (myvers.isMinor()) {
501 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
504 } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
505 aStudy.setProgressState(ProgressState.APPROVED);
510 return update(aStudy);
514 * Moves this study from the Private to the Public area of the repository.
518 * @return true if the move succeeded.
523 public boolean moveToPublic(final Study aStudy) {
524 boolean isOk = false;
525 if (aStudy.getVisibility() == Visibility.PRIVATE) {
526 aStudy.setVisibility(Visibility.PUBLIC);
527 if (update(aStudy)) {
528 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
535 * Moves this study from the Public to the Private area of the repository.
539 * @return true if the move succeeded.
543 public boolean moveToPrivate(final Study aStudy) {
544 boolean isOk = false;
545 if (aStudy.getVisibility() == Visibility.PUBLIC) {
546 aStudy.setVisibility(Visibility.PRIVATE);
547 if (update(aStudy)) {
548 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
555 * Update a study in the database.
558 * the study to update
559 * @return true if the study is updated successfully
562 private boolean update(final Study aStudy) {
563 boolean isOk = false;
565 getStudyDAO().merge(aStudy); // Update of relational base
566 setShortCuts(aStudy); // RKV: initialize transient actors set
567 //RKV: getIndex().update(aStudy); // Update of Lucene index
569 } catch (Exception e) {
570 LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
576 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
580 * @return true if reference building is succeded
583 private boolean buildReference(final Study aStudy) {
584 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
585 IDBuilder tool = selectIDBuilder(aStudy.getDate());
587 tool = new IDBuilder(aStudy.getDate());
588 getIDBuilderDAO().create(tool);
590 aStudy.setReference(buildReference(tool, pattern, aStudy));
595 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
602 * the reference pattern
603 * @return true if reference building is succeded
606 public String buildReference(final IDBuilder aBuilder,
607 final String pattern, final Study study) {
608 char[] format = pattern.toCharArray();
609 char[] ref = new char[80]; // Better evaluate the length of the generated string
610 int next = aBuilder.getBase() + 1;
613 for (int i = 0; i < format.length; i++) {
615 // Insertion of attribute values
616 if (format[i] == '%') {
619 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
621 while (format[i] == 'y') {
623 if (i == format.length) {
627 SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); //RKV: NOPMD: TODO: Use locale here?
628 String year = tostring.format(study.getDate());
629 year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
630 for (int j = 0; j < year.length(); j++) {
631 ref[count] = year.charAt(j);
634 i -= 1; // Back to the last 'y' character
635 } else if (format[i] == '0') { // Insertion of the index
637 while (format[i] == '0') {
639 if (i == format.length) {
643 DecimalFormat tostring = new DecimalFormat(pattern
645 String number = tostring.format(next);
646 for (int j = 0; j < number.length(); j++) {
647 ref[count] = number.charAt(j);
650 i -= 1; // Back to the last '0' character
652 // Keep the character
654 ref[count] = format[i];
658 // Incrementation of the number of study
659 aBuilder.setBase(next);
660 getIDBuilderDAO().update(aBuilder);
661 return String.copyValueOf(ref, 0, count);
665 * Find an id builder by date.
669 * @return found id builder
671 private IDBuilder selectIDBuilder(final Date date) {
672 Calendar aDate = Calendar.getInstance();
674 return getIDBuilderDAO().findByCriteria(
675 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
679 * Fill transient collection ModifiableActors of the study.
684 private void resetActorsShortCut(final Study aStudy) {
685 getModifiableActors(aStudy).clear();
686 // Get all actors involved in validation cycles
687 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
688 .values().iterator(); i.hasNext();) {
689 ValidationCycle cycle = i.next();
690 User[] user = cycle.getAllActors();
691 for (int j = 0; j < user.length; j++) {
692 getModifiableActors(aStudy).add(user[j]);
695 // Get all other actors
696 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
698 Relation link = i.next();
699 Class<?> kindof = link.getClass().getSuperclass();
700 if (!kindof.equals(ActorRelation.class)) {
703 getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
708 * Update lucene index for the study knowledge elements.
712 * @return true if reindexing succeeded
714 private boolean updateKnowledgeElementsIndex(final Study aStudy) {
715 // boolean isOk = false;
717 // IndexService lucin = getIndex();
719 // for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
721 // Scenario scene = i.next();
722 // for (Iterator<KnowledgeElement> j = scene
723 // .getAllKnowledgeElements().iterator(); j.hasNext();) {
724 // KnowledgeElement kelm = j.next();
725 // lucin.update(kelm);
729 // } catch (Exception error) {
730 // LOG.error("Unable to re-index Knowledge Elements, reason:",
738 * Get lucene index service. Create a lucene index if it does not exist.
740 * @return index service
741 * @throws IOException
742 * if error occurs during lucene index creation
744 private IndexService getIndex() throws IOException {
745 IndexService lucin = getIndexService();
746 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
747 .getRepositoryIndexDirectory()))) {
748 IndexWriter.unlock(FSDirectory.open(getRepositoryService()
749 .getRepositoryIndexDirectory()));
751 if (!lucin.exists()) {
752 lucin.create(); // Happens when re-indexing all studies
758 * Create a new validation cycle for documents of the given study.
763 * the cycle description
764 * @return the new validation cycle
766 protected ValidationCycle createValidationCycle(
768 final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
769 Actor[] actype = cycle.getActorTypes();
770 User.Properties uprop = new User.Properties();
772 ValidationCycle aValidationCycle = new ValidationCycle();
773 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
774 cycle.getName())); // Null in case of default validation cycle
775 // context = new ValidationCycleRelation(from, vprop);
776 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
777 for (int i = 0; i < actype.length; i++) {
779 if (actype[i] != null) {
781 if (actype[i] == Actor.manager) {
782 actor = from.getAuthor();
783 } else if (actype[i] == Actor.Nx1) {
784 List<User> manager = getUserService().selectUsersWhere(
785 uprop.setOrganizationName("Nx1"));
786 if (manager.size() == 1) {
787 actor = manager.get(0);
789 } else if (actype[i] == Actor.Nx2) {
790 List<User> manager = getUserService().selectUsersWhere(
791 uprop.setOrganizationName("Nx2"));
792 if (manager.size() == 1) {
793 actor = manager.get(0);
795 } else { /* Actor.customer */
796 actor = from.getAuthor();
797 // TODO: Get the customer of the study, if exists
799 } catch (Exception e) { // Should not happen
804 aValidationCycle.setReviewer(actor);
806 aValidationCycle.setApprover(actor);
808 aValidationCycle.setSignatory(actor);
811 return aValidationCycle;
815 * Remove a validation step from the validation cycle.
817 * @param aValidationCycle
818 * the validation cycle
820 * the validation step to remove
823 protected void remove(final ValidationCycle aValidationCycle,
824 final ValidationStep step) {
825 if (step == ValidationStep.REVIEW) {
826 aValidationCycle.setReviewer(null);
827 } else if (step == ValidationStep.APPROVAL) {
828 aValidationCycle.setApprover(null);
829 } else if (step == ValidationStep.ACCEPTANCE
830 || step == ValidationStep.REFUSAL) {
831 aValidationCycle.setSignatory(null);
833 if (aValidationCycle.isSaved()) {
834 getValidationCycleDAO().update(aValidationCycle);
839 * Reset actors for the validation cycle.
841 * @param aValidationCycle
842 * the validation cycle to update
844 * new validation cycle properties containing new actors
847 public void resetActors(final ValidationCycle aValidationCycle,
848 final ValidationCycle.Properties vprop) {
849 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
850 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
851 aValidationCycle.setApprover(vprop.getApprover()); // May be null
852 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
853 if (aValidationCycle.isSaved()) {
854 getValidationCycleDAO().merge(aValidationCycle);
859 * Set actor for the given validation cycle and validation step.
861 * @param aValidationCycle
862 * the validation cycle
864 * the validation step
869 protected void setActor(final ValidationCycle aValidationCycle,
870 final ValidationStep step, final User actor) {
871 if (step == ValidationStep.PROMOTION) {
872 aValidationCycle.setPublisher(actor);
873 } else if (step == ValidationStep.REVIEW) {
874 aValidationCycle.setReviewer(actor);
875 } else if (step == ValidationStep.APPROVAL) {
876 aValidationCycle.setApprover(actor);
877 } else if (step == ValidationStep.ACCEPTANCE
878 || step == ValidationStep.REFUSAL) {
879 aValidationCycle.setSignatory(actor);
881 if (aValidationCycle.isSaved()) {
882 getValidationCycleDAO().update(aValidationCycle);
887 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
891 * @return the actors of this study
892 * @see #hasActor(User)
894 public Set<User> getActors(final Study aStudy) {
895 if (aStudy.getActor() == null) {
896 setShortCuts(aStudy);
898 return Collections.unmodifiableSet(aStudy.getActor());
902 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
906 * @return the modifiable set of actors of this study
907 * @see #hasActor(User)
909 public Set<User> getModifiableActors(final Study aStudy) {
910 if (aStudy.getActor() == null) {
911 setShortCuts(aStudy);
913 return aStudy.getActor();
917 * Returns unmodifiable initialized transient list of contributors of this study.
921 * @return the unmodifiable not null transient list of contributors of this study
924 public List<User> getContributors(final Study aStudy) {
925 if (aStudy.getContributor() == null) {
926 setShortCuts(aStudy);
928 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
932 * Returns modifiable initialized transient list of contributors of this study.
936 * @return the modifiable not null transient list of contributors of this study
938 public List<User> getModifiableContributors(final Study aStudy) {
939 if (aStudy.getContributor() == null) {
940 setShortCuts(aStudy);
942 return aStudy.getContributor(); // May be empty
946 * Returns the validation cycle of the given document type.
951 * the document type being subject of validation
952 * @return the validation cycle of the document, or null if not defined.
955 public ValidationCycle getValidationCycleOf(final Study aStudy,
956 final DocumentType type) {
957 if (aStudy.getValidationCycles() == null || aStudy.getValidationCycles().isEmpty()) {
958 setShortCuts(aStudy);
960 ValidationCycle result = aStudy.getValidationCycles().get(
962 if (result == null) {
963 if (type.isStepResult()) {
964 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
966 if (result == null) {
967 result = aStudy.getValidationCycles().get("built-in");
974 * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
979 * the user to look for
980 * @return true if the given user is actor of this study.
984 public boolean hasActor(final Study aStudy, final User user) {
988 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
989 User involved = i.next();
990 if (involved.equals(user)) {
998 * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1003 * the user to look for
1004 * @return true if the given user is actor of this study.
1005 * @see #getContributors()
1008 public boolean isStaffedBy(final Study aStudy, final User user) {
1012 if (aStudy == null) {
1015 if (aStudy.getAuthor() == null) {
1018 if (aStudy.getAuthor().equals(user)) {
1021 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1022 if (i.next().equals(user)) {
1030 * Initialize shortcuts of the study as its transient collections.
1036 public void loadWorkflow(final Study aStudy) {
1037 setShortCuts(aStudy);
1041 * Initialize shortcuts of the study as its transient collections.
1046 public void setShortCuts(final Study aStudy) {
1047 aStudy.getContributor().clear();
1048 aStudy.getValidationCycles().clear();
1049 aStudy.getActor().clear();
1051 // Get the contributors
1052 for (Iterator<Relation> i = aStudy.getRelations(
1053 ContributorRelation.class).iterator(); i.hasNext();) {
1054 ContributorRelation link = (ContributorRelation) i.next();
1055 aStudy.getContributor().add(link.getTo());
1057 // Get the validation cycles specific to this study
1058 for (Iterator<Relation> i = aStudy.getRelations(
1059 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1060 ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1061 aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1062 link.getTo()); // The associated document type is necessarily not null in this
1065 // Get the validation cycles coming from the configured workflow and not overridden in this study
1066 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1067 .getAllValidationCycles().iterator(); i.hasNext();) {
1068 ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1070 String type = cycle.getName();
1071 if (!aStudy.getValidationCycles().containsKey(type)) {
1072 aStudy.getValidationCycles().put(type,
1073 createValidationCycle(aStudy, cycle));
1076 // Get all corresponding actors
1077 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1078 .values().iterator(); i.hasNext();) {
1079 ValidationCycle cycle = i.next();
1080 User[] user = cycle.getAllActors();
1081 for (int j = 0; j < user.length; j++) {
1082 aStudy.getActor().add(user[j]);
1085 // Get all other actors
1086 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1088 Relation link = i.next();
1089 Class<?> kindof = link.getClass().getSuperclass();
1090 if (!kindof.equals(ActorRelation.class)) {
1093 aStudy.getActor().add(((ActorRelation) link).getTo());
1100 * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
1104 public void markStudyAsReference (final Study aStudy) {
1106 aStudy.setMarkreference(1);
1107 aStudy.setProgressState(ProgressState.TEMPLATE);
1108 getStudyDAO().merge(aStudy);
1114 * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
1118 public void removeStudyAsReference(final Study aStudy) {
1120 aStudy.setMarkreference(0);
1121 aStudy.setProgressState(ProgressState.APPROVED);
1122 getStudyDAO().merge(aStudy);
1128 * @see org.splat.service.StudyService#getDescription(java.lang.Long)
1131 @Transactional(readOnly = true)
1132 public String getDescription(final Long studyId) throws InvalidParameterException {
1133 if(studyId == null) {
1134 throw new InvalidParameterException("studyId", "null");
1136 Study study = _studyDAO.get(studyId);
1138 throw new InvalidParameterException("studyId", studyId.toString());
1140 return study.getDescription();
1146 * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
1150 public void setDescription(final Long studyId, final String descriptionText)
1151 throws InvalidParameterException {
1152 if(studyId == null) {
1153 throw new InvalidParameterException("studyId", "null");
1155 Study study = _studyDAO.get(studyId);
1157 throw new InvalidParameterException("studyId", studyId.toString());
1159 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1164 * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
1168 public boolean removeDescription(final Long studyId) throws InvalidParameterException {
1169 if(studyId == null) {
1170 throw new InvalidParameterException("studyId", String.valueOf(studyId));
1172 Study study = _studyDAO.get(studyId);
1174 throw new InvalidParameterException("studyId", String.valueOf(studyId));
1176 return study.removeAttribute(study.getAttribute(DescriptionAttribute.class));
1183 * @see org.splat.service.StudyService#compare(java.util.List)
1186 public String compare (final List<DocToCompareDTO> docsList, final String userName) throws IncompatibleDataException{
1188 String axis1Name = "";
1189 String axis2Name = "";
1190 String chartTitle = "";
1191 String resultPath = "";
1193 XYSeriesCollection dataset = new XYSeriesCollection();
1195 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1197 for (; docListIter.hasNext();) {
1199 DocToCompareDTO docDTO = docListIter.next();
1200 String pathToFile = docDTO.getPathToFile();
1201 File compDocFile = new File(pathToFile);
1203 resultPath = pathToFile.substring(0, pathToFile.indexOf("vault")) + "downloads" + File.separator + userName + File.separator + "ComparisonResult.pdf";
1205 XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle());
1207 //read the file and get points information.
1209 Scanner input = new Scanner(compDocFile);
1211 //get the title of the chart.
1212 if (input.hasNext()) {
1213 chartTitle = input.nextLine();
1216 //get the name of the axis.
1217 if (input.hasNext()) {
1218 String[] tokens = input.nextLine().split(",");
1220 if (tokens.length < 2)
1221 throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
1223 if ("".equals(axis1Name)) {
1224 axis1Name = tokens[0];
1225 } else if (!axis1Name.equals(tokens[0])) {
1226 LOG.debug("Axis must be the same for all documents");
1227 throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
1230 if ("".equals(axis2Name)) {
1231 axis2Name = tokens[1];
1232 } else if (!axis2Name.equals(tokens[1])) {
1233 LOG.debug("Axis must be the same for all documents");
1234 throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
1238 //Get the XY points series.
1239 while(input.hasNext()) {
1241 String currentString = input.nextLine();
1243 if ("".equals(currentString)) {
1247 String[] tokens = currentString.split(" ");
1248 series.add(Double.valueOf(tokens[0]), Double.valueOf(tokens[1]));
1253 dataset.addSeries(series);
1255 } catch (FileNotFoundException e) {
1256 // TODO Auto-generated catch block
1257 e.printStackTrace();
1262 JFreeChart chart = ChartFactory.createXYLineChart(
1263 chartTitle, // Title
1264 axis1Name, // x-axis Label
1265 axis2Name, // y-axis Label
1267 PlotOrientation.VERTICAL, // Plot Orientation
1268 true, // Show Legend
1269 true, // Use tooltips
1270 false // Configure chart to generate URLs?
1273 //export to PDF - file.
1276 Rectangle pagesize = new Rectangle(x, y);
1277 Document document = new Document(pagesize, 50, 50, 50, 50);
1280 File resFile = new File(resultPath);
1281 File resFolder = new File(resultPath.substring(0, resultPath.lastIndexOf(File.separator)));
1283 writer = PdfWriter.getInstance(document, new FileOutputStream(resFile));
1286 PdfContentByte cb = writer.getDirectContent();
1287 PdfTemplate tp = cb.createTemplate(x, y);
1288 Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1289 chart.draw(g2, new java.awt.Rectangle(x,y));
1291 cb.addTemplate(tp, 0, 0);
1294 } catch (FileNotFoundException e) {
1295 // TODO Auto-generated catch block
1296 e.printStackTrace();
1297 } catch (DocumentException e) {
1298 // TODO Auto-generated catch block
1299 e.printStackTrace();
1306 * Get project settings.
1308 * @return Project settings service
1310 private ProjectSettingsService getProjectSettings() {
1311 return _projectSettings;
1315 * Set project settings service.
1317 * @param projectSettingsService
1318 * project settings service
1320 public void setProjectSettings(
1321 final ProjectSettingsService projectSettingsService) {
1322 _projectSettings = projectSettingsService;
1326 * Get the projectElementService.
1328 * @return the projectElementService
1330 public ProjectElementService getProjectElementService() {
1331 return _projectElementService;
1335 * Set the projectElementService.
1337 * @param projectElementService
1338 * the projectElementService to set
1340 public void setProjectElementService(
1341 final ProjectElementService projectElementService) {
1342 _projectElementService = projectElementService;
1346 * Get the stepService.
1348 * @return the stepService
1350 public StepService getStepService() {
1351 return _stepService;
1355 * Set the stepService.
1357 * @param stepService
1358 * the stepService to set
1360 public void setStepService(final StepService stepService) {
1361 _stepService = stepService;
1365 * Get the indexService.
1367 * @return the indexService
1369 public IndexService getIndexService() {
1370 return _indexService;
1374 * Set the indexService.
1376 * @param indexService
1377 * the indexService to set
1379 public void setIndexService(final IndexService indexService) {
1380 _indexService = indexService;
1386 * @return the studyDAO
1388 public StudyDAO getStudyDAO() {
1396 * the studyDAO to set
1398 public void setStudyDAO(final StudyDAO studyDAO) {
1399 _studyDAO = studyDAO;
1403 * Get the iDBuilderDAO.
1405 * @return the iDBuilderDAO
1407 public IDBuilderDAO getIDBuilderDAO() {
1408 return _iDBuilderDAO;
1412 * Set the iDBuilderDAO.
1415 * the iDBuilderDAO to set
1417 public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1418 _iDBuilderDAO = builderDAO;
1422 * Get the scenarioDAO.
1424 * @return the scenarioDAO
1426 public ScenarioDAO getScenarioDAO() {
1427 return _scenarioDAO;
1431 * Set the scenarioDAO.
1433 * @param scenarioDAO
1434 * the scenarioDAO to set
1436 public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1437 _scenarioDAO = scenarioDAO;
1441 * Get the validationCycleDAO.
1443 * @return the validationCycleDAO
1445 public ValidationCycleDAO getValidationCycleDAO() {
1446 return _validationCycleDAO;
1450 * Set the validationCycleDAO.
1452 * @param validationCycleDAO
1453 * the validationCycleDAO to set
1455 public void setValidationCycleDAO(
1456 final ValidationCycleDAO validationCycleDAO) {
1457 _validationCycleDAO = validationCycleDAO;
1461 * Get the documentTypeService.
1463 * @return the documentTypeService
1465 public DocumentTypeService getDocumentTypeService() {
1466 return _documentTypeService;
1470 * Set the documentTypeService.
1472 * @param documentTypeService
1473 * the documentTypeService to set
1475 public void setDocumentTypeService(
1476 final DocumentTypeService documentTypeService) {
1477 _documentTypeService = documentTypeService;
1481 * Get the userService.
1483 * @return the userService
1485 public UserService getUserService() {
1486 return _userService;
1490 * Set the userService.
1492 * @param userService
1493 * the userService to set
1495 public void setUserService(final UserService userService) {
1496 _userService = userService;
1502 * @see org.splat.service.StudyService#getComparableStudies()
1504 @Transactional(readOnly = true)
1505 public List<StudyFacadeDTO> getComparableStudies(final long userId) throws MismatchException {
1506 //retrieve the number of the "Analyze the results" step
1507 List<Step> allSteps = _projectSettings.getAllSteps();
1508 Step theAnalyzeStep = null;
1509 for(Step step : allSteps) {
1510 if(step.getKey().equals("postprocessing")) {
1511 theAnalyzeStep = step;
1514 if(theAnalyzeStep == null) { //TODO: throw some other exception
1515 throw new MismatchException("no step with key 'postprocessing' found." +
1516 "Probably, customization settings have been changed.");
1519 List<Publication> publications = _publicationDAO.getFilteredList("mydoc",
1520 Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber())));
1522 //split retrieved publications into groups by studies and scenarios
1523 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1524 Map<ProjectElement, List<Publication>> scenarioMap =
1525 new HashMap<ProjectElement, List<Publication>>();
1527 for(Publication publication : publications) {
1528 //filter out publications corresponding to a document of given step which is not a _result_ document
1529 if(!publication.value().getType().isResultOf(theAnalyzeStep)
1530 || !"srd".equals(publication.getSourceFile().getFormat())) {
1534 //check the study visibility to the user
1535 if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId))
1536 && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) {
1540 Study study = publication.getOwnerStudy();
1541 ProjectElement scenario = publication.getOwner();
1543 Hibernate.initialize(scenario);
1544 if (scenario instanceof HibernateProxy) {
1545 scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer()
1546 .getImplementation();
1549 if(!(scenario instanceof Scenario)) {
1550 throw new MismatchException(
1551 "publications from postprocessing step are supposed to have owner scenario");
1554 if(!studyMap.containsKey(study)) {
1555 studyMap.put(study, new ArrayList<ProjectElement>());
1558 if(!studyMap.get(study).contains(scenario)) {
1559 studyMap.get(study).add(scenario);
1562 if(!scenarioMap.containsKey(scenario)) {
1563 scenarioMap.put(scenario, new ArrayList<Publication>());
1565 scenarioMap.get(scenario).add(publication);
1568 //Create the result DTOs
1569 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1570 for(Study study : studyMap.keySet()) {
1572 StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1573 studyDTO.setName(study.getTitle());
1574 studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1575 result.add(studyDTO);
1577 for(ProjectElement scenario : studyMap.get(study)) {
1579 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1580 scenarioDTO.setName(scenario.getTitle());
1581 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1582 studyDTO.getScenarios().add(scenarioDTO);
1584 for(Publication publication : scenarioMap.get(scenario)) {
1586 DocumentDTO documentDTO = new DocumentDTO();
1587 documentDTO.setId(publication.getIndex());
1588 documentDTO.setTitle(publication.value().getTitle());
1590 scenarioDTO.getDocs().add(documentDTO);
1598 * Get the publicationDAO.
1599 * @return the publicationDAO
1601 public PublicationDAO getPublicationDAO() {
1602 return _publicationDAO;
1606 * Set the publicationDAO.
1607 * @param publicationDAO the publicationDAO to set
1609 public void setPublicationDAO(final PublicationDAO publicationDAO) {
1610 _publicationDAO = publicationDAO;
1614 * Get the repositoryService.
1615 * @return the repositoryService
1617 public RepositoryService getRepositoryService() {
1618 return _repositoryService;
1622 * Set the repositoryService.
1623 * @param repositoryService the repositoryService to set
1625 public void setRepositoryService(final RepositoryService repositoryService) {
1626 _repositoryService = repositoryService;
1630 * Get the documentDAO.
1631 * @return the documentDAO
1633 public DocumentDAO getDocumentDAO() {
1634 return _documentDAO;
1638 * Set the documentDAO.
1639 * @param documentDAO the documentDAO to set
1641 public void setDocumentDAO(final DocumentDAO documentDAO) {
1642 _documentDAO = documentDAO;
1646 * Get the descriptionAttributeDAO.
1647 * @return the descriptionAttributeDAO
1649 public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1650 return _descriptionAttributeDAO;
1654 * Set the descriptionAttributeDAO.
1655 * @param descriptionAttributeDAO the descriptionAttributeDAO to set
1657 public void setDescriptionAttributeDAO(
1658 final DescriptionAttributeDAO descriptionAttributeDAO) {
1659 _descriptionAttributeDAO = descriptionAttributeDAO;