1 /*****************************************************************************
5 * Creation date 06.10.2012
8 *****************************************************************************/
10 package org.splat.service;
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.Calendar;
15 import java.util.Date;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.List;
22 import org.hibernate.criterion.Order;
23 import org.hibernate.criterion.Restrictions;
24 import org.splat.common.properties.MessageKeyEnum;
25 import org.splat.dal.bo.kernel.Relation;
26 import org.splat.dal.bo.kernel.Role;
27 import org.splat.dal.bo.kernel.User;
28 import org.splat.dal.bo.som.ConvertsRelation;
29 import org.splat.dal.bo.som.Document;
30 import org.splat.dal.bo.som.DocumentType;
31 import org.splat.dal.bo.som.File;
32 import org.splat.dal.bo.som.KnowledgeElement;
33 import org.splat.dal.bo.som.KnowledgeElementType;
34 import org.splat.dal.bo.som.ProgressState;
35 import org.splat.dal.bo.som.Publication;
36 import org.splat.dal.bo.som.Scenario;
37 import org.splat.dal.bo.som.SimulationContext;
38 import org.splat.dal.bo.som.SimulationContextType;
39 import org.splat.dal.bo.som.Study;
40 import org.splat.dal.bo.som.UsedByRelation;
41 import org.splat.dal.bo.som.UsesRelation;
42 import org.splat.dal.bo.som.Document.Properties;
43 import org.splat.dal.dao.kernel.RoleDAO;
44 import org.splat.dal.dao.kernel.UserDAO;
45 import org.splat.dal.dao.som.KnowledgeElementDAO;
46 import org.splat.dal.dao.som.KnowledgeElementTypeDAO;
47 import org.splat.dal.dao.som.ScenarioDAO;
48 import org.splat.dal.dao.som.StudyDAO;
49 import org.splat.i18n.I18nUtils;
50 import org.splat.kernel.InvalidPropertyException;
51 import org.splat.kernel.MismatchException;
52 import org.splat.kernel.MissedPropertyException;
53 import org.splat.kernel.MultiplyDefinedException;
54 import org.splat.kernel.NotApplicableException;
55 import org.splat.log.AppLogger;
56 import org.splat.service.dto.DocumentDTO;
57 import org.splat.service.dto.FileDTO;
58 import org.splat.service.dto.StepDTO;
59 import org.splat.service.technical.IndexService;
60 import org.splat.service.technical.ProjectSettingsService;
61 import org.splat.som.Step;
62 import org.splat.util.BeanHelper;
63 import org.springframework.transaction.annotation.Transactional;
66 * Scenario service implementation.
68 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
70 public class ScenarioServiceImpl implements ScenarioService {
73 * The logger for the service.
75 public final static AppLogger LOG = AppLogger
76 .getLogger(ScenarioServiceImpl.class);
79 * Injected index service.
81 private IndexService _indexService;
83 * Injected step service.
85 private StepService _stepService;
87 * Injected study service.
89 private StudyService _studyService;
91 * Injected publication service.
93 private PublicationService _publicationService;
95 * Injected project element service.
97 private ProjectElementService _projectElementService;
99 * Injected knowledge element DAO.
101 private KnowledgeElementDAO _knowledgeElementDAO;
103 * Injected scenario DAO.
105 private ScenarioDAO _scenarioDAO;
108 * Injected study DAO.
110 private StudyDAO _studyDAO;
113 * Injected knowledge element service.
115 private KnowledgeElementTypeService _knowledgeElementTypeService;
118 * Injected user service.
120 private UserService _userService;
125 private UserDAO _userDAO;
130 private RoleDAO _roleDAO;
133 * Injected knowledge element type DAO.
135 private KnowledgeElementTypeDAO _knowledgeElementTypeDAO;
138 * Injected simulation context service.
140 private SimulationContextService _simulationContextService;
143 * Injected simulation context type service.
145 private SimulationContextTypeService _simulationContextTypeService;
148 * Injected project service.
150 private ProjectSettingsService _projectSettings;
153 * Injected document type service.
155 private DocumentTypeService _documentTypeService;
158 * Get the projectElementService.
160 * @return the projectElementService
162 public ProjectElementService getProjectElementService() {
163 return _projectElementService;
167 * Set the projectElementService.
169 * @param projectElementService
170 * the projectElementService to set
172 public void setProjectElementService(
173 final ProjectElementService projectElementService) {
174 _projectElementService = projectElementService;
178 * Get the publicationService.
180 * @return the publicationService
182 public PublicationService getPublicationService() {
183 return _publicationService;
187 * Set the publicationService.
189 * @param publicationService
190 * the publicationService to set
192 public void setPublicationService(
193 final PublicationService publicationService) {
194 _publicationService = publicationService;
198 * Get the stepService.
200 * @return the stepService
202 public StepService getStepService() {
207 * Set the stepService.
210 * the stepService to set
212 public void setStepService(final StepService stepService) {
213 _stepService = stepService;
219 * @see org.splat.service.ScenarioService#getScenarioInfo(long)
221 @Transactional(readOnly = true)
222 public List<StepDTO> getScenarioInfo(final long scenarioId) {
223 List<StepDTO> res = new ArrayList<StepDTO>();
224 // Get the scenario from the database by id
225 Scenario scen = getScenarioDAO().get(scenarioId);
226 if (LOG.isDebugEnabled()) {
227 LOG.debug("Scenario[" + scenarioId + "]: Number of publications: "
228 + scen.getDocums().size());
230 // Get activities of the scenario
231 Step[] steps = getProjectElementService().getSteps(scen);
234 String docType, fileFormat;
237 // For each activity create a step DTO and add it to the result list
238 for (Step step : steps) {
239 stepDTO = BeanHelper.copyBean(step.getStep(), StepDTO.class);
241 if (LOG.isDebugEnabled()) {
242 LOG.debug("Step[" + stepDTO.getNumber()
243 + "]: Number of documents: "
244 + step.getDocuments().size());
246 // For each publication of the activity create a document DTO.
247 // Each file is considered as a source file.
248 for (Publication tag : step.getDocuments()) {
249 docDTO = stepDTO.addDoc(tag.value().getIndex(), tag.value()
251 char aState = tag.getIsnew();
252 docType = tag.value().getType().getName();
253 // For each file of the document create a file DTO
254 // Process source file of the document
255 fileFormat = tag.value().getFile().getFormat();
256 doImport = getProjectSettings().doImport(docType, fileFormat);
257 if (doImport && (!tag.isOutdated())) {
258 processing = "file-import";
260 processing = "file-download";
262 File aFile = tag.value().getFile();
263 docDTO.addFile(aFile.getIndex(), aFile.getRelativePath(),
264 aState, processing, false);
265 // Process all exported files
266 for (Relation rel : tag.value().getRelations(
267 ConvertsRelation.class)) {
268 aFile = ((ConvertsRelation) rel).getTo();
269 fileFormat = aFile.getFormat();
270 doImport = getProjectSettings().doImport(docType,
272 if (doImport && (!tag.isOutdated())) {
273 processing = "file-import";
275 processing = "file-download";
277 docDTO.addFile(aFile.getIndex(), aFile.getRelativePath(),
278 aState, processing, false);
288 * @see org.splat.service.ScenarioService#createStudy(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
291 public long createStudy(final String username, final String title,
292 final String productName, final String description)
293 throws InvalidPropertyException, MissedPropertyException,
294 MultiplyDefinedException {
298 User author = getUserService().selectUser(username);
299 if (author == null) {
301 throw new InvalidPropertyException(MessageKeyEnum.USR_000001
302 .toString(), username);
305 // Set the study properties
306 Study.Properties sprop = new Study.Properties();
307 sprop.setTitle(title).setManager(author);
308 sprop.setDescription(description);
310 // Find the product simulation context
311 SimulationContextType productContextType = getSimulationContextService()
312 .selectType("product");
313 SimulationContext.Properties cprop = new SimulationContext.Properties();
314 cprop.setType(productContextType).setValue(productName);
315 SimulationContext productCtx = getSimulationContextService()
316 .selectSimulationContext(productContextType, productName);
317 if (productCtx != null) {
318 cprop.setIndex(productCtx.getIndex());
321 // Set a first scenario properties
322 Scenario.Properties oprop = new Scenario.Properties();
323 oprop.setTitle(I18nUtils.getMessageLocaleDefault("label.scenario")
326 Study study = createStudy(sprop, oprop, cprop);
327 id = study.getIndex();
333 * Create a new study with one scenario and "product" simulation context.
336 * the study properties
338 * the scenario properties
340 * the "product" simulation context properties
341 * @return the created study
342 * @throws MissedPropertyException
343 * if a mandatory property is missed
344 * @throws InvalidPropertyException
345 * if a property is invalid
346 * @throws MultiplyDefinedException
347 * if some property occurs several times
350 public Study createStudy(final Study.Properties sprop,
351 final Scenario.Properties oprop,
352 final SimulationContext.Properties cprop)
353 throws MissedPropertyException, InvalidPropertyException,
354 MultiplyDefinedException {
355 Study study = getStudyService().createStudy(sprop);
356 addScenario(study, oprop);
357 if (cprop.getIndex() == 0) { // Input of new project context
358 cprop.setType(getSimulationContextService().selectType("product"))
359 .setValue(cprop.getValue());
360 getStudyService().addProjectContext(study, cprop);
361 } else { // Selection of existing project context
362 SimulationContext context = getSimulationContextService()
363 .selectSimulationContext(cprop.getIndex());
364 getStudyService().addProjectContext(study, context);
371 * @see org.splat.service.ScenarioService#assignStudyContext(java.lang.Long, java.lang.String, java.lang.String)
374 public void assignStudyContext(final Long studyId, final String ctxType,
375 final String ctxValue) throws MissedPropertyException,
376 InvalidPropertyException, MultiplyDefinedException {
377 // Find the study by the given id
378 Study study = getStudyDAO().get(studyId);
380 throw new InvalidPropertyException(MessageKeyEnum.STD_000002
381 .toString(), studyId);
383 // Find the context type by its name
384 SimulationContextType celt = getSimulationContextService().selectType(
387 // Creation of a new context type
388 celt = getSimulationContextTypeService().createType(ctxType,
389 getProjectElementService().getFirstStep(study).getStep());
391 // Find the given context value of the given type
392 SimulationContext context = getSimulationContextService()
393 .selectSimulationContext(celt, ctxValue);
394 if (context == null) { // Input of a new project context
395 SimulationContext.Properties cprop = new SimulationContext.Properties();
396 cprop.setType(celt).setValue(ctxValue);
397 getStudyService().addProjectContext(study, cprop);
398 } else { // Selection of existing project context
399 getStudyService().addProjectContext(study, context);
406 * @see org.splat.service.ScenarioService#addKnowledgeElement(org.splat.dal.bo.som.Scenario,
407 * org.splat.dal.bo.som.KnowledgeElement.Properties)
410 public KnowledgeElement addKnowledgeElement(final Scenario aScenarioDTO,
411 final KnowledgeElement.Properties kprop)
412 throws MissedPropertyException, InvalidPropertyException,
413 MultiplyDefinedException {
414 KnowledgeElement kelm = null;
416 long aScenarioId = aScenarioDTO.getIndex();
417 if (LOG.isDebugEnabled()) {
419 .debug("Add a knowledge element to the scenario #"
422 // Get the persistent scenario.
423 Scenario aScenario = getScenarioDAO().get(aScenarioId);
424 // Get persistent objects for creating a new knowledge.
425 // TODO: Actions must use DTO instead of persistent objects.
426 getUserDAO().merge(kprop.getAuthor());
427 getKnowledgeElementTypeDAO().merge(kprop.getType());
428 // Create a transient knowledge element related to the given scenario.
429 kelm = new KnowledgeElement(kprop.setOwnerScenario(aScenario));
430 // Save the new knowledge in the database.
431 getKnowledgeElementDAO().create(kelm);
432 // Update scenario transient data.
433 if (kelm.getType().equals("usecase")) {
434 aScenarioDTO.setUcase(kelm);
435 } else if (aScenarioDTO.getKnowledgeElementsList() != null) { // If null, knowl will be initialized when needed
436 aScenarioDTO.getKnowledgeElementsList().add(kelm);
439 // Load the workflow for the parent study to take into account
440 // all study actors durng reindexing.
441 getStudyService().loadWorkflow(aScenario.getOwnerStudy());
443 // // Update the lucene index of knowledge elements.
444 // getIndexService().add(kelm);
445 if (LOG.isDebugEnabled()) {
446 LOG.debug("A knowledge element #" + kelm.getIndex()
447 + " is added to the scenario #" + aScenario.getIndex());
449 // } catch (IOException error) {
450 // LOG.error("Unable to index the knowedge element '"
451 // + kelm.getIndex() + "', reason:", error);
461 * @see org.splat.service.ScenarioService#checkin(long, long, java.util.List)
464 public void checkin(final long scenId, final long userId,
465 final List<StepDTO> scInfo) throws InvalidPropertyException,
466 MissedPropertyException, MultiplyDefinedException,
467 MismatchException, IOException, NotApplicableException {
468 // Get the scenario from the database by id
469 Scenario aScenario = getScenarioDAO().get(scenId);
470 // Get the user who perform this check-in operation
471 User aUser = getUserService().selectUser(userId);
472 // Get activities of the scenario
473 Step[] steps = getProjectElementService().getSteps(aScenario);
474 // Find result document types
475 List<DocumentType> resTypes = getDocumentTypeService()
476 .selectResultTypes();
478 // Keep newly created documents to create uses relations to results of a previous step.
479 // For each processed existing document keep its new version
480 Map<Document, Document> newVersion = new HashMap<Document, Document>();
481 // Created publications of new created versions of existing documents
482 List<Publication> newVers = new ArrayList<Publication>();
483 // The list of publications of new created documents not existing before the checkin
484 List<Publication> newDocs = new ArrayList<Publication>();
486 DocumentType resType;
487 Date aDate = new Date(); // The timestamp of the checkin operation
488 for (StepDTO stepDTO : scInfo) {
489 if (LOG.isDebugEnabled()) {
490 LOG.debug("Checkin the step:\n" + stepDTO);
492 // Find a result document type of the step
496 if (resTypes.get(i).isResultOf(
497 getProjectSettings().getStep(stepDTO.getNumber()))) {
498 resType = resTypes.get(i);
501 } while ((resType == null) && (i < resTypes.size()));
503 // Find the appropriate scenario step
504 Step step = findStep(stepDTO, steps);
506 // Process each document of the step
507 for (DocumentDTO doc : stepDTO.getDocs()) {
508 checkinDoc(step, doc, aUser, resType, aDate, newVersion,
513 // Set uses/used relations
514 updateRelationsAfterCheckin(aScenario, newVersion, newVers, newDocs);
516 // Mark the scenario as checked in
521 * Updated uses/used relations after checkin operation:<BR>
523 * <li>For each new version copy uses relations from the previous version.</li>
524 * <li>Outdate documents which depend from the previous version and were not checked in during this operation.</li>
525 * <li>For each new document create uses relation to the last versions of results of the previous step.</li>
529 * the checked in scenario
531 * the mapping of documents existed before the checkin to their new created versions
533 * the list of publications of new created versions of documents existed before the checkin
535 * the list of publications of new created documents not existed before the checkin
537 private void updateRelationsAfterCheckin(final Scenario aScenario,
538 final Map<Document, Document> newVersion,
539 final List<Publication> newVers, final List<Publication> newDocs) {
540 // For each new version copy uses relations from the previous version.
541 for (Publication newVer : newVers) {
542 // For each Uses relation of the previous version
543 Document prevDoc = newVer.value().getPreviousVersion();// prevVersion.get(newVer);
544 if (LOG.isDebugEnabled()) {
545 LOG.debug("Previous version for publication #"
546 + newVer.getIndex() + " is found: " + prevDoc);
548 List<Relation> usesRelations = prevDoc
549 .getRelations(UsesRelation.class);
550 for (Relation rel : usesRelations) {
551 // If used document has been also versioned then refer to its new version.
552 Document usedDoc = ((UsesRelation) rel).getTo();
553 if (newVersion.containsKey(usedDoc)) {
554 usedDoc = newVersion.get(usedDoc);
556 // Build the appropriate relation for the new version.
557 newVer.addDependency(usedDoc);
559 // Outdate documents which depend from the previous version and
560 // were not checked in during this operation.
561 // 1. Get all usedBy relations of the previous document version
562 for (Relation rel : prevDoc.getRelations(UsedByRelation.class)) {
563 Document using = ((UsedByRelation) rel).getTo();
564 // Check that not checked in dependent documents became outdated
565 Publication usingPub = aScenario.getPublication(using);
566 if (usingPub != null) { // if the document using the old version is still published
567 usingPub.setIsnew('O');
572 // For each new document create uses relation to the last versions of
573 // results of the previous step.
574 for (Publication newPub : newDocs) {
575 // Find used document type according to the configuration.
576 Set<DocumentType> usedTypes = newPub.value().getType()
578 // Find documents of used type in the previous study step.
579 for (Publication pub : aScenario.getDocums()) {
580 if ((pub.getStep().getNumber() <= newPub.getStep().getNumber())
581 && (!pub.isOutdated())
582 && usedTypes.contains(pub.value().getType())) {
583 // Create uses relation from the new document
584 // to the found document in the previous step.
585 newPub.addDependency(pub);
592 * Pure checkin of the document without creation of uses/usedBy relations. For an existing document a new version is created. New
593 * documents become published in the given step of the appropriate scenario. The appropriate uploaded file is attached to the created
594 * document and the document is published in the scenario. The publication of the old version is removed from the scenario.
597 * the destination scenario step
599 * the DTO of the document to checkin
601 * the user who performs checkin
603 * the result document type of the given step
605 * timestamp of the checkin operation
607 * the mapping of existing documents to their new created versions
609 * the list of publications of new created versions of existing documents
611 * the list of publications of new created documents not existing before the checkin
612 * @throws InvalidPropertyException
613 * if the scenario hasn't some of given steps or documents
614 * @throws IOException
615 * if a file can't be moved into the vault
616 * @throws MismatchException
617 * if version creation in some of steps is failed
618 * @throws MissedPropertyException
619 * if some mandatory property is missed when new document or new document version is created
620 * @throws MultiplyDefinedException
621 * if some property is defined several times when new document or new document version is created
622 * @throws NotApplicableException
623 * if failed saving of a new publication with a given state
625 private void checkinDoc(final Step step, final DocumentDTO doc,
626 final User aUser, final DocumentType resType, final Date aDate,
627 final Map<Document, Document> newVersion,
628 final List<Publication> newVers, final List<Publication> newDocs)
629 throws InvalidPropertyException, MismatchException,
630 MissedPropertyException, MultiplyDefinedException, IOException,
631 NotApplicableException {
632 if (doc.getFiles().size() > 0) {
633 Document.Properties dprop = new Document.Properties();
634 // NOTE: Process only the first attached file for each document
635 FileDTO file = doc.getFiles().get(0);
636 dprop.setLocalPath(file.getPath());
638 // Get document title as the file name
639 java.io.File upfile = new java.io.File(file.getPath());
640 String fileFormat = upfile.getName().substring(
641 upfile.getName().lastIndexOf('.') + 1);
643 // Attach the file via ConvertsRelation, create a new document or
644 // create a new version of the document
645 dprop.setAuthor(aUser).setDate(aDate).setFormat(fileFormat);
647 if (doc.getId() > 0) {
648 checkinExistingDoc(step, doc, dprop, fileFormat, upfile,
649 newVersion, newVers);
652 // Otherwise create a new document of the result type
653 // If result type is not found try to get type by file extension
654 if (resType == null) {
655 dprop.setType(getProjectSettings().getDefaultDocumentType(
656 step.getStep(), fileFormat));
658 dprop.setType(resType);
660 // New document title generation as <document type name>_N
661 String docname = dprop.getType().getName();
663 for (Publication scenPub : step.getOwner().getDocums()) {
664 if (scenPub.value().getTitle().startsWith(docname)) {
668 docname += "_" + i; // The generated new document title
670 dprop.setDescription("Checked in").setName(docname);
671 Publication newPub = getStepService().createDocument(step,
674 // Remember the new document
677 saveFile(newPub, step, upfile);
683 * Check in existing document.
686 * study step to check in
688 * document DTO to check in
690 * document properties
692 * checked in file format
694 * the file to check in
696 * the map of created versions during this check in
698 * the list of new versions created during this check in
699 * @throws InvalidPropertyException
700 * if publication of the document is not found in the step
701 * @throws MismatchException
702 * if the found publication does not point to a document
703 * @throws IOException
704 * if can not move the file into the vault
705 * @throws MultiplyDefinedException
706 * thrown by versionDocument
707 * @throws MissedPropertyException
708 * thrown by versionDocument
709 * @throws NotApplicableException
710 * if failed saving of a new publication with a given state
712 private void checkinExistingDoc(final Step step, final DocumentDTO doc,
713 final Properties dprop, final String fileFormat,
714 final java.io.File upfile,
715 final Map<Document, Document> newVersion,
716 final List<Publication> newVers) throws InvalidPropertyException,
717 MismatchException, MissedPropertyException,
718 MultiplyDefinedException, IOException, NotApplicableException {
719 // If the document already exists then
720 // Attach the file via ConvertsRelation if the extension of the
721 // new file differs from the old one.
722 // If file format (i.e. extension) is the same then create a new
723 // version of the document.
724 // Find the document publication
725 Publication pub = step.getDocument(doc.getId());
727 throw new InvalidPropertyException(MessageKeyEnum.SCN_000002
728 .toString(), doc.getId());
730 if (pub.value() == null) {
731 throw new MismatchException(MessageKeyEnum.SCN_000002.toString(),
734 if (LOG.isDebugEnabled()) {
735 LOG.debug("Old format: " + pub.value().getFormat()
736 + " => New format: " + fileFormat);
738 // If formats are same then create a new document version
739 if (pub.value().getFormat() != null
740 && pub.value().getFormat().equals(fileFormat)) {
741 Publication newPub = getStepService().versionDocument(step, pub,
743 if (LOG.isDebugEnabled()) {
744 LOG.debug("Created document type: "
745 + newPub.value().getType().getName() + ", format: "
746 + newPub.value().getFormat());
748 // Remeber the link from the old document to the new document version
749 newVersion.put(pub.value(), newPub.value());
750 // Remember the new version publication
753 saveFile(newPub, step, upfile);
755 } else { // If formats are different then attach the new file via ConvertsRelation
756 File attach = pub.value().getAttachedFile(fileFormat);
757 if (attach == null) {
758 // If there is no attachment with this extension then attach the new one
759 ConvertsRelation export = getPublicationService().attach(pub,
761 if (LOG.isDebugEnabled()) {
762 LOG.debug("Moving " + upfile.getName() + " to "
763 + export.getTo().asFile().getPath());
765 upfile.renameTo(export.getTo().asFile());
767 // If an attachment with this extension already exists then
768 // replace it by the new one
769 upfile.renameTo(attach.asFile());
770 // Update attached file modification date
771 attach.setDate(new Date());
777 * Save the file in the vault and create its publication in the step.
780 * the new publication to save
782 * the study step to publish the document
784 * the downloaded file
785 * @throws IOException
786 * if a file can't be moved into the vault
787 * @throws NotApplicableException
788 * if failed saving of a new publication with a given state
790 private void saveFile(final Publication newPub, final Step step,
791 final java.io.File upfile) throws IOException,
792 NotApplicableException {
793 // Attach the file to the created document
794 java.io.File updir = newPub.getSourceFile().asFile();
795 if (LOG.isDebugEnabled()) {
796 LOG.debug("Moving \"" + upfile.getName() + "\" to \""
797 + updir.getPath() + "\".");
799 if (updir.exists()) {
800 if (updir.delete()) {
801 LOG.info(MessageKeyEnum.SCN_000003.toString(), updir
802 .getAbsoluteFile(), step.getOwner().getIndex());
804 throw new IOException(
805 "Can't delete the existing destination file to move file from "
806 + upfile.getAbsolutePath() + " to "
807 + updir.getAbsolutePath());
810 if (upfile.renameTo(updir)) {
811 // Save the new publication in the scenario.
812 // The old publication is removed from the scenario here.
813 getPublicationService().saveAs(newPub, ProgressState.inWORK); // May throw FileNotFound if rename was not done
815 throw new IOException("Can't move file from "
816 + upfile.getAbsolutePath() + " to "
817 + updir.getAbsolutePath());
822 * Find appropriate step in the array of scenario steps according to the given step DTO.
828 * @return appropriate scenario step
829 * @throws InvalidPropertyException
830 * if appropriate step is not found
832 private Step findStep(final StepDTO stepDTO, final Step[] steps)
833 throws InvalidPropertyException {
837 if (steps[i].getNumber() == stepDTO.getNumber()) {
841 } while ((step == null) && (i < steps.length));
844 throw new InvalidPropertyException(MessageKeyEnum.SCN_000001
845 .toString(), stepDTO.getNumber());
853 * @see org.splat.service.ScenarioService#checkin(long)
856 public void checkin(final long scenarioId) throws InvalidPropertyException {
857 Scenario aScenario = getScenarioDAO().get(scenarioId);
858 if (aScenario == null) {
859 // Scenario not found
860 throw new InvalidPropertyException(MessageKeyEnum.SCN_000006
861 .toString(), scenarioId);
867 * Mark the scenario as checked in.
870 * the scenario to check in.
872 private void checkin(final Scenario aScenario) {
873 aScenario.setUser(null);
874 aScenario.setLastModificationDate(Calendar.getInstance().getTime());
875 // getScenarioDAO().update(aScenario);
881 * @see org.splat.service.ScenarioService#checkout(org.splat.dal.bo.som.Scenario, org.splat.dal.bo.kernel.User)
883 public boolean checkout(final Scenario aScenario, final User user) {
884 boolean res = getStudyService().isStaffedBy(aScenario.getOwnerStudy(),
887 aScenario.setUser(user);
888 aScenario.setLastModificationDate(Calendar.getInstance().getTime());
889 // RKV: getScenarioDAO().update(aScenario);
895 * Mark the given scenario as checked out by the given user.
900 * the id of the user performing the check out
901 * @throws InvalidPropertyException
902 * if the user or the scenario is not found in the database
903 * @throws NotApplicableException
904 * if the given user can not check out the scenario
907 public void checkout(final long scenarioId, final long userId)
908 throws InvalidPropertyException, NotApplicableException {
909 User aUser = getUserService().selectUser(userId);
912 throw new InvalidPropertyException(MessageKeyEnum.USR_000001
913 .toString(), userId);
915 Scenario aScenario = getScenarioDAO().get(scenarioId);
916 if (aScenario == null) {
917 // Scenario not found
918 throw new InvalidPropertyException(MessageKeyEnum.SCN_000006
919 .toString(), scenarioId);
921 boolean res = getStudyService().isStaffedBy(aScenario.getOwnerStudy(),
924 if (aScenario.isCheckedout()
925 && (!aScenario.getUser().getUsername().equals(
926 aUser.getUsername()))) {
927 throw new NotApplicableException(MessageKeyEnum.SCN_000008
928 .toString(), scenarioId, aScenario.getUser()
931 aScenario.setUser(aUser);
932 aScenario.setLastModificationDate(Calendar.getInstance().getTime());
934 // User doesn't participate in the scenario
935 throw new NotApplicableException(MessageKeyEnum.SCN_000007
936 .toString(), aUser.getUsername(), scenarioId);
943 * @see org.splat.service.ScenarioService#copyContentsUpTo(org.splat.dal.bo.som.Scenario, org.splat.som.Step)
945 public void copyContentsUpTo(final Scenario scenario, final Step lastep) {
946 Scenario base = (Scenario) lastep.getOwner();
947 Step[] from = getProjectElementService().getSteps(base);
948 Step[] to = getProjectElementService().getSteps(scenario);
949 for (int i = 0; i < from.length; i++) {
951 if (step.getNumber() > lastep.getNumber()) {
955 List<Publication> docs = step.getAllDocuments();
956 for (Iterator<Publication> j = docs.iterator(); j.hasNext();) {
957 Publication doc = getPublicationService().copy(j.next(),
958 scenario); // Creation of a new reference to the document
959 // Database.getSession().save(doc); Publications MUST be saved later through cascading when saving the scenario
960 getStepService().add(to[i], doc);
962 List<SimulationContext> ctex = step.getAllSimulationContexts();
963 for (Iterator<SimulationContext> j = ctex.iterator(); j.hasNext();) {
964 getStepService().addSimulationContext(to[i], j.next());
972 * @see org.splat.service.ScenarioService#isEmpty(org.splat.dal.bo.som.Scenario)
974 public boolean isEmpty(final Scenario scenario) {
975 Step[] mystep = getProjectElementService().getSteps(scenario);
976 boolean isEmp = true;
977 for (int i = 0; i < mystep.length; i++) {
978 if (mystep[i].isStarted()) {
990 public boolean isFinished(final Scenario scenario) {
991 Step[] mystep = getProjectElementService().getSteps(scenario);
992 boolean notempty = false; // If this is empty, this is not finished
993 for (int i = 0; i < mystep.length; i++) {
994 if (!mystep[i].isStarted()) {
997 if (!mystep[i].isFinished()) {
1008 * @see org.splat.service.StudyService#addScenario(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Scenario.Properties)
1011 public Scenario addScenario(final Study aStudy,
1012 final Scenario.Properties sprop) throws MissedPropertyException,
1013 InvalidPropertyException, MultiplyDefinedException {
1014 if (sprop.getManager() == null) {
1015 sprop.setManager(aStudy.getAuthor());
1018 Scenario scenario = new Scenario(sprop.setOwnerStudy(aStudy));
1019 if (sprop.getBaseStep() != null) {
1020 copyContentsUpTo(scenario, sprop.getBaseStep());
1022 Scenario previous = sprop.getInsertAfter();
1024 if (previous == null) {
1025 aStudy.getScenariiList().add(scenario);
1027 aStudy.getScenariiList().add(
1028 aStudy.getScenariiList().indexOf(previous) + 1, scenario);
1030 getStudyDAO().update(aStudy); // No need to update the Lucene index
1031 getScenarioDAO().create(scenario); // Must be done after updating this study because of the back reference to the study
1032 if (sprop.getBaseStep() != null) {
1033 // No need to update the Knowledge Element index as Knowledge Elements are not copied
1034 getProjectElementService().refresh(scenario); // Because saving the scenario changes the hashcode of copied Publications
1036 KnowledgeElementType ucase = getKnowledgeElementTypeService()
1037 .selectType("usecase");
1038 KnowledgeElement.Properties kprop = new KnowledgeElement.Properties();
1039 // TODO: Get appropriate user by its role: UserService.getAdmin();
1040 // User admin = getUserService().selectUser(1); // First user created when creating the database
1041 Role adminRole = getRoleDAO().getFilteredList(
1042 Restrictions.like("role", "%sysadmin%")).get(0);
1043 User admin = getUserDAO().getFilteredList(
1044 Restrictions.eq("role", adminRole), Order.asc("rid")).get(0); // First sysadmin in the database
1046 kprop.setType(ucase).setTitle(aStudy.getTitle()).setValue(
1047 scenario.getTitle()).setAuthor(admin); // Internal Knowledge Element required by the validation process of
1049 addKnowledgeElement(scenario, kprop);
1054 * Remove a knowledge element from a scenario.
1059 * the knowledge element to remove
1060 * @return true if removal succeeded
1063 public boolean removeKnowledgeElement(final Scenario scenario,
1064 final KnowledgeElement kelm) {
1065 KnowledgeElement torem = scenario.getKnowledgeElement(kelm.getIndex());
1066 boolean isOk = (torem != null);
1068 isOk = scenario.getKnowledgeElements().remove(torem);
1070 getScenarioDAO().merge(scenario);
1071 // Update of my transient data
1072 // RKV: These transient data are not used indeed.
1073 // RKV: List<KnowledgeElement> kelms = scenario.getKnowledgeByType().get(
1074 // RKV: kelm.getType().getIndex());
1075 // RKV: kelms.remove(torem);
1076 if (scenario.getKnowledgeElementsList() != null) {
1077 scenario.getKnowledgeElementsList().remove(torem);
1079 // TODO: If the owner study is not private, remove the knowledge from the Lucene index
1089 * @see org.splat.service.ScenarioService#renameScenario(java.lang.String)
1092 public void renameScenario(final Scenario scenario) {
1093 getScenarioDAO().merge(scenario);
1097 * Get the knowledgeElementDAO.
1099 * @return the knowledgeElementDAO
1101 public KnowledgeElementDAO getKnowledgeElementDAO() {
1102 return _knowledgeElementDAO;
1106 * Set the knowledgeElementDAO.
1108 * @param knowledgeElementDAO
1109 * the knowledgeElementDAO to set
1111 public void setKnowledgeElementDAO(
1112 final KnowledgeElementDAO knowledgeElementDAO) {
1113 _knowledgeElementDAO = knowledgeElementDAO;
1117 * Get the indexService.
1119 * @return the indexService
1121 public IndexService getIndexService() {
1122 return _indexService;
1126 * Set the indexService.
1128 * @param indexService
1129 * the indexService to set
1131 public void setIndexService(final IndexService indexService) {
1132 _indexService = indexService;
1136 * Get the scenarioDAO.
1138 * @return the scenarioDAO
1140 public ScenarioDAO getScenarioDAO() {
1141 return _scenarioDAO;
1145 * Set the scenarioDAO.
1147 * @param scenarioDAO
1148 * the scenarioDAO to set
1150 public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1151 _scenarioDAO = scenarioDAO;
1157 * @return the studyDAO
1159 public StudyDAO getStudyDAO() {
1167 * the studyDAO to set
1169 public void setStudyDAO(final StudyDAO studyDAO) {
1170 _studyDAO = studyDAO;
1174 * Get the knowledgeElementTypeService.
1176 * @return the knowledgeElementTypeService
1178 public KnowledgeElementTypeService getKnowledgeElementTypeService() {
1179 return _knowledgeElementTypeService;
1183 * Set the knowledgeElementTypeService.
1185 * @param knowledgeElementTypeService
1186 * the knowledgeElementTypeService to set
1188 public void setKnowledgeElementTypeService(
1189 final KnowledgeElementTypeService knowledgeElementTypeService) {
1190 _knowledgeElementTypeService = knowledgeElementTypeService;
1194 * Get the studyService.
1196 * @return the studyService
1198 public StudyService getStudyService() {
1199 return _studyService;
1203 * Set the studyService.
1205 * @param studyService
1206 * the studyService to set
1208 public void setStudyService(final StudyService studyService) {
1209 _studyService = studyService;
1213 * Get the userService.
1215 * @return the userService
1217 public UserService getUserService() {
1218 return _userService;
1222 * Set the userService.
1224 * @param userService
1225 * the userService to set
1227 public void setUserService(final UserService userService) {
1228 _userService = userService;
1234 * @return the userDAO
1236 public UserDAO getUserDAO() {
1244 * the userDAO to set
1246 public void setUserDAO(final UserDAO userDAO) {
1251 * Get the knowledgeElementTypeDAO.
1253 * @return the knowledgeElementTypeDAO
1255 public KnowledgeElementTypeDAO getKnowledgeElementTypeDAO() {
1256 return _knowledgeElementTypeDAO;
1260 * Set the knowledgeElementTypeDAO.
1262 * @param knowledgeElementTypeDAO
1263 * the knowledgeElementTypeDAO to set
1265 public void setKnowledgeElementTypeDAO(
1266 final KnowledgeElementTypeDAO knowledgeElementTypeDAO) {
1267 _knowledgeElementTypeDAO = knowledgeElementTypeDAO;
1271 * Get the simulationContextService.
1273 * @return the simulationContextService
1275 public SimulationContextService getSimulationContextService() {
1276 return _simulationContextService;
1280 * Set the simulationContextService.
1282 * @param simulationContextService
1283 * the simulationContextService to set
1285 public void setSimulationContextService(
1286 final SimulationContextService simulationContextService) {
1287 _simulationContextService = simulationContextService;
1291 * Get project settings.
1293 * @return Project settings service
1295 private ProjectSettingsService getProjectSettings() {
1296 return _projectSettings;
1300 * Set project settings service.
1302 * @param projectSettingsService
1303 * project settings service
1305 public void setProjectSettings(
1306 final ProjectSettingsService projectSettingsService) {
1307 _projectSettings = projectSettingsService;
1311 * Get the documentTypeService.
1313 * @return the documentTypeService
1315 public DocumentTypeService getDocumentTypeService() {
1316 return _documentTypeService;
1320 * Set the documentTypeService.
1322 * @param documentTypeService
1323 * the documentTypeService to set
1325 public void setDocumentTypeService(
1326 final DocumentTypeService documentTypeService) {
1327 _documentTypeService = documentTypeService;
1333 * @return the roleDAO
1335 public RoleDAO getRoleDAO() {
1343 * the roleDAO to set
1345 public void setRoleDAO(final RoleDAO roleDAO) {
1350 * Get the simulationContextTypeService.
1352 * @return the simulationContextTypeService
1354 public SimulationContextTypeService getSimulationContextTypeService() {
1355 return _simulationContextTypeService;
1359 * Set the simulationContextTypeService.
1361 * @param simulationContextTypeService
1362 * the simulationContextTypeService to set
1364 public void setSimulationContextTypeService(
1365 final SimulationContextTypeService simulationContextTypeService) {
1366 _simulationContextTypeService = simulationContextTypeService;