]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java
Salome HOME
Remove study method is implemented. Unit test is added.
[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 import java.util.Set;
21
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;
64
65 /**
66  * Scenario service implementation.
67  * 
68  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
69  */
70 public class ScenarioServiceImpl implements ScenarioService {
71
72         /**
73          * The logger for the service.
74          */
75         public final static AppLogger LOG = AppLogger
76                         .getLogger(ScenarioServiceImpl.class);
77
78         /**
79          * Injected index service.
80          */
81         private IndexService _indexService;
82         /**
83          * Injected step service.
84          */
85         private StepService _stepService;
86         /**
87          * Injected study service.
88          */
89         private StudyService _studyService;
90         /**
91          * Injected publication service.
92          */
93         private PublicationService _publicationService;
94         /**
95          * Injected project element service.
96          */
97         private ProjectElementService _projectElementService;
98         /**
99          * Injected knowledge element DAO.
100          */
101         private KnowledgeElementDAO _knowledgeElementDAO;
102         /**
103          * Injected scenario DAO.
104          */
105         private ScenarioDAO _scenarioDAO;
106
107         /**
108          * Injected study DAO.
109          */
110         private StudyDAO _studyDAO;
111
112         /**
113          * Injected knowledge element service.
114          */
115         private KnowledgeElementTypeService _knowledgeElementTypeService;
116
117         /**
118          * Injected user service.
119          */
120         private UserService _userService;
121
122         /**
123          * Injected user DAO.
124          */
125         private UserDAO _userDAO;
126
127         /**
128          * Injected role DAO.
129          */
130         private RoleDAO _roleDAO;
131
132         /**
133          * Injected knowledge element type DAO.
134          */
135         private KnowledgeElementTypeDAO _knowledgeElementTypeDAO;
136
137         /**
138          * Injected simulation context service.
139          */
140         private SimulationContextService _simulationContextService;
141
142         /**
143          * Injected simulation context type service.
144          */
145         private SimulationContextTypeService _simulationContextTypeService;
146
147         /**
148          * Injected project service.
149          */
150         private ProjectSettingsService _projectSettings;
151
152         /**
153          * Injected document type service.
154          */
155         private DocumentTypeService _documentTypeService;
156
157         /**
158          * Get the projectElementService.
159          * 
160          * @return the projectElementService
161          */
162         public ProjectElementService getProjectElementService() {
163                 return _projectElementService;
164         }
165
166         /**
167          * Set the projectElementService.
168          * 
169          * @param projectElementService
170          *            the projectElementService to set
171          */
172         public void setProjectElementService(
173                         final ProjectElementService projectElementService) {
174                 _projectElementService = projectElementService;
175         }
176
177         /**
178          * Get the publicationService.
179          * 
180          * @return the publicationService
181          */
182         public PublicationService getPublicationService() {
183                 return _publicationService;
184         }
185
186         /**
187          * Set the publicationService.
188          * 
189          * @param publicationService
190          *            the publicationService to set
191          */
192         public void setPublicationService(
193                         final PublicationService publicationService) {
194                 _publicationService = publicationService;
195         }
196
197         /**
198          * Get the stepService.
199          * 
200          * @return the stepService
201          */
202         public StepService getStepService() {
203                 return _stepService;
204         }
205
206         /**
207          * Set the stepService.
208          * 
209          * @param stepService
210          *            the stepService to set
211          */
212         public void setStepService(final StepService stepService) {
213                 _stepService = stepService;
214         }
215
216         /**
217          * {@inheritDoc}
218          * 
219          * @see org.splat.service.ScenarioService#getScenarioInfo(long)
220          */
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());
229                 }
230                 // Get activities of the scenario
231                 Step[] steps = getProjectElementService().getSteps(scen);
232                 StepDTO stepDTO;
233                 DocumentDTO docDTO;
234                 String docType, fileFormat;
235                 String processing;
236                 boolean doImport;
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);
240                         res.add(stepDTO);
241                         if (LOG.isDebugEnabled()) {
242                                 LOG.debug("Step[" + stepDTO.getNumber()
243                                                 + "]: Number of documents: "
244                                                 + step.getDocuments().size());
245                         }
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()
250                                                 .getTitle());
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";
259                                 } else {
260                                         processing = "file-download";
261                                 }
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,
271                                                         fileFormat);
272                                         if (doImport && (!tag.isOutdated())) {
273                                                 processing = "file-import";
274                                         } else {
275                                                 processing = "file-download";
276                                         }
277                                         docDTO.addFile(aFile.getIndex(), aFile.getRelativePath(),
278                                                         aState, processing, false);
279                                 }
280                         }
281                 }
282                 return res;
283         }
284
285         /**
286          * {@inheritDoc}
287          * 
288          * @see org.splat.service.ScenarioService#createStudy(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
289          */
290         @Transactional
291         public long createStudy(final String username, final String title,
292                         final String productName, final String description)
293                         throws InvalidPropertyException, MissedPropertyException,
294                         MultiplyDefinedException {
295                 long id = 0;
296
297                 // Find the author
298                 User author = getUserService().selectUser(username);
299                 if (author == null) {
300                         // User is not found
301                         throw new InvalidPropertyException(MessageKeyEnum.USR_000001
302                                         .toString(), username);
303                 }
304
305                 // Set the study properties
306                 Study.Properties sprop = new Study.Properties();
307                 sprop.setTitle(title).setManager(author);
308                 sprop.setDescription(description);
309
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());
319                 }
320
321                 // Set a first scenario properties
322                 Scenario.Properties oprop = new Scenario.Properties();
323                 oprop.setTitle(I18nUtils.getMessageLocaleDefault("label.scenario")
324                                 + " 1");
325
326                 Study study = createStudy(sprop, oprop, cprop);
327                 id = study.getIndex();
328
329                 return id;
330         }
331
332         /**
333          * Create a new study with one scenario and "product" simulation context.
334          * 
335          * @param sprop
336          *            the study properties
337          * @param oprop
338          *            the scenario properties
339          * @param cprop
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
348          */
349         @Transactional
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);
365                 }
366                 return study;
367         }
368
369         /** 
370          * {@inheritDoc}
371          * @see org.splat.service.ScenarioService#assignStudyContext(java.lang.Long, java.lang.String, java.lang.String)
372          */
373         @Transactional
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);
379                 if (study == null) {
380                         throw new InvalidPropertyException(MessageKeyEnum.STD_000002
381                                         .toString(), studyId);
382                 }
383                 // Find the context type by its name
384                 SimulationContextType celt = getSimulationContextService().selectType(
385                                 ctxType);
386                 if (celt == null) {
387                         // Creation of a new context type
388                         celt = getSimulationContextTypeService().createType(ctxType,
389                                         getProjectElementService().getFirstStep(study).getStep());
390                 }
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);
400                 }
401         }
402
403         /**
404          * {@inheritDoc}
405          * 
406          * @see org.splat.service.ScenarioService#addKnowledgeElement(org.splat.dal.bo.som.Scenario,
407          *      org.splat.dal.bo.som.KnowledgeElement.Properties)
408          */
409         @Transactional
410         public KnowledgeElement addKnowledgeElement(final Scenario aScenarioDTO,
411                         final KnowledgeElement.Properties kprop)
412                         throws MissedPropertyException, InvalidPropertyException,
413                         MultiplyDefinedException {
414                 KnowledgeElement kelm = null;
415                 // try {
416                 long aScenarioId = aScenarioDTO.getIndex();
417                 if (LOG.isDebugEnabled()) {
418                         LOG
419                                         .debug("Add a knowledge element to the scenario #"
420                                                         + aScenarioId);
421                 }
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);
437                 }
438
439                 // Load the workflow for the parent study to take into account
440                 // all study actors durng reindexing.
441                 getStudyService().loadWorkflow(aScenario.getOwnerStudy());
442
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());
448                 }
449                 // } catch (IOException error) {
450                 // LOG.error("Unable to index the knowedge element '"
451                 // + kelm.getIndex() + "', reason:", error);
452                 // kelm = null;
453                 // }
454
455                 return kelm;
456         }
457
458         /**
459          * {@inheritDoc}
460          * 
461          * @see org.splat.service.ScenarioService#checkin(long, long, java.util.List)
462          */
463         @Transactional
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();
477
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>();
485                 // For each step DTO
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);
491                         }
492                         // Find a result document type of the step
493                         int i = 0;
494                         resType = null;
495                         do {
496                                 if (resTypes.get(i).isResultOf(
497                                                 getProjectSettings().getStep(stepDTO.getNumber()))) {
498                                         resType = resTypes.get(i);
499                                 }
500                                 i++;
501                         } while ((resType == null) && (i < resTypes.size()));
502
503                         // Find the appropriate scenario step
504                         Step step = findStep(stepDTO, steps);
505
506                         // Process each document of the step
507                         for (DocumentDTO doc : stepDTO.getDocs()) {
508                                 checkinDoc(step, doc, aUser, resType, aDate, newVersion,
509                                                 newVers, newDocs);
510                         }
511                 }
512
513                 // Set uses/used relations
514                 updateRelationsAfterCheckin(aScenario, newVersion, newVers, newDocs);
515
516                 // Mark the scenario as checked in
517                 checkin(aScenario);
518         }
519
520         /**
521          * Updated uses/used relations after checkin operation:<BR>
522          * <ul>
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>
526          * </ul>
527          * 
528          * @param aScenario
529          *            the checked in scenario
530          * @param newVersion
531          *            the mapping of documents existed before the checkin to their new created versions
532          * @param newVers
533          *            the list of publications of new created versions of documents existed before the checkin
534          * @param newDocs
535          *            the list of publications of new created documents not existed before the checkin
536          */
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);
547                         }
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);
555                                 }
556                                 // Build the appropriate relation for the new version.
557                                 newVer.addDependency(usedDoc);
558                         }
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');
568                                 }
569                         }
570                 }
571
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()
577                                         .getDefaultUses();
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);
586                                 }
587                         }
588                 }
589         }
590
591         /**
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.
595          * 
596          * @param step
597          *            the destination scenario step
598          * @param doc
599          *            the DTO of the document to checkin
600          * @param aUser
601          *            the user who performs checkin
602          * @param resType
603          *            the result document type of the given step
604          * @param aDate
605          *            timestamp of the checkin operation
606          * @param newVersion
607          *            the mapping of existing documents to their new created versions
608          * @param newVers
609          *            the list of publications of new created versions of existing documents
610          * @param newDocs
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
624          */
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());
637
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);
642
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);
646
647                         if (doc.getId() > 0) {
648                                 checkinExistingDoc(step, doc, dprop, fileFormat, upfile,
649                                                 newVersion, newVers);
650                         } else {
651
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));
657                                 } else {
658                                         dprop.setType(resType);
659                                 }
660                                 // New document title generation as <document type name>_N
661                                 String docname = dprop.getType().getName();
662                                 int i = 1;
663                                 for (Publication scenPub : step.getOwner().getDocums()) {
664                                         if (scenPub.value().getTitle().startsWith(docname)) {
665                                                 i++;
666                                         }
667                                 }
668                                 docname += "_" + i; // The generated new document title
669
670                                 dprop.setDescription("Checked in").setName(docname);
671                                 Publication newPub = getStepService().createDocument(step,
672                                                 dprop);
673
674                                 // Remember the new document
675                                 newDocs.add(newPub);
676
677                                 saveFile(newPub, step, upfile);
678                         }
679                 }
680         }
681
682         /**
683          * Check in existing document.
684          * 
685          * @param step
686          *            study step to check in
687          * @param doc
688          *            document DTO to check in
689          * @param dprop
690          *            document properties
691          * @param fileFormat
692          *            checked in file format
693          * @param upfile
694          *            the file to check in
695          * @param newVersion
696          *            the map of created versions during this check in
697          * @param newVers
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
711          */
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());
726                 if (pub == null) {
727                         throw new InvalidPropertyException(MessageKeyEnum.SCN_000002
728                                         .toString(), doc.getId());
729                 }
730                 if (pub.value() == null) {
731                         throw new MismatchException(MessageKeyEnum.SCN_000002.toString(),
732                                         doc.getId());
733                 }
734                 if (LOG.isDebugEnabled()) {
735                         LOG.debug("Old format: " + pub.value().getFormat()
736                                         + " => New format: " + fileFormat);
737                 }
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,
742                                         dprop);
743                         if (LOG.isDebugEnabled()) {
744                                 LOG.debug("Created document type: "
745                                                 + newPub.value().getType().getName() + ", format: "
746                                                 + newPub.value().getFormat());
747                         }
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
751                         newVers.add(newPub);
752
753                         saveFile(newPub, step, upfile);
754
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,
760                                                 fileFormat);
761                                 if (LOG.isDebugEnabled()) {
762                                         LOG.debug("Moving " + upfile.getName() + " to "
763                                                         + export.getTo().asFile().getPath());
764                                 }
765                                 upfile.renameTo(export.getTo().asFile());
766                         } else {
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());
772                         }
773                 }
774         }
775
776         /**
777          * Save the file in the vault and create its publication in the step.
778          * 
779          * @param newPub
780          *            the new publication to save
781          * @param step
782          *            the study step to publish the document
783          * @param upfile
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
789          */
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() + "\".");
798                 }
799                 if (updir.exists()) {
800                         if (updir.delete()) {
801                                 LOG.info(MessageKeyEnum.SCN_000003.toString(), updir
802                                                 .getAbsoluteFile(), step.getOwner().getIndex());
803                         } else {
804                                 throw new IOException(
805                                                 "Can't delete the existing destination file to move file from "
806                                                                 + upfile.getAbsolutePath() + " to "
807                                                                 + updir.getAbsolutePath());
808                         }
809                 }
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
814                 } else {
815                         throw new IOException("Can't move file from "
816                                         + upfile.getAbsolutePath() + " to "
817                                         + updir.getAbsolutePath());
818                 }
819         }
820
821         /**
822          * Find appropriate step in the array of scenario steps according to the given step DTO.
823          * 
824          * @param stepDTO
825          *            the stepDTO
826          * @param steps
827          *            scenario steps
828          * @return appropriate scenario step
829          * @throws InvalidPropertyException
830          *             if appropriate step is not found
831          */
832         private Step findStep(final StepDTO stepDTO, final Step[] steps)
833                         throws InvalidPropertyException {
834                 int i = 0;
835                 Step step = null;
836                 do {
837                         if (steps[i].getNumber() == stepDTO.getNumber()) {
838                                 step = steps[i];
839                         }
840                         i++;
841                 } while ((step == null) && (i < steps.length));
842
843                 if (step == null) {
844                         throw new InvalidPropertyException(MessageKeyEnum.SCN_000001
845                                         .toString(), stepDTO.getNumber());
846                 }
847                 return step;
848         }
849
850         /**
851          * {@inheritDoc}
852          * 
853          * @see org.splat.service.ScenarioService#checkin(long)
854          */
855         @Transactional
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);
862                 }
863                 checkin(aScenario);
864         }
865
866         /**
867          * Mark the scenario as checked in.
868          * 
869          * @param aScenario
870          *            the scenario to check in.
871          */
872         private void checkin(final Scenario aScenario) {
873                 aScenario.setUser(null);
874                 aScenario.setLastModificationDate(Calendar.getInstance().getTime());
875                 // getScenarioDAO().update(aScenario);
876         }
877
878         /**
879          * {@inheritDoc}
880          * 
881          * @see org.splat.service.ScenarioService#checkout(org.splat.dal.bo.som.Scenario, org.splat.dal.bo.kernel.User)
882          */
883         public boolean checkout(final Scenario aScenario, final User user) {
884                 boolean res = getStudyService().isStaffedBy(aScenario.getOwnerStudy(),
885                                 user);
886                 if (res) {
887                         aScenario.setUser(user);
888                         aScenario.setLastModificationDate(Calendar.getInstance().getTime());
889                         // RKV: getScenarioDAO().update(aScenario);
890                 }
891                 return res;
892         }
893
894         /**
895          * Mark the given scenario as checked out by the given user.
896          * 
897          * @param scenarioId
898          *            the scenario id
899          * @param userId
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
905          */
906         @Transactional
907         public void checkout(final long scenarioId, final long userId)
908                         throws InvalidPropertyException, NotApplicableException {
909                 User aUser = getUserService().selectUser(userId);
910                 if (aUser == null) {
911                         // User not found
912                         throw new InvalidPropertyException(MessageKeyEnum.USR_000001
913                                         .toString(), userId);
914                 }
915                 Scenario aScenario = getScenarioDAO().get(scenarioId);
916                 if (aScenario == null) {
917                         // Scenario not found
918                         throw new InvalidPropertyException(MessageKeyEnum.SCN_000006
919                                         .toString(), scenarioId);
920                 }
921                 boolean res = getStudyService().isStaffedBy(aScenario.getOwnerStudy(),
922                                 aUser);
923                 if (res) {
924                         if (aScenario.isCheckedout()
925                                         && (!aScenario.getUser().getUsername().equals(
926                                                         aUser.getUsername()))) {
927                                 throw new NotApplicableException(MessageKeyEnum.SCN_000008
928                                                 .toString(), scenarioId, aScenario.getUser()
929                                                 .getUsername());
930                         }
931                         aScenario.setUser(aUser);
932                         aScenario.setLastModificationDate(Calendar.getInstance().getTime());
933                 } else {
934                         // User doesn't participate in the scenario
935                         throw new NotApplicableException(MessageKeyEnum.SCN_000007
936                                         .toString(), aUser.getUsername(), scenarioId);
937                 }
938         }
939
940         /**
941          * {@inheritDoc}
942          * 
943          * @see org.splat.service.ScenarioService#copyContentsUpTo(org.splat.dal.bo.som.Scenario, org.splat.som.Step)
944          */
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++) {
950                         Step step = from[i];
951                         if (step.getNumber() > lastep.getNumber()) {
952                                 break;
953                         }
954
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);
961                         }
962                         List<SimulationContext> ctex = step.getAllSimulationContexts();
963                         for (Iterator<SimulationContext> j = ctex.iterator(); j.hasNext();) {
964                                 getStepService().addSimulationContext(to[i], j.next());
965                         }
966                 }
967         }
968
969         /**
970          * {@inheritDoc}
971          * 
972          * @see org.splat.service.ScenarioService#isEmpty(org.splat.dal.bo.som.Scenario)
973          */
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()) {
979                                 isEmp = false;
980                                 break;
981                         }
982                 }
983                 return isEmp;
984         }
985
986         /**
987          * @param scenario
988          * @return
989          */
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()) {
995                                 continue;
996                         }
997                         if (!mystep[i].isFinished()) {
998                                 return false;
999                         }
1000                         notempty = true;
1001                 }
1002                 return notempty;
1003         }
1004
1005         /**
1006          * {@inheritDoc}
1007          * 
1008          * @see org.splat.service.StudyService#addScenario(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Scenario.Properties)
1009          */
1010         @Transactional
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());
1016                 }
1017
1018                 Scenario scenario = new Scenario(sprop.setOwnerStudy(aStudy));
1019                 if (sprop.getBaseStep() != null) {
1020                         copyContentsUpTo(scenario, sprop.getBaseStep());
1021                 }
1022                 Scenario previous = sprop.getInsertAfter();
1023
1024                 if (previous == null) {
1025                         aStudy.getScenariiList().add(scenario);
1026                 } else {
1027                         aStudy.getScenariiList().add(
1028                                         aStudy.getScenariiList().indexOf(previous) + 1, scenario);
1029                 }
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
1035                 }
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
1045
1046                 kprop.setType(ucase).setTitle(aStudy.getTitle()).setValue(
1047                                 scenario.getTitle()).setAuthor(admin); // Internal Knowledge Element required by the validation process of
1048                 // knowledges
1049                 addKnowledgeElement(scenario, kprop);
1050                 return scenario;
1051         }
1052
1053         /**
1054          * Remove a knowledge element from a scenario.
1055          * 
1056          * @param scenario
1057          *            the scenario
1058          * @param kelm
1059          *            the knowledge element to remove
1060          * @return true if removal succeeded
1061          */
1062         @Transactional
1063         public boolean removeKnowledgeElement(final Scenario scenario,
1064                         final KnowledgeElement kelm) {
1065                 KnowledgeElement torem = scenario.getKnowledgeElement(kelm.getIndex());
1066                 boolean isOk = (torem != null);
1067                 if (isOk) {
1068                         isOk = scenario.getKnowledgeElements().remove(torem);
1069                         if (isOk) {
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);
1078                                 }
1079                                 // TODO: If the owner study is not private, remove the knowledge from the Lucene index
1080                         }
1081                 }
1082                 return isOk;
1083         }
1084
1085         /**
1086          * 
1087          * {@inheritDoc}
1088          * 
1089          * @see org.splat.service.ScenarioService#renameScenario(java.lang.String)
1090          */
1091         @Transactional
1092         public void renameScenario(final Scenario scenario) {
1093                 getScenarioDAO().merge(scenario);
1094         }
1095
1096         /**
1097          * Get the knowledgeElementDAO.
1098          * 
1099          * @return the knowledgeElementDAO
1100          */
1101         public KnowledgeElementDAO getKnowledgeElementDAO() {
1102                 return _knowledgeElementDAO;
1103         }
1104
1105         /**
1106          * Set the knowledgeElementDAO.
1107          * 
1108          * @param knowledgeElementDAO
1109          *            the knowledgeElementDAO to set
1110          */
1111         public void setKnowledgeElementDAO(
1112                         final KnowledgeElementDAO knowledgeElementDAO) {
1113                 _knowledgeElementDAO = knowledgeElementDAO;
1114         }
1115
1116         /**
1117          * Get the indexService.
1118          * 
1119          * @return the indexService
1120          */
1121         public IndexService getIndexService() {
1122                 return _indexService;
1123         }
1124
1125         /**
1126          * Set the indexService.
1127          * 
1128          * @param indexService
1129          *            the indexService to set
1130          */
1131         public void setIndexService(final IndexService indexService) {
1132                 _indexService = indexService;
1133         }
1134
1135         /**
1136          * Get the scenarioDAO.
1137          * 
1138          * @return the scenarioDAO
1139          */
1140         public ScenarioDAO getScenarioDAO() {
1141                 return _scenarioDAO;
1142         }
1143
1144         /**
1145          * Set the scenarioDAO.
1146          * 
1147          * @param scenarioDAO
1148          *            the scenarioDAO to set
1149          */
1150         public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
1151                 _scenarioDAO = scenarioDAO;
1152         }
1153
1154         /**
1155          * Get the studyDAO.
1156          * 
1157          * @return the studyDAO
1158          */
1159         public StudyDAO getStudyDAO() {
1160                 return _studyDAO;
1161         }
1162
1163         /**
1164          * Set the studyDAO.
1165          * 
1166          * @param studyDAO
1167          *            the studyDAO to set
1168          */
1169         public void setStudyDAO(final StudyDAO studyDAO) {
1170                 _studyDAO = studyDAO;
1171         }
1172
1173         /**
1174          * Get the knowledgeElementTypeService.
1175          * 
1176          * @return the knowledgeElementTypeService
1177          */
1178         public KnowledgeElementTypeService getKnowledgeElementTypeService() {
1179                 return _knowledgeElementTypeService;
1180         }
1181
1182         /**
1183          * Set the knowledgeElementTypeService.
1184          * 
1185          * @param knowledgeElementTypeService
1186          *            the knowledgeElementTypeService to set
1187          */
1188         public void setKnowledgeElementTypeService(
1189                         final KnowledgeElementTypeService knowledgeElementTypeService) {
1190                 _knowledgeElementTypeService = knowledgeElementTypeService;
1191         }
1192
1193         /**
1194          * Get the studyService.
1195          * 
1196          * @return the studyService
1197          */
1198         public StudyService getStudyService() {
1199                 return _studyService;
1200         }
1201
1202         /**
1203          * Set the studyService.
1204          * 
1205          * @param studyService
1206          *            the studyService to set
1207          */
1208         public void setStudyService(final StudyService studyService) {
1209                 _studyService = studyService;
1210         }
1211
1212         /**
1213          * Get the userService.
1214          * 
1215          * @return the userService
1216          */
1217         public UserService getUserService() {
1218                 return _userService;
1219         }
1220
1221         /**
1222          * Set the userService.
1223          * 
1224          * @param userService
1225          *            the userService to set
1226          */
1227         public void setUserService(final UserService userService) {
1228                 _userService = userService;
1229         }
1230
1231         /**
1232          * Get the userDAO.
1233          * 
1234          * @return the userDAO
1235          */
1236         public UserDAO getUserDAO() {
1237                 return _userDAO;
1238         }
1239
1240         /**
1241          * Set the userDAO.
1242          * 
1243          * @param userDAO
1244          *            the userDAO to set
1245          */
1246         public void setUserDAO(final UserDAO userDAO) {
1247                 _userDAO = userDAO;
1248         }
1249
1250         /**
1251          * Get the knowledgeElementTypeDAO.
1252          * 
1253          * @return the knowledgeElementTypeDAO
1254          */
1255         public KnowledgeElementTypeDAO getKnowledgeElementTypeDAO() {
1256                 return _knowledgeElementTypeDAO;
1257         }
1258
1259         /**
1260          * Set the knowledgeElementTypeDAO.
1261          * 
1262          * @param knowledgeElementTypeDAO
1263          *            the knowledgeElementTypeDAO to set
1264          */
1265         public void setKnowledgeElementTypeDAO(
1266                         final KnowledgeElementTypeDAO knowledgeElementTypeDAO) {
1267                 _knowledgeElementTypeDAO = knowledgeElementTypeDAO;
1268         }
1269
1270         /**
1271          * Get the simulationContextService.
1272          * 
1273          * @return the simulationContextService
1274          */
1275         public SimulationContextService getSimulationContextService() {
1276                 return _simulationContextService;
1277         }
1278
1279         /**
1280          * Set the simulationContextService.
1281          * 
1282          * @param simulationContextService
1283          *            the simulationContextService to set
1284          */
1285         public void setSimulationContextService(
1286                         final SimulationContextService simulationContextService) {
1287                 _simulationContextService = simulationContextService;
1288         }
1289
1290         /**
1291          * Get project settings.
1292          * 
1293          * @return Project settings service
1294          */
1295         private ProjectSettingsService getProjectSettings() {
1296                 return _projectSettings;
1297         }
1298
1299         /**
1300          * Set project settings service.
1301          * 
1302          * @param projectSettingsService
1303          *            project settings service
1304          */
1305         public void setProjectSettings(
1306                         final ProjectSettingsService projectSettingsService) {
1307                 _projectSettings = projectSettingsService;
1308         }
1309
1310         /**
1311          * Get the documentTypeService.
1312          * 
1313          * @return the documentTypeService
1314          */
1315         public DocumentTypeService getDocumentTypeService() {
1316                 return _documentTypeService;
1317         }
1318
1319         /**
1320          * Set the documentTypeService.
1321          * 
1322          * @param documentTypeService
1323          *            the documentTypeService to set
1324          */
1325         public void setDocumentTypeService(
1326                         final DocumentTypeService documentTypeService) {
1327                 _documentTypeService = documentTypeService;
1328         }
1329
1330         /**
1331          * Get the roleDAO.
1332          * 
1333          * @return the roleDAO
1334          */
1335         public RoleDAO getRoleDAO() {
1336                 return _roleDAO;
1337         }
1338
1339         /**
1340          * Set the roleDAO.
1341          * 
1342          * @param roleDAO
1343          *            the roleDAO to set
1344          */
1345         public void setRoleDAO(final RoleDAO roleDAO) {
1346                 _roleDAO = roleDAO;
1347         }
1348
1349         /**
1350          * Get the simulationContextTypeService.
1351          * 
1352          * @return the simulationContextTypeService
1353          */
1354         public SimulationContextTypeService getSimulationContextTypeService() {
1355                 return _simulationContextTypeService;
1356         }
1357
1358         /**
1359          * Set the simulationContextTypeService.
1360          * 
1361          * @param simulationContextTypeService
1362          *            the simulationContextTypeService to set
1363          */
1364         public void setSimulationContextTypeService(
1365                         final SimulationContextTypeService simulationContextTypeService) {
1366                 _simulationContextTypeService = simulationContextTypeService;
1367         }
1368
1369 }