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.ReaderRelation;
55 import org.splat.dal.bo.som.Scenario;
56 import org.splat.dal.bo.som.SimulationContext;
57 import org.splat.dal.bo.som.Study;
58 import org.splat.dal.bo.som.ValidationCycle;
59 import org.splat.dal.bo.som.ValidationCycleRelation;
60 import org.splat.dal.bo.som.ValidationStep;
61 import org.splat.dal.bo.som.Visibility;
62 import org.splat.dal.bo.som.Study.Properties;
63 import org.splat.dal.bo.som.ValidationCycle.Actor;
64 import org.splat.dal.dao.som.DescriptionAttributeDAO;
65 import org.splat.dal.dao.som.DocumentDAO;
66 import org.splat.dal.dao.som.IDBuilderDAO;
67 import org.splat.dal.dao.som.PublicationDAO;
68 import org.splat.dal.dao.som.ScenarioDAO;
69 import org.splat.dal.dao.som.StudyDAO;
70 import org.splat.dal.dao.som.UsedByRelationDAO;
71 import org.splat.dal.dao.som.ValidationCycleDAO;
72 import org.splat.exception.BusinessException;
73 import org.splat.exception.IncompatibleDataException;
74 import org.splat.exception.InvalidParameterException;
75 import org.splat.kernel.InvalidPropertyException;
76 import org.splat.kernel.MismatchException;
77 import org.splat.kernel.MissedPropertyException;
78 import org.splat.kernel.MultiplyDefinedException;
79 import org.splat.log.AppLogger;
80 import org.splat.service.dto.DocToCompareDTO;
81 import org.splat.service.dto.DocumentDTO;
82 import org.splat.service.dto.StudyFacadeDTO;
83 import org.splat.service.dto.UserDTO;
84 import org.splat.service.technical.IndexService;
85 import org.splat.service.technical.ProjectSettingsService;
86 import org.splat.service.technical.ProjectSettingsServiceImpl;
87 import org.splat.service.technical.RepositoryService;
88 import org.splat.service.technical.ProjectSettingsService.Step;
89 import org.splat.som.Revision;
90 import org.splat.util.BeanHelper;
91 import org.springframework.transaction.annotation.Transactional;
93 import com.lowagie.text.Document;
94 import com.lowagie.text.DocumentException;
95 import com.lowagie.text.Rectangle;
96 import com.lowagie.text.pdf.DefaultFontMapper;
97 import com.lowagie.text.pdf.PdfContentByte;
98 import com.lowagie.text.pdf.PdfTemplate;
99 import com.lowagie.text.pdf.PdfWriter;
102 * This class defines all methods for creation, modification the study.
104 * @author Maria KRUCHININA
107 public class StudyServiceImpl implements StudyService {
110 * logger for the service.
112 public final static AppLogger LOG = AppLogger
113 .getLogger(StudyServiceImpl.class);
115 * "studyId" parameter name.
117 public final static String PARAM_STUDY_ID = "studyId";
120 * Injected index service.
122 private IndexService _indexService;
125 * Injected step service.
127 private StepService _stepService;
130 * Injected project service.
132 private ProjectSettingsService _projectSettings;
135 * Injected project element service.
137 private ProjectElementService _projectElementService;
140 * Injected study DAO.
142 private StudyDAO _studyDAO;
145 * Injected usedBy relations DAO.
147 private UsedByRelationDAO _usedByRelationDAO;
150 * Injected scenario DAO.
152 private ScenarioDAO _scenarioDAO;
155 * Injected validation cycle DAO.
157 private ValidationCycleDAO _validationCycleDAO;
160 * Injected IDBuilder DAO.
162 private IDBuilderDAO _iDBuilderDAO;
165 * Injected document type service.
167 private DocumentTypeService _documentTypeService;
170 * Injected user service.
172 private UserService _userService;
175 * Injected publication DAO.
177 private PublicationDAO _publicationDAO;
180 * Injected repository service.
182 private RepositoryService _repositoryService;
185 * Injected document DAO.
187 private DocumentDAO _documentDAO;
190 * Injected description attribute DAO.
192 private DescriptionAttributeDAO _descriptionAttributeDAO;
197 * @see org.splat.service.StudyService#selectStudy(long)
200 public Study selectStudy(final long index) {
201 Study result = getStudyDAO().get(index);
202 if (result != null) {
203 loadWorkflow(result);
211 * @see org.splat.service.StudyService#removeStudy(long)
214 public void removeStudy(final Long index) {
215 Study study = getStudyDAO().get(index);
216 Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
218 // Select all documents published in the study and study's scenarios.
219 DetachedCriteria query = DetachedCriteria.forClass(
220 Publication.class, "pub");
222 .createCriteria("pub.owner", "projelem",
224 .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
227 .or(Restrictions.eq("projelem.rid", index),
228 Restrictions.eq("study.rid", index)))
229 .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
231 if (LOG.isDebugEnabled()) {
232 LOG.debug("Find study documents: " + query.toString());
234 for (Publication pub : getPublicationDAO().getFilteredList(query)) {
235 docums.add(pub.value());
236 // Find also all previous versions of the document
237 for (org.splat.dal.bo.som.Document prev = pub.value()
238 .getPreviousVersion(); prev != null; prev = prev
239 .getPreviousVersion()) {
244 // Delete the study with its relations, scenarios and publications
245 getStudyDAO().delete(study);
247 // Remove all relations of study documents
248 for (org.splat.dal.bo.som.Document doc : docums) {
249 LOG.debug("Found doc: " + doc.getTitle() + " ["
250 + doc.getReference() + "]" + " [" + doc.getRid() + "]");
251 doc.getAllRelations().clear();
253 getDocumentDAO().flush();
255 // Remove all documents of the study
256 for (org.splat.dal.bo.som.Document doc : docums) {
257 LOG.debug("Remove doc: " + doc.getTitle() + " ["
258 + doc.getReference() + "]" + " [" + doc.getRid() + "]");
259 getDocumentDAO().delete(doc);
265 * Get study by its reference.
268 * the study reference
269 * @return found study or null
271 @Transactional(readOnly = true)
272 public Study selectStudy(final String refid) {
273 Study result = getStudyDAO().findByCriteria(
274 Restrictions.eq("sid", refid));
275 loadWorkflow(result);
282 * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
285 public Study createStudy(final Study.Properties sprop)
286 throws MissedPropertyException, InvalidPropertyException,
287 MultiplyDefinedException {
288 sprop.setReference(getProjectSettings().getReferencePattern());
289 Study study = new Study(sprop);
291 buildReference(study);
292 getStudyDAO().create(study);
294 // IndexService lucin = getIndex();
296 // } catch (IOException error) {
297 // LOG.error("Unable to index the study '" + study.getIndex()
298 // + "', reason:", error);
299 // // Continue and try to index later
307 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
310 public SimulationContext addProjectContext(final Study aStudy,
311 final SimulationContext.Properties cprop)
312 throws MissedPropertyException, InvalidPropertyException,
313 MultiplyDefinedException {
314 SimulationContext added = getStepService().addSimulationContext(
315 getProjectElementService().getFirstStep(aStudy), cprop);
323 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
326 public SimulationContext addProjectContext(final Study aStudy,
327 final SimulationContext context) {
328 SimulationContext added = getStepService().addSimulationContext(
329 getProjectElementService().getFirstStep(aStudy), context);
337 * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
340 public boolean addContributor(final Study aStudy, final User user) {
341 List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
343 if(contributors.contains(user)) {
347 //Remove user from readers
349 List<UserDTO> readers = getReaders(aStudy.getIndex());
350 for(UserDTO reader : readers) {
351 if(reader.getIndex() == user.getIndex()) {
352 //user must be the actual user in the relationship object in the aStudy object for this to work
353 aStudy.removeRelation(ReaderRelation.class, user);
356 } catch(InvalidParameterException e) {
357 LOG.error(e.getMessage(), e);
360 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
362 aStudy.addRelation(new ContributorRelation(aStudy, user));
364 update(aStudy); // Else, useless to re-index the study
370 * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
371 * previously be approved.
375 * @return true if the move succeeded.
376 * @see #moveToPublic()
378 * @see Publication#approve(Date)
381 public boolean moveToReference(final Study aStudy) {
382 if (aStudy.getProgressState() != ProgressState.APPROVED) {
385 if (aStudy.getVisibility() != Visibility.PUBLIC) {
389 aStudy.setVisibility(Visibility.REFERENCE);
390 if (update(aStudy)) {
391 return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
399 * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
402 public boolean update(final Study aStudy, final Properties sprop)
403 throws InvalidPropertyException {
404 if (sprop.getTitle() != null) {
405 aStudy.setTitle(sprop.getTitle());
407 if (sprop.getSummary() != null) {
408 aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
411 // TODO: To be completed
412 return update(aStudy);
416 * Check if the document is published in the study.
422 * @return true if the document is published in the study
425 * private boolean publishes(final Study aStudy, final Document doc) { if (!aStudy.publishes(doc)) { Scenario[] scene =
426 * aStudy.getScenarii(); for (int i = 0; i < scene.length; i++) { if (scene[i].publishes(doc)) { return true; } } } return false; }
431 * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
434 public boolean removeContributor(final Study aStudy, final User... users) {
435 List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
436 Boolean done = false;
437 for(User user : users) {
438 if(contributors.contains(user)) {
439 aStudy.removeRelation(ContributorRelation.class, user);
440 contributors.remove(user);
453 * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
456 public boolean removeProjectContext(final Study aStudy,
457 final SimulationContext context) {
458 boolean done = getStepService().removeSimulationContext(
459 getProjectElementService().getFirstStep(aStudy), context);
467 * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
468 * org.splat.dal.bo.som.ValidationCycle.Properties)
471 public void setValidationCycle(final Study aStudyDTO,
472 final DocumentType type, final ValidationCycle.Properties vprop) {
473 Map<String, ValidationCycle> validactor = aStudyDTO
474 .getValidationCycles();
475 if (validactor == null) {
476 setShortCuts(aStudyDTO); // Initializes validactor and actor
479 Study aStudy = selectStudy(aStudyDTO.getIndex());
481 String cname = type.getName();
482 ValidationCycle cycle = validactor.get(cname);
484 if (cycle != null && cycle.isAssigned()) {
485 resetActors(cycle, vprop);
488 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
490 getValidationCycleDAO().create(cycle); // RKV
492 ValidationCycleRelation link = cycle.getContext();
493 aStudy.addRelation(link);
494 aStudyDTO.getAllRelations().add(link); // RKV
496 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
497 } catch (BusinessException error) {
498 LOG.error("Unable to create validation cycle, reason:", error);
502 resetActorsShortCut(aStudyDTO);
503 update(aStudy); // Re-index the study, just in case
507 * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
508 * document of the study.
512 * @return true if the demotion succeeded.
515 public boolean demote(final Study aStudy) {
516 if (aStudy.getProgressState() == ProgressState.inCHECK) {
517 aStudy.setProgressState(ProgressState.inDRAFT);
518 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
519 aStudy.setProgressState(ProgressState.inWORK);
523 return update(aStudy);
529 * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
532 public int generateLocalIndex(final Study aStudy) {
533 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
534 return aStudy.getLastLocalIndex();
538 * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
539 * final result document of the study.
543 * @return true if the demotion succeeded.
546 public boolean promote(final Study aStudy) {
547 if (aStudy.getProgressState() == ProgressState.inWORK) {
548 aStudy.setProgressState(ProgressState.inDRAFT);
549 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
550 aStudy.setProgressState(ProgressState.inCHECK);
551 Revision myvers = new Revision(aStudy.getVersion());
552 if (myvers.isMinor()) {
553 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
556 } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
557 aStudy.setProgressState(ProgressState.APPROVED);
562 return update(aStudy);
566 * Moves this study from the Private to the Public area of the repository.
570 * @return true if the move succeeded.
574 public boolean moveToPublic(final Study aStudy) {
575 boolean isOk = false;
576 if (aStudy.getVisibility() == Visibility.PRIVATE) {
577 aStudy.setVisibility(Visibility.PUBLIC);
578 if (update(aStudy)) {
579 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
586 * Moves this study from the Public to the Private area of the repository.
590 * @return true if the move succeeded.
593 public boolean moveToPrivate(final Study aStudy) {
594 boolean isOk = false;
595 if (aStudy.getVisibility() == Visibility.PUBLIC) {
596 aStudy.setVisibility(Visibility.PRIVATE);
597 if (update(aStudy)) {
598 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
605 * Update a study in the database.
608 * the study to update
609 * @return true if the study is updated successfully
611 private boolean update(final Study aStudy) {
612 boolean isOk = false;
614 getStudyDAO().merge(aStudy); // Update of relational base
615 setShortCuts(aStudy); // RKV: initialize transient actors set
616 //RKV: getIndex().update(aStudy); // Update of Lucene index
618 } catch (Exception e) {
619 LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
625 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
629 * @return true if reference building is succeded
632 private boolean buildReference(final Study aStudy) {
633 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
634 IDBuilder tool = selectIDBuilder(aStudy.getDate());
636 tool = new IDBuilder(aStudy.getDate());
637 getIDBuilderDAO().create(tool);
639 aStudy.setReference(buildReference(tool, pattern, aStudy));
644 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
651 * the reference pattern
652 * @return true if reference building is succeded
655 public String buildReference(final IDBuilder aBuilder,
656 final String pattern, final Study study) {
657 char[] format = pattern.toCharArray();
658 char[] ref = new char[80]; // Better evaluate the length of the generated string
659 int next = aBuilder.getBase() + 1;
662 for (int i = 0; i < format.length; i++) {
664 // Insertion of attribute values
665 if (format[i] == '%') {
668 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
670 while (format[i] == 'y') {
672 if (i == format.length) {
676 SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
677 String year = tostring.format(study.getDate());
678 year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
679 for (int j = 0; j < year.length(); j++) {
680 ref[count] = year.charAt(j);
683 i -= 1; // Back to the last 'y' character
684 } else if (format[i] == '0') { // Insertion of the index
686 while (format[i] == '0') {
688 if (i == format.length) {
692 DecimalFormat tostring = new DecimalFormat(pattern
694 String number = tostring.format(next);
695 for (int j = 0; j < number.length(); j++) {
696 ref[count] = number.charAt(j);
699 i -= 1; // Back to the last '0' character
701 // Keep the character
703 ref[count] = format[i];
707 // Incrementation of the number of study
708 aBuilder.setBase(next);
709 getIDBuilderDAO().update(aBuilder);
710 return String.copyValueOf(ref, 0, count);
714 * Find an id builder by date.
718 * @return found id builder
720 private IDBuilder selectIDBuilder(final Date date) {
721 Calendar aDate = Calendar.getInstance();
723 return getIDBuilderDAO().findByCriteria(
724 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
728 * Fill transient collection ModifiableActors of the study.
733 private void resetActorsShortCut(final Study aStudy) {
734 getModifiableActors(aStudy).clear();
735 // Get all actors involved in validation cycles
736 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
737 .values().iterator(); i.hasNext();) {
738 ValidationCycle cycle = i.next();
739 User[] user = cycle.getAllActors();
740 for (int j = 0; j < user.length; j++) {
741 getModifiableActors(aStudy).add(user[j]);
744 // Get all other actors
745 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
747 Relation link = i.next();
748 Class<?> kindof = link.getClass().getSuperclass();
749 if (!kindof.equals(ActorRelation.class)) {
752 getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
757 * Update lucene index for the study knowledge elements.
761 * @return true if reindexing succeeded
763 private boolean updateKnowledgeElementsIndex(final Study aStudy) {
764 // boolean isOk = false;
766 // IndexService lucin = getIndex();
767 // for(Scenario scenario : aStudy.getScenariiList()) {
768 // for (KnowledgeElement element : scenario.getAllKnowledgeElements()) {
769 // lucin.update(element);
773 // } catch (Exception error) {
774 // LOG.error("Unable to re-index Knowledge Elements, reason:",
782 * Get lucene index service. Create a lucene index if it does not exist.
784 * @return index service
785 * @throws IOException
786 * if error occurs during lucene index creation
788 private IndexService getIndex() throws IOException {
789 IndexService lucin = getIndexService();
790 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
791 .getRepositoryIndexDirectory()))) {
792 IndexWriter.unlock(FSDirectory.open(getRepositoryService()
793 .getRepositoryIndexDirectory()));
795 if (!lucin.exists()) {
796 lucin.create(); // Happens when re-indexing all studies
802 * Create a new validation cycle for documents of the given study.
807 * the cycle description
808 * @return the new validation cycle
810 protected ValidationCycle createValidationCycle(
812 final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
813 Actor[] actype = cycle.getActorTypes();
814 User.Properties uprop = new User.Properties();
816 ValidationCycle aValidationCycle = new ValidationCycle();
817 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
818 cycle.getName())); // Null in case of default validation cycle
819 // context = new ValidationCycleRelation(from, vprop);
820 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
821 for (int i = 0; i < actype.length; i++) {
823 if (actype[i] != null) {
825 if (actype[i] == Actor.manager) {
826 actor = from.getAuthor();
827 } else if (actype[i] == Actor.Nx1) {
828 List<User> manager = getUserService().selectUsersWhere(
829 uprop.setOrganizationName("Nx1"));
830 if (manager.size() == 1) {
831 actor = manager.get(0);
833 } else if (actype[i] == Actor.Nx2) {
834 List<User> manager = getUserService().selectUsersWhere(
835 uprop.setOrganizationName("Nx2"));
836 if (manager.size() == 1) {
837 actor = manager.get(0);
839 } else { /* Actor.customer */
840 actor = from.getAuthor();
841 // TODO: Get the customer of the study, if exists
843 } catch (Exception e) { // Should not happen
848 aValidationCycle.setReviewer(actor);
850 aValidationCycle.setApprover(actor);
852 aValidationCycle.setSignatory(actor);
855 return aValidationCycle;
859 * Remove a validation step from the validation cycle.
861 * @param aValidationCycle
862 * the validation cycle
864 * the validation step to remove
867 protected void remove(final ValidationCycle aValidationCycle,
868 final ValidationStep step) {
869 if (step == ValidationStep.REVIEW) {
870 aValidationCycle.setReviewer(null);
871 } else if (step == ValidationStep.APPROVAL) {
872 aValidationCycle.setApprover(null);
873 } else if (step == ValidationStep.ACCEPTANCE
874 || step == ValidationStep.REFUSAL) {
875 aValidationCycle.setSignatory(null);
877 if (aValidationCycle.isSaved()) {
878 getValidationCycleDAO().update(aValidationCycle);
883 * Reset actors for the validation cycle.
885 * @param aValidationCycle
886 * the validation cycle to update
888 * new validation cycle properties containing new actors
891 public void resetActors(final ValidationCycle aValidationCycle,
892 final ValidationCycle.Properties vprop) {
893 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
894 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
895 aValidationCycle.setApprover(vprop.getApprover()); // May be null
896 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
897 if (aValidationCycle.isSaved()) {
898 getValidationCycleDAO().merge(aValidationCycle);
903 * Set actor for the given validation cycle and validation step.
905 * @param aValidationCycle
906 * the validation cycle
908 * the validation step
913 protected void setActor(final ValidationCycle aValidationCycle,
914 final ValidationStep step, final User actor) {
915 if (step == ValidationStep.PROMOTION) {
916 aValidationCycle.setPublisher(actor);
917 } else if (step == ValidationStep.REVIEW) {
918 aValidationCycle.setReviewer(actor);
919 } else if (step == ValidationStep.APPROVAL) {
920 aValidationCycle.setApprover(actor);
921 } else if (step == ValidationStep.ACCEPTANCE
922 || step == ValidationStep.REFUSAL) {
923 aValidationCycle.setSignatory(actor);
925 if (aValidationCycle.isSaved()) {
926 getValidationCycleDAO().update(aValidationCycle);
931 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
935 * @return the actors of this study
936 * @see #hasActor(User)
938 public Set<User> getActors(final Study aStudy) {
939 if (aStudy.getActor() == null) {
940 setShortCuts(aStudy);
942 return Collections.unmodifiableSet(aStudy.getActor());
946 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
950 * @return the modifiable set of actors of this study
951 * @see #hasActor(User)
953 public Set<User> getModifiableActors(final Study aStudy) {
954 if (aStudy.getActor() == null) {
955 setShortCuts(aStudy);
957 return aStudy.getActor();
961 * Returns unmodifiable initialized transient list of contributors of this study.
965 * @return the unmodifiable not null transient list of contributors of this study
967 public List<User> getContributors(final Study aStudy) {
968 if (aStudy.getContributor() == null) {
969 setShortCuts(aStudy);
971 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
975 * Returns modifiable initialized transient list of contributors of this study.
979 * @return the modifiable not null transient list of contributors of this study
981 public List<User> getModifiableContributors(final Study aStudy) {
982 if (aStudy.getContributor() == null) {
983 setShortCuts(aStudy);
985 return aStudy.getContributor(); // May be empty
989 * Returns the validation cycle of the given document type.
994 * the document type being subject of validation
995 * @return the validation cycle of the document, or null if not defined.
997 public ValidationCycle getValidationCycleOf(final Study aStudy,
998 final DocumentType type) {
999 if (aStudy.getValidationCycles() == null
1000 || aStudy.getValidationCycles().isEmpty()) {
1001 setShortCuts(aStudy);
1003 ValidationCycle result = aStudy.getValidationCycles().get(
1005 if (result == null) {
1006 if (type.isStepResult()) {
1007 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
1009 if (result == null) {
1010 result = aStudy.getValidationCycles().get("built-in");
1017 * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
1022 * the user to look for
1023 * @return true if the given user is actor of this study.
1026 public boolean hasActor(final Study aStudy, final User user) {
1030 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
1031 User involved = i.next();
1032 if (involved.equals(user)) {
1040 * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1045 * the user to look for
1046 * @return true if the given user is actor of this study.
1047 * @see #getContributors()
1049 public boolean isStaffedBy(final Study aStudy, final User user) {
1053 if (aStudy == null) {
1056 if (aStudy.getAuthor() == null) {
1059 if (aStudy.getAuthor().equals(user)) {
1062 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1063 if (i.next().equals(user)) {
1071 * Initialize shortcuts of the study as its transient collections.
1076 public void loadWorkflow(final Study aStudy) {
1077 setShortCuts(aStudy);
1081 * Initialize shortcuts of the study as its transient collections.
1086 public void setShortCuts(final Study aStudy) {
1087 aStudy.getContributor().clear();
1088 aStudy.getValidationCycles().clear();
1089 aStudy.getActor().clear();
1091 // Get the contributors
1092 for (Iterator<Relation> i = aStudy.getRelations(
1093 ContributorRelation.class).iterator(); i.hasNext();) {
1094 ContributorRelation link = (ContributorRelation) i.next();
1095 aStudy.getContributor().add(link.getTo());
1097 // Get the validation cycles specific to this study
1098 for (Iterator<Relation> i = aStudy.getRelations(
1099 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1100 ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1101 aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1102 link.getTo()); // The associated document type is necessarily not null in this
1105 // Get the validation cycles coming from the configured workflow and not overridden in this study
1106 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1107 .getAllValidationCycles().iterator(); i.hasNext();) {
1108 ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1110 String type = cycle.getName();
1111 if (!aStudy.getValidationCycles().containsKey(type)) {
1112 aStudy.getValidationCycles().put(type,
1113 createValidationCycle(aStudy, cycle));
1116 // Get all corresponding actors
1117 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1118 .values().iterator(); i.hasNext();) {
1119 ValidationCycle cycle = i.next();
1120 User[] user = cycle.getAllActors();
1121 for (int j = 0; j < user.length; j++) {
1122 aStudy.getActor().add(user[j]);
1125 // Get all other actors
1126 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1128 Relation link = i.next();
1129 Class<?> kindof = link.getClass().getSuperclass();
1130 if (!kindof.equals(ActorRelation.class)) {
1133 aStudy.getActor().add(((ActorRelation) link).getTo());
1141 * @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)
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
1182 return study.getDescription();
1188 * @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
1201 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1207 * @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()
1255 + " Scenario: " + docDTO.getScenarioTitle() + " Document: "
1256 + docDTO.getDocumentTitle());
1258 // read the file and get points information.
1260 Scanner input = new Scanner(compDocFile);
1262 // get the title of the chart.
1263 if (input.hasNext()) {
1264 chartTitle = input.nextLine();
1267 // get the name of the axis.
1268 if (input.hasNext()) {
1269 String[] tokens = input.nextLine().split(",");
1271 if (tokens.length < 2) {
1272 throw new IncompatibleDataException(
1273 MessageKeyEnum.IDT_000001.toString());
1276 if ("".equals(axis1Name)) {
1277 axis1Name = tokens[0];
1278 } else if (!axis1Name.equals(tokens[0])) {
1279 LOG.debug("Axis must be the same for all documents");
1280 throw new IncompatibleDataException(
1281 MessageKeyEnum.IDT_000001.toString());
1284 if ("".equals(axis2Name)) {
1285 axis2Name = tokens[1];
1286 } else if (!axis2Name.equals(tokens[1])) {
1287 LOG.debug("Axis must be the same for all documents");
1288 throw new IncompatibleDataException(
1289 MessageKeyEnum.IDT_000001.toString());
1293 // Get the XY points series.
1294 while (input.hasNext()) {
1296 String currentString = input.nextLine();
1298 if (!("".equals(currentString))) {
1299 String[] tokens = currentString.split(" ");
1300 series.add(Double.valueOf(tokens[0]), Double
1301 .valueOf(tokens[1]));
1306 dataset.addSeries(series);
1308 } catch (FileNotFoundException e) {
1309 LOG.error("Sorry, the file is not found.", e);
1313 JFreeChart chart = ChartFactory.createXYLineChart(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);
1357 * @see org.splat.service.StudyService#getReaders(long)
1359 @Transactional(readOnly = true)
1360 public List<UserDTO> getReaders(final long studyId) throws InvalidParameterException {
1361 Study aStudy = selectStudy(studyId);
1363 throw new InvalidParameterException("studyId", String.valueOf(studyId));
1365 List<Relation> relations = aStudy.getRelations(ReaderRelation.class);
1366 List<UserDTO> result = new ArrayList<UserDTO>();
1367 for(Relation relation : relations){
1368 result.add(BeanHelper.copyBean(relation.getTo(), UserDTO.class));
1370 return Collections.unmodifiableList(result);
1375 * @see org.splat.service.StudyService#addReader(long, long)
1378 public boolean addReader(final long studyId, final long userId) throws InvalidParameterException {
1379 Study aStudy = selectStudy(studyId);
1381 throw new InvalidParameterException("studyId", String.valueOf(studyId));
1383 User user = _userService.selectUser(userId);
1385 throw new InvalidParameterException("userId", String.valueOf(userId));
1388 for(Relation relation : aStudy.getRelations(ReaderRelation.class)) {
1389 if(user.equals(relation.getTo())) {
1393 aStudy.addRelation(new ReaderRelation(aStudy, user));
1400 * @see org.splat.service.StudyService#removeReader(long, long)
1403 public boolean removeReader(final long studyId, final long userId) throws InvalidParameterException {
1404 Study aStudy = selectStudy(studyId);
1406 throw new InvalidParameterException("studyId", String.valueOf(studyId));
1408 User user = _userService.selectUser(userId);
1410 throw new InvalidParameterException("userId", String.valueOf(userId));
1413 Relation relation = aStudy.removeRelation(ReaderRelation.class, user);
1415 return relation != null;
1419 * Get project settings.
1421 * @return Project settings service
1423 private ProjectSettingsService getProjectSettings() {
1424 return _projectSettings;
1428 * Set project settings service.
1430 * @param projectSettingsService
1431 * project settings service
1433 public void setProjectSettings(
1434 final ProjectSettingsService projectSettingsService) {
1435 _projectSettings = projectSettingsService;
1439 * Get the projectElementService.
1441 * @return the projectElementService
1443 public ProjectElementService getProjectElementService() {
1444 return _projectElementService;
1448 * Set the projectElementService.
1450 * @param projectElementService
1451 * the projectElementService to set
1453 public void setProjectElementService(
1454 final ProjectElementService projectElementService) {
1455 _projectElementService = projectElementService;
1459 * Get the stepService.
1461 * @return the stepService
1463 public StepService getStepService() {
1464 return _stepService;
1468 * Set the stepService.
1470 * @param stepService
1471 * the stepService to set
1473 public void setStepService(final StepService stepService) {
1474 _stepService = stepService;
1478 * Get the indexService.
1480 * @return the indexService
1482 public IndexService getIndexService() {
1483 return _indexService;
1487 * Set the indexService.
1489 * @param indexService
1490 * the indexService to set
1492 public void setIndexService(final IndexService indexService) {
1493 _indexService = indexService;
1499 * @return the studyDAO
1501 public StudyDAO getStudyDAO() {
1509 * the studyDAO to set
1511 public void setStudyDAO(final StudyDAO studyDAO) {
1512 _studyDAO = studyDAO;
1516 * Get the iDBuilderDAO.
1518 * @return the iDBuilderDAO
1520 public IDBuilderDAO getIDBuilderDAO() {
1521 return _iDBuilderDAO;
1525 * Set the iDBuilderDAO.
1528 * the iDBuilderDAO to set
1530 public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1531 _iDBuilderDAO = builderDAO;
1535 * Get the scenarioDAO.
1537 * @return the scenarioDAO
1539 public ScenarioDAO getScenarioDAO() {
1540 return _scenarioDAO;
1544 * Set the scenarioDAO.
1546 * @param scenarioDAO
1547 * the scenarioDAO to set
1549 public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1550 _scenarioDAO = scenarioDAO;
1554 * Get the validationCycleDAO.
1556 * @return the validationCycleDAO
1558 public ValidationCycleDAO getValidationCycleDAO() {
1559 return _validationCycleDAO;
1563 * Set the validationCycleDAO.
1565 * @param validationCycleDAO
1566 * the validationCycleDAO to set
1568 public void setValidationCycleDAO(
1569 final ValidationCycleDAO validationCycleDAO) {
1570 _validationCycleDAO = validationCycleDAO;
1574 * Get the documentTypeService.
1576 * @return the documentTypeService
1578 public DocumentTypeService getDocumentTypeService() {
1579 return _documentTypeService;
1583 * Set the documentTypeService.
1585 * @param documentTypeService
1586 * the documentTypeService to set
1588 public void setDocumentTypeService(
1589 final DocumentTypeService documentTypeService) {
1590 _documentTypeService = documentTypeService;
1594 * Get the userService.
1596 * @return the userService
1598 public UserService getUserService() {
1599 return _userService;
1603 * Set the userService.
1605 * @param userService
1606 * the userService to set
1608 public void setUserService(final UserService userService) {
1609 _userService = userService;
1615 * @see org.splat.service.StudyService#getComparableStudies()
1617 @Transactional(readOnly = true)
1618 public List<StudyFacadeDTO> getComparableStudies(final long userId)
1619 throws MismatchException {
1620 // retrieve the number of the "Analyze the results" step
1621 List<Step> allSteps = _projectSettings.getAllSteps();
1622 Step theAnalyzeStep = null;
1623 for (Step step : allSteps) {
1624 if (step.getKey().equals("postprocessing")) {
1625 theAnalyzeStep = step;
1628 if (theAnalyzeStep == null) { // TODO: throw some other exception
1629 throw new MismatchException(
1630 "no step with key 'postprocessing' found."
1631 + "Probably, customization settings have been changed.");
1634 List<Publication> publications = _publicationDAO.getFilteredList(
1635 "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep
1638 // split retrieved publications into groups by studies and scenarios
1639 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1640 Map<ProjectElement, List<Publication>> scenarioMap = new HashMap<ProjectElement, List<Publication>>();
1642 for (Publication publication : publications) {
1643 // filter out publications corresponding to a document of given step which is not a _result_ document
1644 if (!publication.value().getType().isResultOf(theAnalyzeStep)
1645 || !"srd".equals(publication.getSourceFile().getFormat())) {
1649 // check the study visibility to the user
1650 if (!isStaffedBy(publication.getOwnerStudy(), _userService
1651 .selectUser(userId))
1652 && Visibility.PUBLIC.equals(publication.getOwnerStudy()
1653 .getVisibility())) {
1657 Study study = publication.getOwnerStudy();
1658 ProjectElement scenario = publication.getOwner();
1660 Hibernate.initialize(scenario);
1661 if (scenario instanceof HibernateProxy) {
1662 scenario = (ProjectElement) ((HibernateProxy) scenario)
1663 .getHibernateLazyInitializer().getImplementation();
1666 if (!(scenario instanceof Scenario)) {
1667 throw new MismatchException(
1668 "publications from postprocessing step are supposed to have owner scenario");
1671 if (!studyMap.containsKey(study)) {
1672 studyMap.put(study, new ArrayList<ProjectElement>());
1675 if (!studyMap.get(study).contains(scenario)) {
1676 studyMap.get(study).add(scenario);
1679 if (!scenarioMap.containsKey(scenario)) {
1680 scenarioMap.put(scenario, new ArrayList<Publication>());
1682 scenarioMap.get(scenario).add(publication);
1685 // Create the result DTOs
1686 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1687 for (Study study : studyMap.keySet()) {
1689 StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1690 studyDTO.setName(study.getTitle());
1691 studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1692 result.add(studyDTO);
1694 for (ProjectElement scenario : studyMap.get(study)) {
1696 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1697 scenarioDTO.setName(scenario.getTitle());
1698 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1699 studyDTO.getScenarios().add(scenarioDTO);
1701 for (Publication publication : scenarioMap.get(scenario)) {
1703 DocumentDTO documentDTO = new DocumentDTO();
1704 documentDTO.setId(publication.getIndex());
1705 documentDTO.setTitle(publication.value().getTitle());
1707 scenarioDTO.getDocs().add(documentDTO);
1715 * Get the publicationDAO.
1717 * @return the publicationDAO
1719 public PublicationDAO getPublicationDAO() {
1720 return _publicationDAO;
1724 * Set the publicationDAO.
1726 * @param publicationDAO
1727 * the publicationDAO to set
1729 public void setPublicationDAO(final PublicationDAO publicationDAO) {
1730 _publicationDAO = publicationDAO;
1734 * Get the repositoryService.
1736 * @return the repositoryService
1738 public RepositoryService getRepositoryService() {
1739 return _repositoryService;
1743 * Set the repositoryService.
1745 * @param repositoryService
1746 * the repositoryService to set
1748 public void setRepositoryService(final RepositoryService repositoryService) {
1749 _repositoryService = repositoryService;
1753 * Get the documentDAO.
1755 * @return the documentDAO
1757 public DocumentDAO getDocumentDAO() {
1758 return _documentDAO;
1762 * Set the documentDAO.
1764 * @param documentDAO
1765 * the documentDAO to set
1767 public void setDocumentDAO(final DocumentDAO documentDAO) {
1768 _documentDAO = documentDAO;
1772 * Get the descriptionAttributeDAO.
1774 * @return the descriptionAttributeDAO
1776 public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1777 return _descriptionAttributeDAO;
1781 * Set the descriptionAttributeDAO.
1783 * @param descriptionAttributeDAO
1784 * the descriptionAttributeDAO to set
1786 public void setDescriptionAttributeDAO(
1787 final DescriptionAttributeDAO descriptionAttributeDAO) {
1788 _descriptionAttributeDAO = descriptionAttributeDAO;
1792 * Get the usedByRelationDAO.
1794 * @return the usedByRelationDAO
1796 public UsedByRelationDAO getUsedByRelationDAO() {
1797 return _usedByRelationDAO;
1801 * Set the usedByRelationDAO.
1803 * @param usedByRelationDAO
1804 * the usedByRelationDAO to set
1806 public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
1807 _usedByRelationDAO = usedByRelationDAO;