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.Study.Properties;
58 import org.splat.dal.bo.som.ValidationCycle;
59 import org.splat.dal.bo.som.ValidationCycle.Actor;
60 import org.splat.dal.bo.som.ValidationCycleRelation;
61 import org.splat.dal.bo.som.ValidationStep;
62 import org.splat.dal.bo.som.Visibility;
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.IncompatibleDataException;
72 import org.splat.exception.InvalidParameterException;
73 import org.splat.kernel.InvalidPropertyException;
74 import org.splat.kernel.MismatchException;
75 import org.splat.kernel.MissedPropertyException;
76 import org.splat.kernel.MultiplyDefinedException;
77 import org.splat.log.AppLogger;
78 import org.splat.service.dto.DocToCompareDTO;
79 import org.splat.service.dto.DocumentDTO;
80 import org.splat.service.dto.StudyFacadeDTO;
81 import org.splat.service.technical.IndexService;
82 import org.splat.service.technical.ProjectSettingsService;
83 import org.splat.service.technical.ProjectSettingsService.Step;
84 import org.splat.service.technical.ProjectSettingsServiceImpl;
85 import org.splat.service.technical.RepositoryService;
86 import org.splat.som.Revision;
87 import org.springframework.transaction.annotation.Transactional;
89 import com.lowagie.text.Document;
90 import com.lowagie.text.DocumentException;
91 import com.lowagie.text.Rectangle;
92 import com.lowagie.text.pdf.DefaultFontMapper;
93 import com.lowagie.text.pdf.PdfContentByte;
94 import com.lowagie.text.pdf.PdfTemplate;
95 import com.lowagie.text.pdf.PdfWriter;
98 * This class defines all methods for creation, modification the study.
100 * @author Maria KRUCHININA
103 public class StudyServiceImpl implements StudyService {
106 * logger for the service.
108 public final static AppLogger LOG = AppLogger
109 .getLogger(StudyServiceImpl.class);
111 * "studyId" parameter name.
113 public final static String PARAM_STUDY_ID = "studyId";
116 * Injected index service.
118 private IndexService _indexService;
121 * Injected step service.
123 private StepService _stepService;
126 * Injected project service.
128 private ProjectSettingsService _projectSettings;
131 * Injected project element service.
133 private ProjectElementService _projectElementService;
136 * Injected study DAO.
138 private StudyDAO _studyDAO;
141 * Injected usedBy relations DAO.
143 private UsedByRelationDAO _usedByRelationDAO;
146 * Injected scenario DAO.
148 private ScenarioDAO _scenarioDAO;
151 * Injected validation cycle DAO.
153 private ValidationCycleDAO _validationCycleDAO;
156 * Injected IDBuilder DAO.
158 private IDBuilderDAO _iDBuilderDAO;
161 * Injected document type service.
163 private DocumentTypeService _documentTypeService;
166 * Injected user service.
168 private UserService _userService;
171 * Injected publication DAO.
173 private PublicationDAO _publicationDAO;
176 * Injected repository service.
178 private RepositoryService _repositoryService;
181 * Injected document DAO.
183 private DocumentDAO _documentDAO;
186 * Injected description attribute DAO.
188 private DescriptionAttributeDAO _descriptionAttributeDAO;
193 * @see org.splat.service.StudyService#selectStudy(long)
196 public Study selectStudy(final long index) {
197 Study result = getStudyDAO().get(index);
198 loadWorkflow(result);
205 * @see org.splat.service.StudyService#removeStudy(long)
208 public void removeStudy(final Long index) {
209 Study study = getStudyDAO().get(index);
210 Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
212 // Select all documents published in the study and study's scenarios.
213 DetachedCriteria query = DetachedCriteria.forClass(
214 Publication.class, "pub");
216 .createCriteria("pub.owner", "projelem",
218 .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
221 .or(Restrictions.eq("projelem.rid", index),
222 Restrictions.eq("study.rid", index)))
223 .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
225 if (LOG.isDebugEnabled()) {
226 LOG.debug("Find study documents: " + query.toString());
228 for (Publication pub : getPublicationDAO().getFilteredList(query)) {
229 docums.add(pub.value());
230 // Find also all previous versions of the document
231 for (org.splat.dal.bo.som.Document prev = pub.value()
232 .getPreviousVersion(); prev != null; prev = prev
233 .getPreviousVersion()) {
238 // Delete the study with its relations, scenarios and publications
239 getStudyDAO().delete(study);
241 // Remove all relations of study documents
242 for (org.splat.dal.bo.som.Document doc : docums) {
243 LOG.debug("Found doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
244 doc.getAllRelations().clear();
246 getDocumentDAO().flush();
248 // Remove all documents of the study
249 for (org.splat.dal.bo.som.Document doc : docums) {
250 LOG.debug("Remove doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
251 getDocumentDAO().delete(doc);
257 * Get study by its reference.
260 * the study reference
261 * @return found study or null
263 @Transactional(readOnly = true)
264 public Study selectStudy(final String refid) {
265 Study result = getStudyDAO().findByCriteria(
266 Restrictions.eq("sid", refid));
267 loadWorkflow(result);
274 * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
277 public Study createStudy(final Study.Properties sprop)
278 throws MissedPropertyException, InvalidPropertyException,
279 MultiplyDefinedException {
280 sprop.setReference(getProjectSettings().getReferencePattern());
281 Study study = new Study(sprop);
283 buildReference(study);
284 getStudyDAO().create(study);
286 // IndexService lucin = getIndex();
288 // } catch (IOException error) {
289 // LOG.error("Unable to index the study '" + study.getIndex()
290 // + "', reason:", error);
291 // // Continue and try to index later
299 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
302 public SimulationContext addProjectContext(final Study aStudy,
303 final SimulationContext.Properties cprop)
304 throws MissedPropertyException, InvalidPropertyException,
305 MultiplyDefinedException {
306 SimulationContext added = getStepService().addSimulationContext(
307 getProjectElementService().getFirstStep(aStudy), cprop);
315 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
318 public SimulationContext addProjectContext(final Study aStudy,
319 final SimulationContext context) {
320 SimulationContext added = getStepService().addSimulationContext(
321 getProjectElementService().getFirstStep(aStudy), context);
329 * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
332 public boolean addContributor(final Study aStudy, final User user) {
333 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
334 for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
335 User present = i.next();
336 if (present.equals(user)) {
340 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
342 aStudy.addRelation(new ContributorRelation(aStudy, user));
344 update(aStudy); // Else, useless to re-index the study
350 * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
351 * previously be approved.
355 * @return true if the move succeeded.
356 * @see #moveToPublic()
358 * @see Publication#approve(Date)
360 public boolean moveToReference(final Study aStudy) {
361 if (aStudy.getProgressState() != ProgressState.APPROVED) {
364 if (aStudy.getVisibility() != Visibility.PUBLIC) {
368 aStudy.setVisibility(Visibility.REFERENCE);
369 if (update(aStudy)) {
370 return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
378 * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
380 public boolean update(final Study aStudy, final Properties sprop)
381 throws InvalidPropertyException {
382 if (sprop.getTitle() != null) {
383 aStudy.setTitle(sprop.getTitle());
385 if (sprop.getSummary() != null) {
386 aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
389 // TODO: To be completed
390 return update(aStudy);
394 * Check if the document is published in the study.
400 * @return true if the document is published in the study
402 /* private boolean publishes(final Study aStudy, final Document doc) {
403 if (!aStudy.publishes(doc)) {
404 Scenario[] scene = aStudy.getScenarii();
405 for (int i = 0; i < scene.length; i++) {
406 if (scene[i].publishes(doc)) {
417 * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
420 public boolean removeContributor(final Study aStudy, final User... users) {
421 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
422 Boolean done = false;
423 for (int i = 0; i < users.length; i++) {
424 User user = users[i];
425 for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
426 User present = j.next();
427 if (!present.equals(user)) {
431 aStudy.removeRelation(ContributorRelation.class, user);
432 j.remove(); // Updates the contributor shortcut
446 * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
448 public boolean removeProjectContext(final Study aStudy,
449 final SimulationContext context) {
450 boolean done = getStepService().removeSimulationContext(
451 getProjectElementService().getFirstStep(aStudy), context);
459 * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
460 * org.splat.dal.bo.som.ValidationCycle.Properties)
463 public void setValidationCycle(final Study aStudyDTO,
464 final DocumentType type, final ValidationCycle.Properties vprop) {
465 Map<String, ValidationCycle> validactor = aStudyDTO
466 .getValidationCycles();
467 if (validactor == null) {
468 setShortCuts(aStudyDTO); // Initializes validactor and actor
471 Study aStudy = selectStudy(aStudyDTO.getIndex());
473 String cname = type.getName();
474 ValidationCycle cycle = validactor.get(cname);
476 if (cycle != null && cycle.isAssigned()) {
477 resetActors(cycle, vprop);
480 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
482 getValidationCycleDAO().create(cycle); // RKV
484 ValidationCycleRelation link = cycle.getContext();
485 aStudy.addRelation(link);
486 aStudyDTO.getAllRelations().add(link); // RKV
488 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
489 } catch (Exception error) {
490 LOG.error("Unable to re-index Knowledge Elements, reason:",
495 resetActorsShortCut(aStudyDTO);
496 update(aStudy); // Re-index the study, just in case
500 * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
501 * document of the study.
505 * @return true if the demotion succeeded.
507 public boolean demote(final Study aStudy) {
508 if (aStudy.getProgressState() == ProgressState.inCHECK) {
509 aStudy.setProgressState(ProgressState.inDRAFT);
510 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
511 aStudy.setProgressState(ProgressState.inWORK);
515 return update(aStudy);
521 * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
524 public int generateLocalIndex(final Study aStudy) {
525 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
526 return aStudy.getLastLocalIndex();
530 * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
531 * final result document of the study.
535 * @return true if the demotion succeeded.
538 public boolean promote(final Study aStudy) {
539 if (aStudy.getProgressState() == ProgressState.inWORK) {
540 aStudy.setProgressState(ProgressState.inDRAFT);
541 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
542 aStudy.setProgressState(ProgressState.inCHECK);
543 Revision myvers = new Revision(aStudy.getVersion());
544 if (myvers.isMinor()) {
545 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
548 } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
549 aStudy.setProgressState(ProgressState.APPROVED);
554 return update(aStudy);
558 * Moves this study from the Private to the Public area of the repository.
562 * @return true if the move succeeded.
566 public boolean moveToPublic(final Study aStudy) {
567 boolean isOk = false;
568 if (aStudy.getVisibility() == Visibility.PRIVATE) {
569 aStudy.setVisibility(Visibility.PUBLIC);
570 if (update(aStudy)) {
571 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
578 * Moves this study from the Public to the Private area of the repository.
582 * @return true if the move succeeded.
585 public boolean moveToPrivate(final Study aStudy) {
586 boolean isOk = false;
587 if (aStudy.getVisibility() == Visibility.PUBLIC) {
588 aStudy.setVisibility(Visibility.PRIVATE);
589 if (update(aStudy)) {
590 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
597 * Update a study in the database.
600 * the study to update
601 * @return true if the study is updated successfully
604 private boolean update(final Study aStudy) {
605 boolean isOk = false;
607 getStudyDAO().merge(aStudy); // Update of relational base
608 setShortCuts(aStudy); // RKV: initialize transient actors set
609 // RKV: getIndex().update(aStudy); // Update of Lucene index
611 } catch (Exception e) {
612 LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
618 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
622 * @return true if reference building is succeded
625 private boolean buildReference(final Study aStudy) {
626 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
627 IDBuilder tool = selectIDBuilder(aStudy.getDate());
629 tool = new IDBuilder(aStudy.getDate());
630 getIDBuilderDAO().create(tool);
632 aStudy.setReference(buildReference(tool, pattern, aStudy));
637 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
644 * the reference pattern
645 * @return true if reference building is succeded
648 public String buildReference(final IDBuilder aBuilder,
649 final String pattern, final Study study) {
650 char[] format = pattern.toCharArray();
651 char[] ref = new char[80]; // Better evaluate the length of the generated string
652 int next = aBuilder.getBase() + 1;
655 for (int i = 0; i < format.length; i++) {
657 // Insertion of attribute values
658 if (format[i] == '%') {
661 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
663 while (format[i] == 'y') {
665 if (i == format.length) {
669 SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
670 String year = tostring.format(study.getDate());
671 year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
672 for (int j = 0; j < year.length(); j++) {
673 ref[count] = year.charAt(j);
676 i -= 1; // Back to the last 'y' character
677 } else if (format[i] == '0') { // Insertion of the index
679 while (format[i] == '0') {
681 if (i == format.length) {
685 DecimalFormat tostring = new DecimalFormat(pattern
687 String number = tostring.format(next);
688 for (int j = 0; j < number.length(); j++) {
689 ref[count] = number.charAt(j);
692 i -= 1; // Back to the last '0' character
694 // Keep the character
696 ref[count] = format[i];
700 // Incrementation of the number of study
701 aBuilder.setBase(next);
702 getIDBuilderDAO().update(aBuilder);
703 return String.copyValueOf(ref, 0, count);
707 * Find an id builder by date.
711 * @return found id builder
713 private IDBuilder selectIDBuilder(final Date date) {
714 Calendar aDate = Calendar.getInstance();
716 return getIDBuilderDAO().findByCriteria(
717 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
721 * Fill transient collection ModifiableActors of the study.
726 private void resetActorsShortCut(final Study aStudy) {
727 getModifiableActors(aStudy).clear();
728 // Get all actors involved in validation cycles
729 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
730 .values().iterator(); i.hasNext();) {
731 ValidationCycle cycle = i.next();
732 User[] user = cycle.getAllActors();
733 for (int j = 0; j < user.length; j++) {
734 getModifiableActors(aStudy).add(user[j]);
737 // Get all other actors
738 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
740 Relation link = i.next();
741 Class<?> kindof = link.getClass().getSuperclass();
742 if (!kindof.equals(ActorRelation.class)) {
745 getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
750 * Update lucene index for the study knowledge elements.
754 * @return true if reindexing succeeded
756 private boolean updateKnowledgeElementsIndex(final Study aStudy) {
757 // boolean isOk = false;
759 // IndexService lucin = getIndex();
761 // for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
763 // Scenario scene = i.next();
764 // for (Iterator<KnowledgeElement> j = scene
765 // .getAllKnowledgeElements().iterator(); j.hasNext();) {
766 // KnowledgeElement kelm = j.next();
767 // lucin.update(kelm);
771 // } catch (Exception error) {
772 // LOG.error("Unable to re-index Knowledge Elements, reason:",
780 * Get lucene index service. Create a lucene index if it does not exist.
782 * @return index service
783 * @throws IOException
784 * if error occurs during lucene index creation
786 private IndexService getIndex() throws IOException {
787 IndexService lucin = getIndexService();
788 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
789 .getRepositoryIndexDirectory()))) {
790 IndexWriter.unlock(FSDirectory.open(getRepositoryService()
791 .getRepositoryIndexDirectory()));
793 if (!lucin.exists()) {
794 lucin.create(); // Happens when re-indexing all studies
800 * Create a new validation cycle for documents of the given study.
805 * the cycle description
806 * @return the new validation cycle
808 protected ValidationCycle createValidationCycle(
810 final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
811 Actor[] actype = cycle.getActorTypes();
812 User.Properties uprop = new User.Properties();
814 ValidationCycle aValidationCycle = new ValidationCycle();
815 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
816 cycle.getName())); // Null in case of default validation cycle
817 // context = new ValidationCycleRelation(from, vprop);
818 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
819 for (int i = 0; i < actype.length; i++) {
821 if (actype[i] != null) {
823 if (actype[i] == Actor.manager) {
824 actor = from.getAuthor();
825 } else if (actype[i] == Actor.Nx1) {
826 List<User> manager = getUserService().selectUsersWhere(
827 uprop.setOrganizationName("Nx1"));
828 if (manager.size() == 1) {
829 actor = manager.get(0);
831 } else if (actype[i] == Actor.Nx2) {
832 List<User> manager = getUserService().selectUsersWhere(
833 uprop.setOrganizationName("Nx2"));
834 if (manager.size() == 1) {
835 actor = manager.get(0);
837 } else { /* Actor.customer */
838 actor = from.getAuthor();
839 // TODO: Get the customer of the study, if exists
841 } catch (Exception e) { // Should not happen
846 aValidationCycle.setReviewer(actor);
848 aValidationCycle.setApprover(actor);
850 aValidationCycle.setSignatory(actor);
853 return aValidationCycle;
857 * Remove a validation step from the validation cycle.
859 * @param aValidationCycle
860 * the validation cycle
862 * the validation step to remove
865 protected void remove(final ValidationCycle aValidationCycle,
866 final ValidationStep step) {
867 if (step == ValidationStep.REVIEW) {
868 aValidationCycle.setReviewer(null);
869 } else if (step == ValidationStep.APPROVAL) {
870 aValidationCycle.setApprover(null);
871 } else if (step == ValidationStep.ACCEPTANCE
872 || step == ValidationStep.REFUSAL) {
873 aValidationCycle.setSignatory(null);
875 if (aValidationCycle.isSaved()) {
876 getValidationCycleDAO().update(aValidationCycle);
881 * Reset actors for the validation cycle.
883 * @param aValidationCycle
884 * the validation cycle to update
886 * new validation cycle properties containing new actors
889 public void resetActors(final ValidationCycle aValidationCycle,
890 final ValidationCycle.Properties vprop) {
891 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
892 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
893 aValidationCycle.setApprover(vprop.getApprover()); // May be null
894 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
895 if (aValidationCycle.isSaved()) {
896 getValidationCycleDAO().merge(aValidationCycle);
901 * Set actor for the given validation cycle and validation step.
903 * @param aValidationCycle
904 * the validation cycle
906 * the validation step
911 protected void setActor(final ValidationCycle aValidationCycle,
912 final ValidationStep step, final User actor) {
913 if (step == ValidationStep.PROMOTION) {
914 aValidationCycle.setPublisher(actor);
915 } else if (step == ValidationStep.REVIEW) {
916 aValidationCycle.setReviewer(actor);
917 } else if (step == ValidationStep.APPROVAL) {
918 aValidationCycle.setApprover(actor);
919 } else if (step == ValidationStep.ACCEPTANCE
920 || step == ValidationStep.REFUSAL) {
921 aValidationCycle.setSignatory(actor);
923 if (aValidationCycle.isSaved()) {
924 getValidationCycleDAO().update(aValidationCycle);
929 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
933 * @return the actors of this study
934 * @see #hasActor(User)
936 public Set<User> getActors(final Study aStudy) {
937 if (aStudy.getActor() == null) {
938 setShortCuts(aStudy);
940 return Collections.unmodifiableSet(aStudy.getActor());
944 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
948 * @return the modifiable set of actors of this study
949 * @see #hasActor(User)
951 public Set<User> getModifiableActors(final Study aStudy) {
952 if (aStudy.getActor() == null) {
953 setShortCuts(aStudy);
955 return aStudy.getActor();
959 * Returns unmodifiable initialized transient list of contributors of this study.
963 * @return the unmodifiable not null transient list of contributors of this study
965 public List<User> getContributors(final Study aStudy) {
966 if (aStudy.getContributor() == null) {
967 setShortCuts(aStudy);
969 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
973 * Returns modifiable initialized transient list of contributors of this study.
977 * @return the modifiable not null transient list of contributors of this study
979 public List<User> getModifiableContributors(final Study aStudy) {
980 if (aStudy.getContributor() == null) {
981 setShortCuts(aStudy);
983 return aStudy.getContributor(); // May be empty
987 * Returns the validation cycle of the given document type.
992 * the document type being subject of validation
993 * @return the validation cycle of the document, or null if not defined.
995 public ValidationCycle getValidationCycleOf(final Study aStudy,
996 final DocumentType type) {
997 if (aStudy.getValidationCycles() == null
998 || aStudy.getValidationCycles().isEmpty()) {
999 setShortCuts(aStudy);
1001 ValidationCycle result = aStudy.getValidationCycles().get(
1003 if (result == null) {
1004 if (type.isStepResult()) {
1005 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
1007 if (result == null) {
1008 result = aStudy.getValidationCycles().get("built-in");
1015 * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
1020 * the user to look for
1021 * @return true if the given user is actor of this study.
1024 public boolean hasActor(final Study aStudy, final User user) {
1028 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
1029 User involved = i.next();
1030 if (involved.equals(user)) {
1038 * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1043 * the user to look for
1044 * @return true if the given user is actor of this study.
1045 * @see #getContributors()
1047 public boolean isStaffedBy(final Study aStudy, final User user) {
1051 if (aStudy == null) {
1054 if (aStudy.getAuthor() == null) {
1057 if (aStudy.getAuthor().equals(user)) {
1060 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1061 if (i.next().equals(user)) {
1069 * Initialize shortcuts of the study as its transient collections.
1074 public void loadWorkflow(final Study aStudy) {
1075 setShortCuts(aStudy);
1079 * Initialize shortcuts of the study as its transient collections.
1084 public void setShortCuts(final Study aStudy) {
1085 aStudy.getContributor().clear();
1086 aStudy.getValidationCycles().clear();
1087 aStudy.getActor().clear();
1089 // Get the contributors
1090 for (Iterator<Relation> i = aStudy.getRelations(
1091 ContributorRelation.class).iterator(); i.hasNext();) {
1092 ContributorRelation link = (ContributorRelation) i.next();
1093 aStudy.getContributor().add(link.getTo());
1095 // Get the validation cycles specific to this study
1096 for (Iterator<Relation> i = aStudy.getRelations(
1097 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1098 ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1099 aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1100 link.getTo()); // The associated document type is necessarily not null in this
1103 // Get the validation cycles coming from the configured workflow and not overridden in this study
1104 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1105 .getAllValidationCycles().iterator(); i.hasNext();) {
1106 ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1108 String type = cycle.getName();
1109 if (!aStudy.getValidationCycles().containsKey(type)) {
1110 aStudy.getValidationCycles().put(type,
1111 createValidationCycle(aStudy, cycle));
1114 // Get all corresponding actors
1115 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1116 .values().iterator(); i.hasNext();) {
1117 ValidationCycle cycle = i.next();
1118 User[] user = cycle.getAllActors();
1119 for (int j = 0; j < user.length; j++) {
1120 aStudy.getActor().add(user[j]);
1123 // Get all other actors
1124 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1126 Relation link = i.next();
1127 Class<?> kindof = link.getClass().getSuperclass();
1128 if (!kindof.equals(ActorRelation.class)) {
1131 aStudy.getActor().add(((ActorRelation) link).getTo());
1139 * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
1143 public void markStudyAsReference(final Study aStudy) {
1145 aStudy.setMarkreference(1);
1146 aStudy.setProgressState(ProgressState.TEMPLATE);
1147 getStudyDAO().merge(aStudy);
1154 * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
1158 public void removeStudyAsReference(final Study aStudy) {
1160 aStudy.setMarkreference(0);
1161 aStudy.setProgressState(ProgressState.APPROVED);
1162 getStudyDAO().merge(aStudy);
1168 * @see org.splat.service.StudyService#getDescription(java.lang.Long)
1171 @Transactional(readOnly = true)
1172 public String getDescription(final Long studyId)
1173 throws InvalidParameterException {
1174 if (studyId == null) {
1175 throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1177 Study study = _studyDAO.get(studyId);
1178 if (study == null) {
1179 throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString());
1181 return study.getDescription();
1187 * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
1191 public void setDescription(final Long studyId, final String descriptionText)
1192 throws InvalidParameterException {
1193 if (studyId == null) {
1194 throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1196 Study study = _studyDAO.get(studyId);
1197 if (study == null) {
1198 throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString());
1200 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1206 * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
1210 public boolean removeDescription(final Long studyId)
1211 throws InvalidParameterException {
1212 if (studyId == null) {
1213 throw new InvalidParameterException(PARAM_STUDY_ID, String
1216 Study study = _studyDAO.get(studyId);
1217 if (study == null) {
1218 throw new InvalidParameterException(PARAM_STUDY_ID, String
1221 return study.removeAttribute(study
1222 .getAttribute(DescriptionAttribute.class));
1229 * @see org.splat.service.StudyService#compare(java.util.List)
1232 public String compare(final List<DocToCompareDTO> docsList,
1233 final String userName) throws IncompatibleDataException {
1235 String axis1Name = "";
1236 String axis2Name = "";
1237 String chartTitle = "";
1238 String resultPath = "";
1240 XYSeriesCollection dataset = new XYSeriesCollection();
1242 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1244 for (; docListIter.hasNext();) {
1246 DocToCompareDTO docDTO = docListIter.next();
1247 String pathToFile = docDTO.getPathToFile();
1248 File compDocFile = new File(pathToFile);
1250 resultPath = pathToFile.substring(0, pathToFile.indexOf("vault"))
1251 + "downloads" + File.separator + userName + File.separator
1252 + "ComparisonResult.pdf";
1254 XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle());
1256 // read the file and get points information.
1258 Scanner input = new Scanner(compDocFile);
1260 //get the title of the chart.
1261 if (input.hasNext()) {
1262 chartTitle = input.nextLine();
1265 // get the name of the axis.
1266 if (input.hasNext()) {
1267 String[] tokens = input.nextLine().split(",");
1269 if (tokens.length < 2) {
1270 throw new IncompatibleDataException(
1271 MessageKeyEnum.IDT_000001.toString());
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());
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());
1291 // Get the XY points series.
1292 while (input.hasNext()) {
1294 String currentString = input.nextLine();
1296 if (!("".equals(currentString))) {
1297 String[] tokens = currentString.split(" ");
1298 series.add(Double.valueOf(tokens[0]), Double
1299 .valueOf(tokens[1]));
1304 dataset.addSeries(series);
1306 } catch (FileNotFoundException e) {
1307 if (LOG.isDebugEnabled()) {
1308 LOG.debug("Sorry, the file is not found.");
1314 JFreeChart chart = ChartFactory.createXYLineChart(
1315 chartTitle, // Title
1316 axis1Name, // x-axis Label
1317 axis2Name, // y-axis Label
1319 PlotOrientation.VERTICAL, // Plot Orientation
1320 true, // Show Legend
1321 true, // Use tooltips
1322 false // Configure chart to generate URLs?
1325 // export to PDF - file.
1328 Rectangle pagesize = new Rectangle(x, y);
1329 Document document = new Document(pagesize, 50, 50, 50, 50);
1332 File resFile = new File(resultPath);
1333 File resFolder = new File(resultPath.substring(0, resultPath
1334 .lastIndexOf(File.separator)));
1336 writer = PdfWriter.getInstance(document, new FileOutputStream(
1340 PdfContentByte cb = writer.getDirectContent();
1341 PdfTemplate tp = cb.createTemplate(x, y);
1342 Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1343 chart.draw(g2, new java.awt.Rectangle(x, y));
1345 cb.addTemplate(tp, 0, 0);
1348 } catch (FileNotFoundException e) {
1349 if (LOG.isDebugEnabled()) {
1350 LOG.debug("Sorry, the file is not found.");
1352 } catch (DocumentException e) {
1353 if (LOG.isDebugEnabled()) {
1354 LOG.debug("Sorry, the DocumentException is thrown.");
1362 * Get project settings.
1364 * @return Project settings service
1366 private ProjectSettingsService getProjectSettings() {
1367 return _projectSettings;
1371 * Set project settings service.
1373 * @param projectSettingsService
1374 * project settings service
1376 public void setProjectSettings(
1377 final ProjectSettingsService projectSettingsService) {
1378 _projectSettings = projectSettingsService;
1382 * Get the projectElementService.
1384 * @return the projectElementService
1386 public ProjectElementService getProjectElementService() {
1387 return _projectElementService;
1391 * Set the projectElementService.
1393 * @param projectElementService
1394 * the projectElementService to set
1396 public void setProjectElementService(
1397 final ProjectElementService projectElementService) {
1398 _projectElementService = projectElementService;
1402 * Get the stepService.
1404 * @return the stepService
1406 public StepService getStepService() {
1407 return _stepService;
1411 * Set the stepService.
1413 * @param stepService
1414 * the stepService to set
1416 public void setStepService(final StepService stepService) {
1417 _stepService = stepService;
1421 * Get the indexService.
1423 * @return the indexService
1425 public IndexService getIndexService() {
1426 return _indexService;
1430 * Set the indexService.
1432 * @param indexService
1433 * the indexService to set
1435 public void setIndexService(final IndexService indexService) {
1436 _indexService = indexService;
1442 * @return the studyDAO
1444 public StudyDAO getStudyDAO() {
1452 * the studyDAO to set
1454 public void setStudyDAO(final StudyDAO studyDAO) {
1455 _studyDAO = studyDAO;
1459 * Get the iDBuilderDAO.
1461 * @return the iDBuilderDAO
1463 public IDBuilderDAO getIDBuilderDAO() {
1464 return _iDBuilderDAO;
1468 * Set the iDBuilderDAO.
1471 * the iDBuilderDAO to set
1473 public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1474 _iDBuilderDAO = builderDAO;
1478 * Get the scenarioDAO.
1480 * @return the scenarioDAO
1482 public ScenarioDAO getScenarioDAO() {
1483 return _scenarioDAO;
1487 * Set the scenarioDAO.
1489 * @param scenarioDAO
1490 * the scenarioDAO to set
1492 public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1493 _scenarioDAO = scenarioDAO;
1497 * Get the validationCycleDAO.
1499 * @return the validationCycleDAO
1501 public ValidationCycleDAO getValidationCycleDAO() {
1502 return _validationCycleDAO;
1506 * Set the validationCycleDAO.
1508 * @param validationCycleDAO
1509 * the validationCycleDAO to set
1511 public void setValidationCycleDAO(
1512 final ValidationCycleDAO validationCycleDAO) {
1513 _validationCycleDAO = validationCycleDAO;
1517 * Get the documentTypeService.
1519 * @return the documentTypeService
1521 public DocumentTypeService getDocumentTypeService() {
1522 return _documentTypeService;
1526 * Set the documentTypeService.
1528 * @param documentTypeService
1529 * the documentTypeService to set
1531 public void setDocumentTypeService(
1532 final DocumentTypeService documentTypeService) {
1533 _documentTypeService = documentTypeService;
1537 * Get the userService.
1539 * @return the userService
1541 public UserService getUserService() {
1542 return _userService;
1546 * Set the userService.
1548 * @param userService
1549 * the userService to set
1551 public void setUserService(final UserService userService) {
1552 _userService = userService;
1558 * @see org.splat.service.StudyService#getComparableStudies()
1560 @Transactional(readOnly = true)
1561 public List<StudyFacadeDTO> getComparableStudies(final long userId) throws MismatchException {
1562 //retrieve the number of the "Analyze the results" step
1563 List<Step> allSteps = _projectSettings.getAllSteps();
1564 Step theAnalyzeStep = null;
1565 for(Step step : allSteps) {
1566 if(step.getKey().equals("postprocessing")) {
1567 theAnalyzeStep = step;
1570 if(theAnalyzeStep == null) { //TODO: throw some other exception
1571 throw new MismatchException("no step with key 'postprocessing' found." +
1572 "Probably, customization settings have been changed.");
1575 List<Publication> publications = _publicationDAO.getFilteredList("mydoc",
1576 Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber())));
1578 //split retrieved publications into groups by studies and scenarios
1579 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1580 Map<ProjectElement, List<Publication>> scenarioMap =
1581 new HashMap<ProjectElement, List<Publication>>();
1583 for(Publication publication : publications) {
1584 //filter out publications corresponding to a document of given step which is not a _result_ document
1585 if(!publication.value().getType().isResultOf(theAnalyzeStep)
1586 || !"srd".equals(publication.getSourceFile().getFormat())) {
1590 //check the study visibility to the user
1591 if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId))
1592 && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) {
1596 Study study = publication.getOwnerStudy();
1597 ProjectElement scenario = publication.getOwner();
1599 Hibernate.initialize(scenario);
1600 if (scenario instanceof HibernateProxy) {
1601 scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer()
1602 .getImplementation();
1605 if(!(scenario instanceof Scenario)) {
1606 throw new MismatchException(
1607 "publications from postprocessing step are supposed to have owner scenario");
1610 if(!studyMap.containsKey(study)) {
1611 studyMap.put(study, new ArrayList<ProjectElement>());
1614 if(!studyMap.get(study).contains(scenario)) {
1615 studyMap.get(study).add(scenario);
1618 if(!scenarioMap.containsKey(scenario)) {
1619 scenarioMap.put(scenario, new ArrayList<Publication>());
1621 scenarioMap.get(scenario).add(publication);
1624 //Create the result DTOs
1625 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1626 for(Study study : studyMap.keySet()) {
1628 StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1629 studyDTO.setName(study.getTitle());
1630 studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1631 result.add(studyDTO);
1633 for(ProjectElement scenario : studyMap.get(study)) {
1635 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1636 scenarioDTO.setName(scenario.getTitle());
1637 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1638 studyDTO.getScenarios().add(scenarioDTO);
1640 for(Publication publication : scenarioMap.get(scenario)) {
1642 DocumentDTO documentDTO = new DocumentDTO();
1643 documentDTO.setId(publication.getIndex());
1644 documentDTO.setTitle(publication.value().getTitle());
1646 scenarioDTO.getDocs().add(documentDTO);
1654 * Get the publicationDAO.
1656 * @return the publicationDAO
1658 public PublicationDAO getPublicationDAO() {
1659 return _publicationDAO;
1663 * Set the publicationDAO.
1665 * @param publicationDAO
1666 * the publicationDAO to set
1668 public void setPublicationDAO(final PublicationDAO publicationDAO) {
1669 _publicationDAO = publicationDAO;
1673 * Get the repositoryService.
1675 * @return the repositoryService
1677 public RepositoryService getRepositoryService() {
1678 return _repositoryService;
1682 * Set the repositoryService.
1684 * @param repositoryService
1685 * the repositoryService to set
1687 public void setRepositoryService(final RepositoryService repositoryService) {
1688 _repositoryService = repositoryService;
1692 * Get the documentDAO.
1694 * @return the documentDAO
1696 public DocumentDAO getDocumentDAO() {
1697 return _documentDAO;
1701 * Set the documentDAO.
1703 * @param documentDAO
1704 * the documentDAO to set
1706 public void setDocumentDAO(final DocumentDAO documentDAO) {
1707 _documentDAO = documentDAO;
1711 * Get the descriptionAttributeDAO.
1713 * @return the descriptionAttributeDAO
1715 public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1716 return _descriptionAttributeDAO;
1720 * Set the descriptionAttributeDAO.
1722 * @param descriptionAttributeDAO
1723 * the descriptionAttributeDAO to set
1725 public void setDescriptionAttributeDAO(
1726 final DescriptionAttributeDAO descriptionAttributeDAO) {
1727 _descriptionAttributeDAO = descriptionAttributeDAO;
1731 * Get the usedByRelationDAO.
1733 * @return the usedByRelationDAO
1735 public UsedByRelationDAO getUsedByRelationDAO() {
1736 return _usedByRelationDAO;
1740 * Set the usedByRelationDAO.
1742 * @param usedByRelationDAO
1743 * the usedByRelationDAO to set
1745 public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
1746 _usedByRelationDAO = usedByRelationDAO;