]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java
Salome HOME
The checkin from SALOME operation is updated (ScenarioService.checkin()). Versioning...
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / ScenarioServiceImpl.java
1 /*****************************************************************************
2  * Company         OPEN CASCADE
3  * Application     SIMAN
4  * File            $Id$ 
5  * Creation date   06.10.2012
6  * @author         $Author$
7  * @version        $Revision$
8  *****************************************************************************/
9
10 package org.splat.service;
11
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;
19 import java.util.Map;
20
21 import org.apache.log4j.Logger;
22 import org.splat.common.properties.MessageKeyEnum;
23 import org.splat.dal.bo.kernel.Relation;
24 import org.splat.dal.bo.kernel.User;
25 import org.splat.dal.bo.som.ConvertsRelation;
26 import org.splat.dal.bo.som.Document;
27 import org.splat.dal.bo.som.DocumentType;
28 import org.splat.dal.bo.som.File;
29 import org.splat.dal.bo.som.KnowledgeElement;
30 import org.splat.dal.bo.som.KnowledgeElementType;
31 import org.splat.dal.bo.som.ProgressState;
32 import org.splat.dal.bo.som.Publication;
33 import org.splat.dal.bo.som.Scenario;
34 import org.splat.dal.bo.som.SimulationContext;
35 import org.splat.dal.bo.som.Study;
36 import org.splat.dal.bo.som.UsesRelation;
37 import org.splat.dal.dao.kernel.UserDAO;
38 import org.splat.dal.dao.som.KnowledgeElementDAO;
39 import org.splat.dal.dao.som.KnowledgeElementTypeDAO;
40 import org.splat.dal.dao.som.ScenarioDAO;
41 import org.splat.dal.dao.som.StudyDAO;
42 import org.splat.kernel.InvalidPropertyException;
43 import org.splat.kernel.MismatchException;
44 import org.splat.kernel.MissedPropertyException;
45 import org.splat.kernel.MultiplyDefinedException;
46 import org.splat.kernel.NotApplicableException;
47 import org.splat.service.dto.DocumentDTO;
48 import org.splat.service.dto.FileDTO;
49 import org.splat.service.dto.StepDTO;
50 import org.splat.service.technical.IndexService;
51 import org.splat.service.technical.ProjectSettingsService;
52 import org.splat.som.Step;
53 import org.splat.util.BeanHelper;
54 import org.springframework.transaction.annotation.Transactional;
55
56 /**
57  * Scenario service implementation.
58  * 
59  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
60  */
61 public class ScenarioServiceImpl implements ScenarioService {
62
63         /**
64          * Logger for this class.
65          */
66         protected final static Logger LOG = Logger
67                         .getLogger(ScenarioServiceImpl.class);
68
69         /**
70          * Injected index service.
71          */
72         private IndexService _indexService;
73         /**
74          * Injected step service.
75          */
76         private StepService _stepService;
77         /**
78          * Injected study service.
79          */
80         private StudyService _studyService;
81         /**
82          * Injected publication service.
83          */
84         private PublicationService _publicationService;
85         /**
86          * Injected project element service.
87          */
88         private ProjectElementService _projectElementService;
89         /**
90          * Injected knowledge element DAO.
91          */
92         private KnowledgeElementDAO _knowledgeElementDAO;
93         /**
94          * Injected scenario DAO.
95          */
96         private ScenarioDAO _scenarioDAO;
97
98         /**
99          * Injected study DAO.
100          */
101         private StudyDAO _studyDAO;
102
103         /**
104          * Injected knowledge element service.
105          */
106         private KnowledgeElementTypeService _knowledgeElementTypeService;
107
108         /**
109          * Injected user service.
110          */
111         private UserService _userService;
112
113         /**
114          * Injected user DAO.
115          */
116         private UserDAO _userDAO;
117
118         /**
119          * Injected knowledge element type DAO.
120          */
121         private KnowledgeElementTypeDAO _knowledgeElementTypeDAO;
122
123         /**
124          * Injected simulation context service.
125          */
126         private SimulationContextService _simulationContextService;
127
128         /**
129          * Injected project service.
130          */
131         private ProjectSettingsService _projectSettings;
132
133         /**
134          * Injected document type service.
135          */
136         private DocumentTypeService _documentTypeService;
137
138         /**
139          * Get the projectElementService.
140          * 
141          * @return the projectElementService
142          */
143         public ProjectElementService getProjectElementService() {
144                 return _projectElementService;
145         }
146
147         /**
148          * Set the projectElementService.
149          * 
150          * @param projectElementService
151          *            the projectElementService to set
152          */
153         public void setProjectElementService(
154                         final ProjectElementService projectElementService) {
155                 _projectElementService = projectElementService;
156         }
157
158         /**
159          * Get the publicationService.
160          * 
161          * @return the publicationService
162          */
163         public PublicationService getPublicationService() {
164                 return _publicationService;
165         }
166
167         /**
168          * Set the publicationService.
169          * 
170          * @param publicationService
171          *            the publicationService to set
172          */
173         public void setPublicationService(
174                         final PublicationService publicationService) {
175                 _publicationService = publicationService;
176         }
177
178         /**
179          * Get the stepService.
180          * 
181          * @return the stepService
182          */
183         public StepService getStepService() {
184                 return _stepService;
185         }
186
187         /**
188          * Set the stepService.
189          * 
190          * @param stepService
191          *            the stepService to set
192          */
193         public void setStepService(final StepService stepService) {
194                 _stepService = stepService;
195         }
196
197         /**
198          * {@inheritDoc}
199          * 
200          * @see org.splat.service.ScenarioService#getScenarioInfo(long)
201          */
202         @Transactional(readOnly = true)
203         public List<StepDTO> getScenarioInfo(final long scenarioId) {
204                 List<StepDTO> res = new ArrayList<StepDTO>();
205                 // Get the scenario from the database by id
206                 Scenario scen = getScenarioDAO().get(scenarioId);
207                 if (LOG.isDebugEnabled()) {
208                         LOG.debug("Scenario[" + scenarioId + "]: Number of publications: "
209                                         + scen.getDocums().size());
210                 }
211                 // Get activities of the scenario
212                 Step[] steps = getProjectElementService().getSteps(scen);
213                 StepDTO stepDTO;
214                 DocumentDTO docDTO;
215                 String docType, fileFormat;
216                 String processing;
217                 boolean doImport;
218                 // For each activity create a step DTO and add it to the result list
219                 for (Step step : steps) {
220                         stepDTO = BeanHelper.copyBean(step.getStep(), StepDTO.class);
221                         res.add(stepDTO);
222                         if (LOG.isDebugEnabled()) {
223                                 LOG.debug("Step[" + stepDTO.getNumber()
224                                                 + "]: Number of documents: "
225                                                 + step.getDocuments().size());
226                         }
227                         // For each publication of the activity create a document DTO.
228                         // Each file is considered as a source file.
229                         for (Publication tag : step.getDocuments()) {
230                                 docDTO = stepDTO.addDoc(tag.value().getIndex(), tag.value()
231                                                 .getTitle());
232                                 char aState = tag.getIsnew();
233                                 docType = tag.value().getType().getName();
234                                 // For each file of the document create a file DTO
235                                 // Process source file of the document
236                                 fileFormat = tag.value().getFile().getFormat();
237                                 doImport = getProjectSettings().doImport(docType, fileFormat);
238                                 if (doImport && (!tag.isOutdated())) {
239                                         processing = "file-import";
240                                 } else {
241                                         processing = "file-download";
242                                 }
243                                 docDTO.addFile(tag.value().getFile().getRelativePath(), aState,
244                                                 processing, false);
245                                 // Process all exported files
246                                 for (Relation rel : tag.value().getRelations(
247                                                 ConvertsRelation.class)) {
248                                         File aFile = ((ConvertsRelation) rel).getTo();
249                                         fileFormat = aFile.getFormat();
250                                         doImport = getProjectSettings().doImport(docType,
251                                                         fileFormat);
252                                         if (doImport && (!tag.isOutdated())) {
253                                                 processing = "file-import";
254                                         } else {
255                                                 processing = "file-download";
256                                         }
257                                         docDTO.addFile(aFile.getRelativePath(), aState, processing,
258                                                         false);
259                                 }
260                         }
261                 }
262                 return res;
263         }
264
265         /**
266          * Create a new study with one scenario and "product" simulation context.
267          * 
268          * @param sprop
269          *            the study properties
270          * @param oprop
271          *            the scenario properties
272          * @param cprop
273          *            the "product" simulation context properties
274          * @return the created study
275          * @throws MissedPropertyException
276          *             if a mandatory property is missed
277          * @throws InvalidPropertyException
278          *             if a property is invalid
279          * @throws MultiplyDefinedException
280          *             if some property occurs several times
281          */
282         @Transactional
283         public Study createStudy(final Study.Properties sprop,
284                         final Scenario.Properties oprop,
285                         final SimulationContext.Properties cprop)
286                         throws MissedPropertyException, InvalidPropertyException,
287                         MultiplyDefinedException {
288                 Study study = getStudyService().createStudy(sprop);
289                 addScenario(study, oprop);
290                 if (cprop.getIndex() == 0) { // Input of new project context
291                         cprop.setType(getSimulationContextService().selectType("product"))
292                                         .setValue(cprop.getValue());
293                         getStudyService().addProjectContext(study, cprop);
294                 } else { // Selection of existing project context
295                         SimulationContext context = getSimulationContextService()
296                                         .selectSimulationContext(cprop.getIndex());
297                         getStudyService().addProjectContext(study, context);
298                 }
299                 return study;
300         }
301
302         /**
303          * {@inheritDoc}
304          * 
305          * @see org.splat.service.ScenarioService#addKnowledgeElement(org.splat.dal.bo.som.Scenario,
306          *      org.splat.dal.bo.som.KnowledgeElement.Properties)
307          */
308         @Transactional
309         public KnowledgeElement addKnowledgeElement(final Scenario aScenarioDTO,
310                         final KnowledgeElement.Properties kprop)
311                         throws MissedPropertyException, InvalidPropertyException,
312                         MultiplyDefinedException {
313                 KnowledgeElement kelm = null;
314                 try {
315                         long aScenarioId = aScenarioDTO.getIndex();
316                         if (LOG.isDebugEnabled()) {
317                                 LOG.debug("Add a knowledge element to the scenario #"
318                                                 + aScenarioId);
319                         }
320                         // Get the persistent scenario.
321                         Scenario aScenario = getScenarioDAO().get(aScenarioId);
322                         // Get persistent objects for creating a new knowledge.
323                         // TODO: Actions must use DTO instead of persistent objects.
324                         getUserDAO().merge(kprop.getAuthor());
325                         getKnowledgeElementTypeDAO().merge(kprop.getType());
326                         // Create a transient knowledge element related to the given scenario.
327                         kelm = new KnowledgeElement(kprop.setOwnerScenario(aScenario));
328                         // Save the new knowledge in the database.
329                         getKnowledgeElementDAO().create(kelm);
330                         // Update scenario transient data.
331                         if (kelm.getType().equals("usecase")) {
332                                 aScenarioDTO.setUcase(kelm);
333                         } else if (aScenarioDTO.getKnowledgeElementsList() != null) { // If null, knowl will be initialized when needed
334                                 aScenarioDTO.getKnowledgeElementsList().add(kelm);
335                         }
336
337                         // Load the workflow for the parent study to take into account
338                         // all study actors durng reindexing.
339                         getStudyService().loadWorkflow(aScenario.getOwnerStudy());
340
341                         // Update the lucene index of knowledge elements.
342                         getIndexService().add(kelm);
343                         if (LOG.isDebugEnabled()) {
344                                 LOG.debug("A knowledge element #" + kelm.getIndex()
345                                                 + " is added to the scenario #" + aScenario.getIndex());
346                         }
347                 } catch (IOException error) {
348                         LOG.error("Unable to index the knowedge element '"
349                                         + kelm.getIndex() + "', reason:", error);
350                         kelm = null;
351                 }
352
353                 return kelm;
354         }
355
356         /**
357          * Update the scenario in the database.
358          * 
359          * @param aScenario
360          *            the scenario to update
361          * @return true if updating succeeded
362          */
363         @Transactional
364         private boolean update(final Scenario aScenario) {
365                 boolean isOk = false;
366                 try {
367                         getScenarioDAO().update(aScenario); // Update of relational base
368                         isOk = true;
369                 } catch (Exception error) {
370                         LOG.error("Unable to re-index the knowledge element '"
371                                         + aScenario.getIndex() + "', reason:", error);
372                 }
373                 return isOk;
374         }
375
376         /**
377          * {@inheritDoc}
378          * 
379          * @see org.splat.service.ScenarioService#checkin(long, long, java.util.List)
380          */
381         @Transactional
382         public void checkin(final long scenId, final long userId,
383                         final List<StepDTO> scInfo) throws InvalidPropertyException,
384                         MissedPropertyException, MultiplyDefinedException,
385                         MismatchException, IOException, NotApplicableException {
386                 // Get the scenario from the database by id
387                 Scenario aScenario = getScenarioDAO().get(scenId);
388                 // Get the user who perform this check-in operation
389                 User aUser = getUserService().selectUser(userId);
390                 // Get activities of the scenario
391                 Step[] steps = getProjectElementService().getSteps(aScenario);
392                 // Find result document types
393                 List<DocumentType> resTypes = getDocumentTypeService()
394                                 .selectResultTypes();
395
396                 // For each processed existing document keep its new version
397                 Map<Document, Document> newVersion = new HashMap<Document, Document>();
398                 // Keep newly created documents to create uses relations to results of a previous step.
399                 List<Publication> newVers = new ArrayList<Publication>();
400                 List<Publication> newDocs = new ArrayList<Publication>();
401                 // For each step DTO
402                 DocumentType resType;
403                 java.io.File updir;
404                 Document.Properties dprop = new Document.Properties();
405                 Date aDate = new Date();
406                 for (StepDTO stepDTO : scInfo) {
407                         if (LOG.isDebugEnabled()) {
408                                 LOG.debug("Checkin the step:\n" + stepDTO);
409                         }
410                         // Find a result document type of the step
411                         int i = 0;
412                         resType = null;
413                         do {
414                                 if (resTypes.get(i).isResultOf(
415                                                 getProjectSettings().getStep(stepDTO.getNumber()))) {
416                                         resType = resTypes.get(i);
417                                 }
418                                 i++;
419                         } while ((resType == null) && (i < resTypes.size()));
420
421                         // Find the appropriate scenario step
422                         Step step = findStep(stepDTO, steps);
423
424                         // Process documents of the step
425                         for (DocumentDTO doc : stepDTO.getDocs()) {
426                                 if (doc.getFiles().size() > 0) {
427                                         // NOTE: Process only the first attached file for each document
428                                         FileDTO file = doc.getFiles().get(0);
429
430                                         // Get document title as the file name
431                                         java.io.File upfile = new java.io.File(file.getPath());
432                                         String fileFormat = upfile.getName().substring(
433                                                         upfile.getName().lastIndexOf('.') + 1);
434                                         String docname = upfile.getName().substring(0,
435                                                         upfile.getName().lastIndexOf('.'));
436
437                                         // Create a new document or a new version of the document
438                                         dprop.clear();
439                                         dprop.setAuthor(aUser).setDate(aDate);
440                                         Publication pub, newPub;
441
442                                         if (doc.getId() > 0) {
443                                                 // If the document already exists then create a new version of it
444                                                 // Find the document publication
445                                                 pub = step.getDocument(doc.getId());
446                                                 if (pub == null) {
447                                                         throw new InvalidPropertyException(
448                                                                         MessageKeyEnum.SCN_000002.toString(), doc
449                                                                                         .getId());
450                                                 }
451                                                 if (pub.value() == null) {
452                                                         throw new MismatchException(
453                                                                         MessageKeyEnum.SCN_000002.toString(), doc
454                                                                                         .getId());
455                                                 }
456                                                 newPub = getStepService().versionDocument(step, pub,
457                                                                 dprop);
458                                                 // Remeber the link from the old document to the new document version
459                                                 newVersion.put(pub.value(), newPub.value());
460                                                 // Remember the new version publication
461                                                 newVers.add(newPub);
462                                         } else {
463
464                                                 // Otherwise create a new document of the result type
465                                                 // If result type is not found try to get type by file extension
466                                                 if (resType == null) {
467                                                         dprop.setType(getProjectSettings()
468                                                                         .getDefaultDocumentType(step.getStep(),
469                                                                                         fileFormat));
470                                                 } else {
471                                                         dprop.setType(resType);
472                                                 }
473                                                 dprop.setDescription("Checked in").setName(docname)
474                                                                 .setFormat(fileFormat);
475                                                 newPub = getStepService().createDocument(step, dprop);
476
477                                                 // Remeber the new document
478                                                 newDocs.add(newPub);
479                                         }
480
481                                         // Attach the file to the created document
482                                         updir = newPub.getSourceFile().asFile();
483                                         if (LOG.isInfoEnabled()) {
484                                                 LOG.info("Moving \"" + upfile.getName() + "\" to \""
485                                                                 + updir.getPath() + "\".");
486                                         }
487                                         if (upfile.renameTo(updir)) {
488                                                 // Save the new publication in the scenario.
489                                                 // The old publication is removed from the scenario here.
490                                                 getPublicationService().saveAs(newPub,
491                                                                 ProgressState.inWORK); // May throw FileNotFound if rename was not done
492                                         }
493                                 }
494                         }
495                 }
496
497                 // Set uses/used relations
498
499                 // For each new version copy uses relations from the previous version.
500                 for (Publication newVer : newVers) {
501                         // For each Uses relation of the previous version
502                         Document prevDoc = newVer.value().getPreviousVersion();//prevVersion.get(newVer);
503                         if (LOG.isDebugEnabled()) {
504                                 LOG.debug("Previous version for publication #"
505                                                 + newVer.getIndex() + " is found: " + prevDoc);
506                         }
507                         List<Relation> usesRelations = prevDoc
508                                         .getRelations(UsesRelation.class);
509                         for (Relation rel : usesRelations) {
510                                 // If used document has been also versioned then refer to its new version.
511                                 Document usedDoc = ((UsesRelation) rel).getTo();
512                                 if (newVersion.containsKey(usedDoc)) {
513                                         usedDoc = newVersion.get(usedDoc);
514                                 }
515                                 // Build the appropriate relation for the new version.
516                                 newVer.addDependency(usedDoc);
517                         }
518                         // TODO: Outdate documents which depend from the previous version and were not checked in during this operation.
519
520                 }
521
522                 // For each new document create uses relation to the last versions of
523                 // results of the previous step.
524                 for (Publication newDoc : newDocs) {
525                         // Find used document type according to the configuration.
526                         // Find documents of used type in the previous study step.
527
528                         // Create uses relation from the new document
529                         // to the found document in the previous step.
530                         // newDoc.addDependency(to);
531                 }
532
533                 // Mark the scenario as checked in
534                 checkin(aScenario);
535         }
536
537         /**
538          * Find appropriate step in the array of scenario steps according to the given step DTO.
539          * 
540          * @param stepDTO
541          *            the stepDTO
542          * @param steps
543          *            scenario steps
544          * @return appropriate scenario step
545          * @throws InvalidPropertyException
546          *             if appropriate step is not found
547          */
548         private Step findStep(final StepDTO stepDTO, final Step[] steps)
549                         throws InvalidPropertyException {
550                 int i = 0;
551                 Step step = null;
552                 do {
553                         if (steps[i].getNumber() == stepDTO.getNumber()) {
554                                 step = steps[i];
555                         }
556                         i++;
557                 } while ((step == null) && (i < steps.length));
558
559                 if (step == null) {
560                         throw new InvalidPropertyException(MessageKeyEnum.SCN_000001
561                                         .toString(), stepDTO.getNumber());
562                 }
563                 return step;
564         }
565
566         /**
567          * {@inheritDoc}
568          * 
569          * @see org.splat.service.ScenarioService#checkin(org.splat.dal.bo.som.Scenario)
570          */
571         public void checkin(final Scenario aScenario) {
572                 aScenario.setUser(null);
573                 aScenario.setLastModificationDate(Calendar.getInstance().getTime());
574                 getScenarioDAO().update(aScenario);
575         }
576
577         /**
578          * {@inheritDoc}
579          * 
580          * @see org.splat.service.ScenarioService#checkout(org.splat.dal.bo.som.Scenario, org.splat.dal.bo.kernel.User)
581          */
582         public boolean checkout(final Scenario aScenario, final User user) {
583                 boolean res = getStudyService().isStaffedBy(aScenario.getOwnerStudy(),
584                                 user);
585                 if (res) {
586                         aScenario.setUser(user);
587                         aScenario.setLastModificationDate(Calendar.getInstance().getTime());
588                         getScenarioDAO().update(aScenario);
589                 }
590                 return res;
591         }
592
593         /**
594          * {@inheritDoc}
595          * 
596          * @see org.splat.service.ScenarioService#copyContentsUpTo(org.splat.dal.bo.som.Scenario, org.splat.som.Step)
597          */
598         public void copyContentsUpTo(final Scenario scenario, final Step lastep) {
599                 Scenario base = (Scenario) lastep.getOwner();
600                 Step[] from = getProjectElementService().getSteps(base);
601                 Step[] to = getProjectElementService().getSteps(scenario);
602                 for (int i = 0; i < from.length; i++) {
603                         Step step = from[i];
604                         if (step.getNumber() > lastep.getNumber()) {
605                                 break;
606                         }
607
608                         List<Publication> docs = step.getAllDocuments();
609                         for (Iterator<Publication> j = docs.iterator(); j.hasNext();) {
610                                 Publication doc = getPublicationService().copy(j.next(),
611                                                 scenario); // Creation of a new reference to the document
612                                 // Database.getSession().save(doc); Publications MUST be saved later through cascading when saving the scenario
613                                 getStepService().add(to[i], doc);
614                         }
615                         List<SimulationContext> ctex = step.getAllSimulationContexts();
616                         for (Iterator<SimulationContext> j = ctex.iterator(); j.hasNext();) {
617                                 getStepService().addSimulationContext(to[i], j.next());
618                         }
619                 }
620         }
621
622         /**
623          * {@inheritDoc}
624          * 
625          * @see org.splat.service.ScenarioService#isEmpty(org.splat.dal.bo.som.Scenario)
626          */
627         public boolean isEmpty(final Scenario scenario) {
628                 Step[] mystep = getProjectElementService().getSteps(scenario);
629                 boolean isEmp = true;
630                 for (int i = 0; i < mystep.length; i++) {
631                         if (mystep[i].isStarted()) {
632                                 isEmp = false;
633                                 break;
634                         }
635                 }
636                 return isEmp;
637         }
638
639         /**
640          * @param scenario
641          * @return
642          */
643         public boolean isFinished(final Scenario scenario) {
644                 Step[] mystep = getProjectElementService().getSteps(scenario);
645                 boolean notempty = false; // If this is empty, this is not finished
646                 for (int i = 0; i < mystep.length; i++) {
647                         if (!mystep[i].isStarted()) {
648                                 continue;
649                         }
650                         if (!mystep[i].isFinished()) {
651                                 return false;
652                         }
653                         notempty = true;
654                 }
655                 return notempty;
656         }
657
658         /**
659          * {@inheritDoc}
660          * 
661          * @see org.splat.service.StudyService#addScenario(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Scenario.Properties)
662          */
663         @Transactional
664         public Scenario addScenario(final Study aStudy,
665                         final Scenario.Properties sprop) throws MissedPropertyException,
666                         InvalidPropertyException, MultiplyDefinedException {
667                 if (sprop.getManager() == null) {
668                         sprop.setManager(aStudy.getAuthor());
669                 }
670
671                 Scenario scenario = new Scenario(sprop.setOwnerStudy(aStudy));
672                 if (sprop.getBaseStep() != null) {
673                         copyContentsUpTo(scenario, sprop.getBaseStep());
674                 }
675                 Scenario previous = sprop.getInsertAfter();
676
677                 if (previous == null) {
678                         aStudy.getScenariiList().add(scenario);
679                 } else {
680                         aStudy.getScenariiList().add(
681                                         aStudy.getScenariiList().indexOf(previous) + 1, scenario);
682                 }
683                 getStudyDAO().update(aStudy); // No need to update the Lucene index
684                 getScenarioDAO().create(scenario); // Must be done after updating this study because of the back reference to the study
685                 if (sprop.getBaseStep() != null) {
686                         // No need to update the Knowledge Element index as Knowledge Elements are not copied
687                         getProjectElementService().refresh(scenario); // Because saving the scenario changes the hashcode of copied Publications
688                 }
689                 KnowledgeElementType ucase = getKnowledgeElementTypeService()
690                                 .selectType("usecase");
691                 KnowledgeElement.Properties kprop = new KnowledgeElement.Properties();
692                 User admin = getUserService().selectUser(1); // First user created when creating the database
693                 kprop.setType(ucase).setTitle(aStudy.getTitle()).setValue(
694                                 scenario.getTitle()).setAuthor(admin); // Internal Knowledge Element required by the validation process of
695                 // knowledges
696                 addKnowledgeElement(scenario, kprop);
697                 return scenario;
698         }
699
700         /**
701          * Remove a knowledge element from a scenario.
702          * 
703          * @param scenario
704          *            the scenario
705          * @param kelm
706          *            the knowledge element to remove
707          * @return true if removal succeeded
708          */
709         public boolean removeKnowledgeElement(final Scenario scenario,
710                         final KnowledgeElement kelm) {
711                 KnowledgeElement torem = scenario.getKnowledgeElement(kelm.getIndex());
712                 if (torem == null) {
713                         return false;
714                 }
715                 boolean done = scenario.getKnowledgeElements().remove(torem);
716                 if (done) {
717                         // Update of my transient data
718                         // RKV: These transient data are not used indeed.
719                         // RKV: List<KnowledgeElement> kelms = scenario.getKnowledgeByType().get(
720                         // RKV: kelm.getType().getIndex());
721                         // RKV: kelms.remove(torem);
722                         if (scenario.getKnowledgeElementsList() != null) {
723                                 scenario.getKnowledgeElementsList().remove(torem);
724                         }
725                         getScenarioDAO().update(scenario);
726                         // TODO: If the owner study is not private, remove the knowledge from the Lucene index
727                         return true;
728                 } else {
729                         return false;
730                 }
731         }
732
733         /**
734          * Get the knowledgeElementDAO.
735          * 
736          * @return the knowledgeElementDAO
737          */
738         public KnowledgeElementDAO getKnowledgeElementDAO() {
739                 return _knowledgeElementDAO;
740         }
741
742         /**
743          * Set the knowledgeElementDAO.
744          * 
745          * @param knowledgeElementDAO
746          *            the knowledgeElementDAO to set
747          */
748         public void setKnowledgeElementDAO(
749                         final KnowledgeElementDAO knowledgeElementDAO) {
750                 _knowledgeElementDAO = knowledgeElementDAO;
751         }
752
753         /**
754          * Get the indexService.
755          * 
756          * @return the indexService
757          */
758         public IndexService getIndexService() {
759                 return _indexService;
760         }
761
762         /**
763          * Set the indexService.
764          * 
765          * @param indexService
766          *            the indexService to set
767          */
768         public void setIndexService(final IndexService indexService) {
769                 _indexService = indexService;
770         }
771
772         /**
773          * Get the scenarioDAO.
774          * 
775          * @return the scenarioDAO
776          */
777         public ScenarioDAO getScenarioDAO() {
778                 return _scenarioDAO;
779         }
780
781         /**
782          * Set the scenarioDAO.
783          * 
784          * @param scenarioDAO
785          *            the scenarioDAO to set
786          */
787         public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
788                 _scenarioDAO = scenarioDAO;
789         }
790
791         /**
792          * Get the studyDAO.
793          * 
794          * @return the studyDAO
795          */
796         public StudyDAO getStudyDAO() {
797                 return _studyDAO;
798         }
799
800         /**
801          * Set the studyDAO.
802          * 
803          * @param studyDAO
804          *            the studyDAO to set
805          */
806         public void setStudyDAO(final StudyDAO studyDAO) {
807                 _studyDAO = studyDAO;
808         }
809
810         /**
811          * Get the knowledgeElementTypeService.
812          * 
813          * @return the knowledgeElementTypeService
814          */
815         public KnowledgeElementTypeService getKnowledgeElementTypeService() {
816                 return _knowledgeElementTypeService;
817         }
818
819         /**
820          * Set the knowledgeElementTypeService.
821          * 
822          * @param knowledgeElementTypeService
823          *            the knowledgeElementTypeService to set
824          */
825         public void setKnowledgeElementTypeService(
826                         final KnowledgeElementTypeService knowledgeElementTypeService) {
827                 _knowledgeElementTypeService = knowledgeElementTypeService;
828         }
829
830         /**
831          * Get the studyService.
832          * 
833          * @return the studyService
834          */
835         public StudyService getStudyService() {
836                 return _studyService;
837         }
838
839         /**
840          * Set the studyService.
841          * 
842          * @param studyService
843          *            the studyService to set
844          */
845         public void setStudyService(final StudyService studyService) {
846                 _studyService = studyService;
847         }
848
849         /**
850          * Get the userService.
851          * 
852          * @return the userService
853          */
854         public UserService getUserService() {
855                 return _userService;
856         }
857
858         /**
859          * Set the userService.
860          * 
861          * @param userService
862          *            the userService to set
863          */
864         public void setUserService(final UserService userService) {
865                 _userService = userService;
866         }
867
868         /**
869          * Get the userDAO.
870          * 
871          * @return the userDAO
872          */
873         public UserDAO getUserDAO() {
874                 return _userDAO;
875         }
876
877         /**
878          * Set the userDAO.
879          * 
880          * @param userDAO
881          *            the userDAO to set
882          */
883         public void setUserDAO(final UserDAO userDAO) {
884                 _userDAO = userDAO;
885         }
886
887         /**
888          * Get the knowledgeElementTypeDAO.
889          * 
890          * @return the knowledgeElementTypeDAO
891          */
892         public KnowledgeElementTypeDAO getKnowledgeElementTypeDAO() {
893                 return _knowledgeElementTypeDAO;
894         }
895
896         /**
897          * Set the knowledgeElementTypeDAO.
898          * 
899          * @param knowledgeElementTypeDAO
900          *            the knowledgeElementTypeDAO to set
901          */
902         public void setKnowledgeElementTypeDAO(
903                         final KnowledgeElementTypeDAO knowledgeElementTypeDAO) {
904                 _knowledgeElementTypeDAO = knowledgeElementTypeDAO;
905         }
906
907         /**
908          * Get the simulationContextService.
909          * 
910          * @return the simulationContextService
911          */
912         public SimulationContextService getSimulationContextService() {
913                 return _simulationContextService;
914         }
915
916         /**
917          * Set the simulationContextService.
918          * 
919          * @param simulationContextService
920          *            the simulationContextService to set
921          */
922         public void setSimulationContextService(
923                         final SimulationContextService simulationContextService) {
924                 _simulationContextService = simulationContextService;
925         }
926
927         /**
928          * Get project settings.
929          * 
930          * @return Project settings service
931          */
932         private ProjectSettingsService getProjectSettings() {
933                 return _projectSettings;
934         }
935
936         /**
937          * Set project settings service.
938          * 
939          * @param projectSettingsService
940          *            project settings service
941          */
942         public void setProjectSettings(
943                         final ProjectSettingsService projectSettingsService) {
944                 _projectSettings = projectSettingsService;
945         }
946
947         /**
948          * Get the documentTypeService.
949          * 
950          * @return the documentTypeService
951          */
952         public DocumentTypeService getDocumentTypeService() {
953                 return _documentTypeService;
954         }
955
956         /**
957          * Set the documentTypeService.
958          * 
959          * @param documentTypeService
960          *            the documentTypeService to set
961          */
962         public void setDocumentTypeService(
963                         final DocumentTypeService documentTypeService) {
964                 _documentTypeService = documentTypeService;
965         }
966
967 }