1 /*****************************************************************************
5 * Creation date 02.10.2012
6 * @author Author: Maria KRUCHININA
8 *****************************************************************************/
10 package org.splat.service;
12 import java.awt.Graphics2D;
14 import java.io.FileNotFoundException;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.text.DecimalFormat;
18 import java.text.SimpleDateFormat;
19 import java.util.ArrayList;
20 import java.util.Calendar;
21 import java.util.Collections;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.Scanner;
31 import org.apache.lucene.index.IndexWriter;
32 import org.apache.lucene.store.FSDirectory;
33 import org.hibernate.Criteria;
34 import org.hibernate.Hibernate;
35 import org.hibernate.criterion.DetachedCriteria;
36 import org.hibernate.criterion.Restrictions;
37 import org.hibernate.proxy.HibernateProxy;
38 import org.jfree.chart.ChartFactory;
39 import org.jfree.chart.JFreeChart;
40 import org.jfree.chart.plot.PlotOrientation;
41 import org.jfree.data.xy.XYSeries;
42 import org.jfree.data.xy.XYSeriesCollection;
43 import org.splat.common.properties.MessageKeyEnum;
44 import org.splat.dal.bo.kernel.Relation;
45 import org.splat.dal.bo.kernel.User;
46 import org.splat.dal.bo.som.ActorRelation;
47 import org.splat.dal.bo.som.ContributorRelation;
48 import org.splat.dal.bo.som.DescriptionAttribute;
49 import org.splat.dal.bo.som.DocumentType;
50 import org.splat.dal.bo.som.IDBuilder;
51 import org.splat.dal.bo.som.ProgressState;
52 import org.splat.dal.bo.som.ProjectElement;
53 import org.splat.dal.bo.som.Publication;
54 import org.splat.dal.bo.som.Scenario;
55 import org.splat.dal.bo.som.SimulationContext;
56 import org.splat.dal.bo.som.Study;
57 import org.splat.dal.bo.som.ValidationCycle;
58 import org.splat.dal.bo.som.ValidationCycleRelation;
59 import org.splat.dal.bo.som.ValidationStep;
60 import org.splat.dal.bo.som.Visibility;
61 import org.splat.dal.bo.som.Study.Properties;
62 import org.splat.dal.bo.som.ValidationCycle.Actor;
63 import org.splat.dal.dao.som.DescriptionAttributeDAO;
64 import org.splat.dal.dao.som.DocumentDAO;
65 import org.splat.dal.dao.som.IDBuilderDAO;
66 import org.splat.dal.dao.som.PublicationDAO;
67 import org.splat.dal.dao.som.ScenarioDAO;
68 import org.splat.dal.dao.som.StudyDAO;
69 import org.splat.dal.dao.som.UsedByRelationDAO;
70 import org.splat.dal.dao.som.ValidationCycleDAO;
71 import org.splat.exception.BusinessException;
72 import org.splat.exception.IncompatibleDataException;
73 import org.splat.exception.InvalidParameterException;
74 import org.splat.kernel.InvalidPropertyException;
75 import org.splat.kernel.MismatchException;
76 import org.splat.kernel.MissedPropertyException;
77 import org.splat.kernel.MultiplyDefinedException;
78 import org.splat.log.AppLogger;
79 import org.splat.service.dto.DocToCompareDTO;
80 import org.splat.service.dto.DocumentDTO;
81 import org.splat.service.dto.StudyFacadeDTO;
82 import org.splat.service.technical.IndexService;
83 import org.splat.service.technical.ProjectSettingsService;
84 import org.splat.service.technical.ProjectSettingsServiceImpl;
85 import org.splat.service.technical.RepositoryService;
86 import org.splat.service.technical.ProjectSettingsService.Step;
87 import org.splat.som.Revision;
88 import org.springframework.transaction.annotation.Transactional;
90 import com.lowagie.text.Document;
91 import com.lowagie.text.DocumentException;
92 import com.lowagie.text.Rectangle;
93 import com.lowagie.text.pdf.DefaultFontMapper;
94 import com.lowagie.text.pdf.PdfContentByte;
95 import com.lowagie.text.pdf.PdfTemplate;
96 import com.lowagie.text.pdf.PdfWriter;
99 * This class defines all methods for creation, modification the study.
101 * @author Maria KRUCHININA
104 public class StudyServiceImpl implements StudyService {
107 * logger for the service.
109 public final static AppLogger LOG = AppLogger
110 .getLogger(StudyServiceImpl.class);
112 * "studyId" parameter name.
114 public final static String PARAM_STUDY_ID = "studyId";
117 * Injected index service.
119 private IndexService _indexService;
122 * Injected step service.
124 private StepService _stepService;
127 * Injected project service.
129 private ProjectSettingsService _projectSettings;
132 * Injected project element service.
134 private ProjectElementService _projectElementService;
137 * Injected study DAO.
139 private StudyDAO _studyDAO;
142 * Injected usedBy relations DAO.
144 private UsedByRelationDAO _usedByRelationDAO;
147 * Injected scenario DAO.
149 private ScenarioDAO _scenarioDAO;
152 * Injected validation cycle DAO.
154 private ValidationCycleDAO _validationCycleDAO;
157 * Injected IDBuilder DAO.
159 private IDBuilderDAO _iDBuilderDAO;
162 * Injected document type service.
164 private DocumentTypeService _documentTypeService;
167 * Injected user service.
169 private UserService _userService;
172 * Injected publication DAO.
174 private PublicationDAO _publicationDAO;
177 * Injected repository service.
179 private RepositoryService _repositoryService;
182 * Injected document DAO.
184 private DocumentDAO _documentDAO;
187 * Injected description attribute DAO.
189 private DescriptionAttributeDAO _descriptionAttributeDAO;
194 * @see org.splat.service.StudyService#selectStudy(long)
197 public Study selectStudy(final long index) {
198 Study result = getStudyDAO().get(index);
199 if (result != null) {
200 loadWorkflow(result);
208 * @see org.splat.service.StudyService#removeStudy(long)
211 public void removeStudy(final Long index) {
212 Study study = getStudyDAO().get(index);
213 Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
215 // Select all documents published in the study and study's scenarios.
216 DetachedCriteria query = DetachedCriteria.forClass(
217 Publication.class, "pub");
219 .createCriteria("pub.owner", "projelem",
221 .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
224 .or(Restrictions.eq("projelem.rid", index),
225 Restrictions.eq("study.rid", index)))
226 .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
228 if (LOG.isDebugEnabled()) {
229 LOG.debug("Find study documents: " + query.toString());
231 for (Publication pub : getPublicationDAO().getFilteredList(query)) {
232 docums.add(pub.value());
233 // Find also all previous versions of the document
234 for (org.splat.dal.bo.som.Document prev = pub.value()
235 .getPreviousVersion(); prev != null; prev = prev
236 .getPreviousVersion()) {
241 // Delete the study with its relations, scenarios and publications
242 getStudyDAO().delete(study);
244 // Remove all relations of study documents
245 for (org.splat.dal.bo.som.Document doc : docums) {
246 LOG.debug("Found doc: " + doc.getTitle() + " ["
247 + doc.getReference() + "]" + " [" + doc.getRid() + "]");
248 doc.getAllRelations().clear();
250 getDocumentDAO().flush();
252 // Remove all documents of the study
253 for (org.splat.dal.bo.som.Document doc : docums) {
254 LOG.debug("Remove doc: " + doc.getTitle() + " ["
255 + doc.getReference() + "]" + " [" + doc.getRid() + "]");
256 getDocumentDAO().delete(doc);
262 * Get study by its reference.
265 * the study reference
266 * @return found study or null
268 @Transactional(readOnly = true)
269 public Study selectStudy(final String refid) {
270 Study result = getStudyDAO().findByCriteria(
271 Restrictions.eq("sid", refid));
272 loadWorkflow(result);
279 * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
282 public Study createStudy(final Study.Properties sprop)
283 throws MissedPropertyException, InvalidPropertyException,
284 MultiplyDefinedException {
285 sprop.setReference(getProjectSettings().getReferencePattern());
286 Study study = new Study(sprop);
288 buildReference(study);
289 getStudyDAO().create(study);
291 // IndexService lucin = getIndex();
293 // } catch (IOException error) {
294 // LOG.error("Unable to index the study '" + study.getIndex()
295 // + "', reason:", error);
296 // // Continue and try to index later
304 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
307 public SimulationContext addProjectContext(final Study aStudy,
308 final SimulationContext.Properties cprop)
309 throws MissedPropertyException, InvalidPropertyException,
310 MultiplyDefinedException {
311 SimulationContext added = getStepService().addSimulationContext(
312 getProjectElementService().getFirstStep(aStudy), cprop);
320 * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
323 public SimulationContext addProjectContext(final Study aStudy,
324 final SimulationContext context) {
325 SimulationContext added = getStepService().addSimulationContext(
326 getProjectElementService().getFirstStep(aStudy), context);
334 * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
337 public boolean addContributor(final Study aStudy, final User user) {
338 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
339 for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
340 User present = i.next();
341 if (present.equals(user)) {
345 boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
347 aStudy.addRelation(new ContributorRelation(aStudy, user));
349 update(aStudy); // Else, useless to re-index the study
355 * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
356 * previously be approved.
360 * @return true if the move succeeded.
361 * @see #moveToPublic()
363 * @see Publication#approve(Date)
365 public boolean moveToReference(final Study aStudy) {
366 if (aStudy.getProgressState() != ProgressState.APPROVED) {
369 if (aStudy.getVisibility() != Visibility.PUBLIC) {
373 aStudy.setVisibility(Visibility.REFERENCE);
374 if (update(aStudy)) {
375 return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
383 * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
385 public boolean update(final Study aStudy, final Properties sprop)
386 throws InvalidPropertyException {
387 if (sprop.getTitle() != null) {
388 aStudy.setTitle(sprop.getTitle());
390 if (sprop.getSummary() != null) {
391 aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
394 // TODO: To be completed
395 return update(aStudy);
399 * Check if the document is published in the study.
405 * @return true if the document is published in the study
408 * private boolean publishes(final Study aStudy, final Document doc) { if (!aStudy.publishes(doc)) { Scenario[] scene =
409 * aStudy.getScenarii(); for (int i = 0; i < scene.length; i++) { if (scene[i].publishes(doc)) { return true; } } } return false; }
414 * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
417 public boolean removeContributor(final Study aStudy, final User... users) {
418 List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
419 Boolean done = false;
420 for (int i = 0; i < users.length; i++) {
421 User user = users[i];
422 for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
423 User present = j.next();
424 if (!present.equals(user)) {
428 aStudy.removeRelation(ContributorRelation.class, user);
429 j.remove(); // Updates the contributor shortcut
443 * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
445 public boolean removeProjectContext(final Study aStudy,
446 final SimulationContext context) {
447 boolean done = getStepService().removeSimulationContext(
448 getProjectElementService().getFirstStep(aStudy), context);
456 * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
457 * org.splat.dal.bo.som.ValidationCycle.Properties)
460 public void setValidationCycle(final Study aStudyDTO,
461 final DocumentType type, final ValidationCycle.Properties vprop) {
462 Map<String, ValidationCycle> validactor = aStudyDTO
463 .getValidationCycles();
464 if (validactor == null) {
465 setShortCuts(aStudyDTO); // Initializes validactor and actor
468 Study aStudy = selectStudy(aStudyDTO.getIndex());
470 String cname = type.getName();
471 ValidationCycle cycle = validactor.get(cname);
473 if (cycle != null && cycle.isAssigned()) {
474 resetActors(cycle, vprop);
477 cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
479 getValidationCycleDAO().create(cycle); // RKV
481 ValidationCycleRelation link = cycle.getContext();
482 aStudy.addRelation(link);
483 aStudyDTO.getAllRelations().add(link); // RKV
485 validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
486 } catch (BusinessException error) {
487 LOG.error("Unable to create validation cycle, reason:", error);
491 resetActorsShortCut(aStudyDTO);
492 update(aStudy); // Re-index the study, just in case
496 * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
497 * document of the study.
501 * @return true if the demotion succeeded.
503 public boolean demote(final Study aStudy) {
504 if (aStudy.getProgressState() == ProgressState.inCHECK) {
505 aStudy.setProgressState(ProgressState.inDRAFT);
506 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
507 aStudy.setProgressState(ProgressState.inWORK);
511 return update(aStudy);
517 * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
520 public int generateLocalIndex(final Study aStudy) {
521 aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
522 return aStudy.getLastLocalIndex();
526 * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
527 * final result document of the study.
531 * @return true if the demotion succeeded.
534 public boolean promote(final Study aStudy) {
535 if (aStudy.getProgressState() == ProgressState.inWORK) {
536 aStudy.setProgressState(ProgressState.inDRAFT);
537 } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
538 aStudy.setProgressState(ProgressState.inCHECK);
539 Revision myvers = new Revision(aStudy.getVersion());
540 if (myvers.isMinor()) {
541 aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
544 } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
545 aStudy.setProgressState(ProgressState.APPROVED);
550 return update(aStudy);
554 * Moves this study from the Private to the Public area of the repository.
558 * @return true if the move succeeded.
562 public boolean moveToPublic(final Study aStudy) {
563 boolean isOk = false;
564 if (aStudy.getVisibility() == Visibility.PRIVATE) {
565 aStudy.setVisibility(Visibility.PUBLIC);
566 if (update(aStudy)) {
567 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
574 * Moves this study from the Public to the Private area of the repository.
578 * @return true if the move succeeded.
581 public boolean moveToPrivate(final Study aStudy) {
582 boolean isOk = false;
583 if (aStudy.getVisibility() == Visibility.PUBLIC) {
584 aStudy.setVisibility(Visibility.PRIVATE);
585 if (update(aStudy)) {
586 isOk = updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
593 * Update a study in the database.
596 * the study to update
597 * @return true if the study is updated successfully
600 private boolean update(final Study aStudy) {
601 boolean isOk = false;
603 getStudyDAO().merge(aStudy); // Update of relational base
604 setShortCuts(aStudy); // RKV: initialize transient actors set
605 // RKV: getIndex().update(aStudy); // Update of Lucene index
607 } catch (Exception e) {
608 LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
614 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
618 * @return true if reference building is succeded
621 private boolean buildReference(final Study aStudy) {
622 String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
623 IDBuilder tool = selectIDBuilder(aStudy.getDate());
625 tool = new IDBuilder(aStudy.getDate());
626 getIDBuilderDAO().create(tool);
628 aStudy.setReference(buildReference(tool, pattern, aStudy));
633 * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
640 * the reference pattern
641 * @return true if reference building is succeded
644 public String buildReference(final IDBuilder aBuilder,
645 final String pattern, final Study study) {
646 char[] format = pattern.toCharArray();
647 char[] ref = new char[80]; // Better evaluate the length of the generated string
648 int next = aBuilder.getBase() + 1;
651 for (int i = 0; i < format.length; i++) {
653 // Insertion of attribute values
654 if (format[i] == '%') {
657 if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
659 while (format[i] == 'y') {
661 if (i == format.length) {
665 SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
666 String year = tostring.format(study.getDate());
667 year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
668 for (int j = 0; j < year.length(); j++) {
669 ref[count] = year.charAt(j);
672 i -= 1; // Back to the last 'y' character
673 } else if (format[i] == '0') { // Insertion of the index
675 while (format[i] == '0') {
677 if (i == format.length) {
681 DecimalFormat tostring = new DecimalFormat(pattern
683 String number = tostring.format(next);
684 for (int j = 0; j < number.length(); j++) {
685 ref[count] = number.charAt(j);
688 i -= 1; // Back to the last '0' character
690 // Keep the character
692 ref[count] = format[i];
696 // Incrementation of the number of study
697 aBuilder.setBase(next);
698 getIDBuilderDAO().update(aBuilder);
699 return String.copyValueOf(ref, 0, count);
703 * Find an id builder by date.
707 * @return found id builder
709 private IDBuilder selectIDBuilder(final Date date) {
710 Calendar aDate = Calendar.getInstance();
712 return getIDBuilderDAO().findByCriteria(
713 Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
717 * Fill transient collection ModifiableActors of the study.
722 private void resetActorsShortCut(final Study aStudy) {
723 getModifiableActors(aStudy).clear();
724 // Get all actors involved in validation cycles
725 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
726 .values().iterator(); i.hasNext();) {
727 ValidationCycle cycle = i.next();
728 User[] user = cycle.getAllActors();
729 for (int j = 0; j < user.length; j++) {
730 getModifiableActors(aStudy).add(user[j]);
733 // Get all other actors
734 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
736 Relation link = i.next();
737 Class<?> kindof = link.getClass().getSuperclass();
738 if (!kindof.equals(ActorRelation.class)) {
741 getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
746 * Update lucene index for the study knowledge elements.
750 * @return true if reindexing succeeded
752 private boolean updateKnowledgeElementsIndex(final Study aStudy) {
753 // boolean isOk = false;
755 // IndexService lucin = getIndex();
757 // for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
759 // Scenario scene = i.next();
760 // for (Iterator<KnowledgeElement> j = scene
761 // .getAllKnowledgeElements().iterator(); j.hasNext();) {
762 // KnowledgeElement kelm = j.next();
763 // lucin.update(kelm);
767 // } catch (Exception error) {
768 // LOG.error("Unable to re-index Knowledge Elements, reason:",
776 * Get lucene index service. Create a lucene index if it does not exist.
778 * @return index service
779 * @throws IOException
780 * if error occurs during lucene index creation
782 private IndexService getIndex() throws IOException {
783 IndexService lucin = getIndexService();
784 if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
785 .getRepositoryIndexDirectory()))) {
786 IndexWriter.unlock(FSDirectory.open(getRepositoryService()
787 .getRepositoryIndexDirectory()));
789 if (!lucin.exists()) {
790 lucin.create(); // Happens when re-indexing all studies
796 * Create a new validation cycle for documents of the given study.
801 * the cycle description
802 * @return the new validation cycle
804 protected ValidationCycle createValidationCycle(
806 final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
807 Actor[] actype = cycle.getActorTypes();
808 User.Properties uprop = new User.Properties();
810 ValidationCycle aValidationCycle = new ValidationCycle();
811 aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
812 cycle.getName())); // Null in case of default validation cycle
813 // context = new ValidationCycleRelation(from, vprop);
814 // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
815 for (int i = 0; i < actype.length; i++) {
817 if (actype[i] != null) {
819 if (actype[i] == Actor.manager) {
820 actor = from.getAuthor();
821 } else if (actype[i] == Actor.Nx1) {
822 List<User> manager = getUserService().selectUsersWhere(
823 uprop.setOrganizationName("Nx1"));
824 if (manager.size() == 1) {
825 actor = manager.get(0);
827 } else if (actype[i] == Actor.Nx2) {
828 List<User> manager = getUserService().selectUsersWhere(
829 uprop.setOrganizationName("Nx2"));
830 if (manager.size() == 1) {
831 actor = manager.get(0);
833 } else { /* Actor.customer */
834 actor = from.getAuthor();
835 // TODO: Get the customer of the study, if exists
837 } catch (Exception e) { // Should not happen
842 aValidationCycle.setReviewer(actor);
844 aValidationCycle.setApprover(actor);
846 aValidationCycle.setSignatory(actor);
849 return aValidationCycle;
853 * Remove a validation step from the validation cycle.
855 * @param aValidationCycle
856 * the validation cycle
858 * the validation step to remove
861 protected void remove(final ValidationCycle aValidationCycle,
862 final ValidationStep step) {
863 if (step == ValidationStep.REVIEW) {
864 aValidationCycle.setReviewer(null);
865 } else if (step == ValidationStep.APPROVAL) {
866 aValidationCycle.setApprover(null);
867 } else if (step == ValidationStep.ACCEPTANCE
868 || step == ValidationStep.REFUSAL) {
869 aValidationCycle.setSignatory(null);
871 if (aValidationCycle.isSaved()) {
872 getValidationCycleDAO().update(aValidationCycle);
877 * Reset actors for the validation cycle.
879 * @param aValidationCycle
880 * the validation cycle to update
882 * new validation cycle properties containing new actors
885 public void resetActors(final ValidationCycle aValidationCycle,
886 final ValidationCycle.Properties vprop) {
887 aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
888 aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
889 aValidationCycle.setApprover(vprop.getApprover()); // May be null
890 aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
891 if (aValidationCycle.isSaved()) {
892 getValidationCycleDAO().merge(aValidationCycle);
897 * Set actor for the given validation cycle and validation step.
899 * @param aValidationCycle
900 * the validation cycle
902 * the validation step
907 protected void setActor(final ValidationCycle aValidationCycle,
908 final ValidationStep step, final User actor) {
909 if (step == ValidationStep.PROMOTION) {
910 aValidationCycle.setPublisher(actor);
911 } else if (step == ValidationStep.REVIEW) {
912 aValidationCycle.setReviewer(actor);
913 } else if (step == ValidationStep.APPROVAL) {
914 aValidationCycle.setApprover(actor);
915 } else if (step == ValidationStep.ACCEPTANCE
916 || step == ValidationStep.REFUSAL) {
917 aValidationCycle.setSignatory(actor);
919 if (aValidationCycle.isSaved()) {
920 getValidationCycleDAO().update(aValidationCycle);
925 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
929 * @return the actors of this study
930 * @see #hasActor(User)
932 public Set<User> getActors(final Study aStudy) {
933 if (aStudy.getActor() == null) {
934 setShortCuts(aStudy);
936 return Collections.unmodifiableSet(aStudy.getActor());
940 * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
944 * @return the modifiable set of actors of this study
945 * @see #hasActor(User)
947 public Set<User> getModifiableActors(final Study aStudy) {
948 if (aStudy.getActor() == null) {
949 setShortCuts(aStudy);
951 return aStudy.getActor();
955 * Returns unmodifiable initialized transient list of contributors of this study.
959 * @return the unmodifiable not null transient list of contributors of this study
961 public List<User> getContributors(final Study aStudy) {
962 if (aStudy.getContributor() == null) {
963 setShortCuts(aStudy);
965 return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
969 * Returns modifiable initialized transient list of contributors of this study.
973 * @return the modifiable not null transient list of contributors of this study
975 public List<User> getModifiableContributors(final Study aStudy) {
976 if (aStudy.getContributor() == null) {
977 setShortCuts(aStudy);
979 return aStudy.getContributor(); // May be empty
983 * Returns the validation cycle of the given document type.
988 * the document type being subject of validation
989 * @return the validation cycle of the document, or null if not defined.
991 public ValidationCycle getValidationCycleOf(final Study aStudy,
992 final DocumentType type) {
993 if (aStudy.getValidationCycles() == null
994 || aStudy.getValidationCycles().isEmpty()) {
995 setShortCuts(aStudy);
997 ValidationCycle result = aStudy.getValidationCycles().get(
999 if (result == null) {
1000 if (type.isStepResult()) {
1001 result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
1003 if (result == null) {
1004 result = aStudy.getValidationCycles().get("built-in");
1011 * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
1016 * the user to look for
1017 * @return true if the given user is actor of this study.
1020 public boolean hasActor(final Study aStudy, final User user) {
1024 for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
1025 User involved = i.next();
1026 if (involved.equals(user)) {
1034 * Checks if the given user participates to this study. The Study staff includes the author and contributors.
1039 * the user to look for
1040 * @return true if the given user is actor of this study.
1041 * @see #getContributors()
1043 public boolean isStaffedBy(final Study aStudy, final User user) {
1047 if (aStudy == null) {
1050 if (aStudy.getAuthor() == null) {
1053 if (aStudy.getAuthor().equals(user)) {
1056 for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
1057 if (i.next().equals(user)) {
1065 * Initialize shortcuts of the study as its transient collections.
1070 public void loadWorkflow(final Study aStudy) {
1071 setShortCuts(aStudy);
1075 * Initialize shortcuts of the study as its transient collections.
1080 public void setShortCuts(final Study aStudy) {
1081 aStudy.getContributor().clear();
1082 aStudy.getValidationCycles().clear();
1083 aStudy.getActor().clear();
1085 // Get the contributors
1086 for (Iterator<Relation> i = aStudy.getRelations(
1087 ContributorRelation.class).iterator(); i.hasNext();) {
1088 ContributorRelation link = (ContributorRelation) i.next();
1089 aStudy.getContributor().add(link.getTo());
1091 // Get the validation cycles specific to this study
1092 for (Iterator<Relation> i = aStudy.getRelations(
1093 ValidationCycleRelation.class).iterator(); i.hasNext();) {
1094 ValidationCycleRelation link = (ValidationCycleRelation) i.next();
1095 aStudy.getValidationCycles().put(link.getDocumentType().getName(),
1096 link.getTo()); // The associated document type is necessarily not null in this
1099 // Get the validation cycles coming from the configured workflow and not overridden in this study
1100 for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
1101 .getAllValidationCycles().iterator(); i.hasNext();) {
1102 ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
1104 String type = cycle.getName();
1105 if (!aStudy.getValidationCycles().containsKey(type)) {
1106 aStudy.getValidationCycles().put(type,
1107 createValidationCycle(aStudy, cycle));
1110 // Get all corresponding actors
1111 for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
1112 .values().iterator(); i.hasNext();) {
1113 ValidationCycle cycle = i.next();
1114 User[] user = cycle.getAllActors();
1115 for (int j = 0; j < user.length; j++) {
1116 aStudy.getActor().add(user[j]);
1119 // Get all other actors
1120 for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
1122 Relation link = i.next();
1123 Class<?> kindof = link.getClass().getSuperclass();
1124 if (!kindof.equals(ActorRelation.class)) {
1127 aStudy.getActor().add(((ActorRelation) link).getTo());
1135 * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
1139 public void markStudyAsReference(final Study aStudy) {
1141 aStudy.setMarkreference(1);
1142 aStudy.setProgressState(ProgressState.TEMPLATE);
1143 getStudyDAO().merge(aStudy);
1150 * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
1154 public void removeStudyAsReference(final Study aStudy) {
1156 aStudy.setMarkreference(0);
1157 aStudy.setProgressState(ProgressState.APPROVED);
1158 getStudyDAO().merge(aStudy);
1164 * @see org.splat.service.StudyService#getDescription(java.lang.Long)
1167 @Transactional(readOnly = true)
1168 public String getDescription(final Long studyId)
1169 throws InvalidParameterException {
1170 if (studyId == null) {
1171 throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1173 Study study = _studyDAO.get(studyId);
1174 if (study == null) {
1175 throw new InvalidParameterException(PARAM_STUDY_ID, studyId
1178 return study.getDescription();
1184 * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
1188 public void setDescription(final Long studyId, final String descriptionText)
1189 throws InvalidParameterException {
1190 if (studyId == null) {
1191 throw new InvalidParameterException(PARAM_STUDY_ID, "null");
1193 Study study = _studyDAO.get(studyId);
1194 if (study == null) {
1195 throw new InvalidParameterException(PARAM_STUDY_ID, studyId
1198 study.setAttribute(new DescriptionAttribute(study, descriptionText));
1204 * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
1208 public boolean removeDescription(final Long studyId)
1209 throws InvalidParameterException {
1210 if (studyId == null) {
1211 throw new InvalidParameterException(PARAM_STUDY_ID, String
1214 Study study = _studyDAO.get(studyId);
1215 if (study == null) {
1216 throw new InvalidParameterException(PARAM_STUDY_ID, String
1219 return study.removeAttribute(study
1220 .getAttribute(DescriptionAttribute.class));
1227 * @see org.splat.service.StudyService#compare(java.util.List)
1230 public String compare(final List<DocToCompareDTO> docsList,
1231 final String userName) throws IncompatibleDataException {
1233 String axis1Name = "";
1234 String axis2Name = "";
1235 String chartTitle = "";
1236 String resultPath = "";
1238 XYSeriesCollection dataset = new XYSeriesCollection();
1240 Iterator<DocToCompareDTO> docListIter = docsList.iterator();
1242 for (; docListIter.hasNext();) {
1244 DocToCompareDTO docDTO = docListIter.next();
1245 String pathToFile = docDTO.getPathToFile();
1246 File compDocFile = new File(pathToFile);
1248 resultPath = pathToFile.substring(0, pathToFile.indexOf("vault"))
1249 + "downloads" + File.separator + userName + File.separator
1250 + "ComparisonResult.pdf";
1252 XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle()
1253 + " Scenario: " + docDTO.getScenarioTitle() + " Document: "
1254 + 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 LOG.error("Sorry, the file is not found.", e);
1311 JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // Title
1312 axis1Name, // x-axis Label
1313 axis2Name, // y-axis Label
1315 PlotOrientation.VERTICAL, // Plot Orientation
1316 true, // Show Legend
1317 true, // Use tooltips
1318 false // Configure chart to generate URLs?
1321 // export to PDF - file.
1324 Rectangle pagesize = new Rectangle(x, y);
1325 Document document = new Document(pagesize, 50, 50, 50, 50);
1328 File resFile = new File(resultPath);
1329 File resFolder = new File(resultPath.substring(0, resultPath
1330 .lastIndexOf(File.separator)));
1332 writer = PdfWriter.getInstance(document, new FileOutputStream(
1336 PdfContentByte cb = writer.getDirectContent();
1337 PdfTemplate tp = cb.createTemplate(x, y);
1338 Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
1339 chart.draw(g2, new java.awt.Rectangle(x, y));
1341 cb.addTemplate(tp, 0, 0);
1344 } catch (FileNotFoundException e) {
1345 LOG.error("Sorry, the file is not found.", e);
1346 } catch (DocumentException e) {
1347 LOG.error("Sorry, the DocumentException is thrown.", e);
1354 * Get project settings.
1356 * @return Project settings service
1358 private ProjectSettingsService getProjectSettings() {
1359 return _projectSettings;
1363 * Set project settings service.
1365 * @param projectSettingsService
1366 * project settings service
1368 public void setProjectSettings(
1369 final ProjectSettingsService projectSettingsService) {
1370 _projectSettings = projectSettingsService;
1374 * Get the projectElementService.
1376 * @return the projectElementService
1378 public ProjectElementService getProjectElementService() {
1379 return _projectElementService;
1383 * Set the projectElementService.
1385 * @param projectElementService
1386 * the projectElementService to set
1388 public void setProjectElementService(
1389 final ProjectElementService projectElementService) {
1390 _projectElementService = projectElementService;
1394 * Get the stepService.
1396 * @return the stepService
1398 public StepService getStepService() {
1399 return _stepService;
1403 * Set the stepService.
1405 * @param stepService
1406 * the stepService to set
1408 public void setStepService(final StepService stepService) {
1409 _stepService = stepService;
1413 * Get the indexService.
1415 * @return the indexService
1417 public IndexService getIndexService() {
1418 return _indexService;
1422 * Set the indexService.
1424 * @param indexService
1425 * the indexService to set
1427 public void setIndexService(final IndexService indexService) {
1428 _indexService = indexService;
1434 * @return the studyDAO
1436 public StudyDAO getStudyDAO() {
1444 * the studyDAO to set
1446 public void setStudyDAO(final StudyDAO studyDAO) {
1447 _studyDAO = studyDAO;
1451 * Get the iDBuilderDAO.
1453 * @return the iDBuilderDAO
1455 public IDBuilderDAO getIDBuilderDAO() {
1456 return _iDBuilderDAO;
1460 * Set the iDBuilderDAO.
1463 * the iDBuilderDAO to set
1465 public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
1466 _iDBuilderDAO = builderDAO;
1470 * Get the scenarioDAO.
1472 * @return the scenarioDAO
1474 public ScenarioDAO getScenarioDAO() {
1475 return _scenarioDAO;
1479 * Set the scenarioDAO.
1481 * @param scenarioDAO
1482 * the scenarioDAO to set
1484 public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1485 _scenarioDAO = scenarioDAO;
1489 * Get the validationCycleDAO.
1491 * @return the validationCycleDAO
1493 public ValidationCycleDAO getValidationCycleDAO() {
1494 return _validationCycleDAO;
1498 * Set the validationCycleDAO.
1500 * @param validationCycleDAO
1501 * the validationCycleDAO to set
1503 public void setValidationCycleDAO(
1504 final ValidationCycleDAO validationCycleDAO) {
1505 _validationCycleDAO = validationCycleDAO;
1509 * Get the documentTypeService.
1511 * @return the documentTypeService
1513 public DocumentTypeService getDocumentTypeService() {
1514 return _documentTypeService;
1518 * Set the documentTypeService.
1520 * @param documentTypeService
1521 * the documentTypeService to set
1523 public void setDocumentTypeService(
1524 final DocumentTypeService documentTypeService) {
1525 _documentTypeService = documentTypeService;
1529 * Get the userService.
1531 * @return the userService
1533 public UserService getUserService() {
1534 return _userService;
1538 * Set the userService.
1540 * @param userService
1541 * the userService to set
1543 public void setUserService(final UserService userService) {
1544 _userService = userService;
1550 * @see org.splat.service.StudyService#getComparableStudies()
1552 @Transactional(readOnly = true)
1553 public List<StudyFacadeDTO> getComparableStudies(final long userId)
1554 throws MismatchException {
1555 // retrieve the number of the "Analyze the results" step
1556 List<Step> allSteps = _projectSettings.getAllSteps();
1557 Step theAnalyzeStep = null;
1558 for (Step step : allSteps) {
1559 if (step.getKey().equals("postprocessing")) {
1560 theAnalyzeStep = step;
1563 if (theAnalyzeStep == null) { // TODO: throw some other exception
1564 throw new MismatchException(
1565 "no step with key 'postprocessing' found."
1566 + "Probably, customization settings have been changed.");
1569 List<Publication> publications = _publicationDAO.getFilteredList(
1570 "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep
1573 // split retrieved publications into groups by studies and scenarios
1574 Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
1575 Map<ProjectElement, List<Publication>> scenarioMap = new HashMap<ProjectElement, List<Publication>>();
1577 for (Publication publication : publications) {
1578 // filter out publications corresponding to a document of given step which is not a _result_ document
1579 if (!publication.value().getType().isResultOf(theAnalyzeStep)
1580 || !"srd".equals(publication.getSourceFile().getFormat())) {
1584 // check the study visibility to the user
1585 if (!isStaffedBy(publication.getOwnerStudy(), _userService
1586 .selectUser(userId))
1587 && Visibility.PUBLIC.equals(publication.getOwnerStudy()
1588 .getVisibility())) {
1592 Study study = publication.getOwnerStudy();
1593 ProjectElement scenario = publication.getOwner();
1595 Hibernate.initialize(scenario);
1596 if (scenario instanceof HibernateProxy) {
1597 scenario = (ProjectElement) ((HibernateProxy) scenario)
1598 .getHibernateLazyInitializer().getImplementation();
1601 if (!(scenario instanceof Scenario)) {
1602 throw new MismatchException(
1603 "publications from postprocessing step are supposed to have owner scenario");
1606 if (!studyMap.containsKey(study)) {
1607 studyMap.put(study, new ArrayList<ProjectElement>());
1610 if (!studyMap.get(study).contains(scenario)) {
1611 studyMap.get(study).add(scenario);
1614 if (!scenarioMap.containsKey(scenario)) {
1615 scenarioMap.put(scenario, new ArrayList<Publication>());
1617 scenarioMap.get(scenario).add(publication);
1620 // Create the result DTOs
1621 List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
1622 for (Study study : studyMap.keySet()) {
1624 StudyFacadeDTO studyDTO = new StudyFacadeDTO();
1625 studyDTO.setName(study.getTitle());
1626 studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
1627 result.add(studyDTO);
1629 for (ProjectElement scenario : studyMap.get(study)) {
1631 StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
1632 scenarioDTO.setName(scenario.getTitle());
1633 scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
1634 studyDTO.getScenarios().add(scenarioDTO);
1636 for (Publication publication : scenarioMap.get(scenario)) {
1638 DocumentDTO documentDTO = new DocumentDTO();
1639 documentDTO.setId(publication.getIndex());
1640 documentDTO.setTitle(publication.value().getTitle());
1642 scenarioDTO.getDocs().add(documentDTO);
1650 * Get the publicationDAO.
1652 * @return the publicationDAO
1654 public PublicationDAO getPublicationDAO() {
1655 return _publicationDAO;
1659 * Set the publicationDAO.
1661 * @param publicationDAO
1662 * the publicationDAO to set
1664 public void setPublicationDAO(final PublicationDAO publicationDAO) {
1665 _publicationDAO = publicationDAO;
1669 * Get the repositoryService.
1671 * @return the repositoryService
1673 public RepositoryService getRepositoryService() {
1674 return _repositoryService;
1678 * Set the repositoryService.
1680 * @param repositoryService
1681 * the repositoryService to set
1683 public void setRepositoryService(final RepositoryService repositoryService) {
1684 _repositoryService = repositoryService;
1688 * Get the documentDAO.
1690 * @return the documentDAO
1692 public DocumentDAO getDocumentDAO() {
1693 return _documentDAO;
1697 * Set the documentDAO.
1699 * @param documentDAO
1700 * the documentDAO to set
1702 public void setDocumentDAO(final DocumentDAO documentDAO) {
1703 _documentDAO = documentDAO;
1707 * Get the descriptionAttributeDAO.
1709 * @return the descriptionAttributeDAO
1711 public DescriptionAttributeDAO getDescriptionAttributeDAO() {
1712 return _descriptionAttributeDAO;
1716 * Set the descriptionAttributeDAO.
1718 * @param descriptionAttributeDAO
1719 * the descriptionAttributeDAO to set
1721 public void setDescriptionAttributeDAO(
1722 final DescriptionAttributeDAO descriptionAttributeDAO) {
1723 _descriptionAttributeDAO = descriptionAttributeDAO;
1727 * Get the usedByRelationDAO.
1729 * @return the usedByRelationDAO
1731 public UsedByRelationDAO getUsedByRelationDAO() {
1732 return _usedByRelationDAO;
1736 * Set the usedByRelationDAO.
1738 * @param usedByRelationDAO
1739 * the usedByRelationDAO to set
1741 public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
1742 _usedByRelationDAO = usedByRelationDAO;