Salome HOME
createStudy method is added for calling from Python.
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / ScenarioServiceImpl.java
index 55f75248b302d0b55e2ab19f165559a8a08cfcec..85815f726033facc427668f4627166c7733c1ac4 100644 (file)
@@ -35,15 +35,18 @@ import org.splat.dal.bo.som.ProgressState;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
 import org.splat.dal.bo.som.Study;
 import org.splat.dal.bo.som.UsedByRelation;
 import org.splat.dal.bo.som.UsesRelation;
+import org.splat.dal.bo.som.Document.Properties;
 import org.splat.dal.dao.kernel.RoleDAO;
 import org.splat.dal.dao.kernel.UserDAO;
 import org.splat.dal.dao.som.KnowledgeElementDAO;
 import org.splat.dal.dao.som.KnowledgeElementTypeDAO;
 import org.splat.dal.dao.som.ScenarioDAO;
 import org.splat.dal.dao.som.StudyDAO;
+import org.splat.i18n.I18nUtils;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.kernel.MismatchException;
 import org.splat.kernel.MissedPropertyException;
@@ -274,6 +277,53 @@ public class ScenarioServiceImpl implements ScenarioService {
                return res;
        }
 
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.ScenarioService#createStudy(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
+        */
+       @Override
+       public long createStudy(final String username, final String title,
+                       final String productName, final String description)
+                       throws InvalidPropertyException, MissedPropertyException,
+                       MultiplyDefinedException {
+               long id = 0;
+
+               // Find the author
+               User author = getUserService().selectUser(username);
+               if (author == null) {
+                       // User is not found
+                       throw new InvalidPropertyException(MessageKeyEnum.USR_000001
+                                       .toString(), username);
+               }
+
+               // Set the study properties
+               Study.Properties sprop = new Study.Properties();
+               sprop.setTitle(title).setManager(author);
+               sprop.setDescription(description);
+
+               // Find the product simulation context
+               SimulationContextType productContextType = getSimulationContextService()
+                               .selectType("product");
+               SimulationContext.Properties cprop = new SimulationContext.Properties();
+               cprop.setType(productContextType).setValue(productName);
+               SimulationContext productCtx = getSimulationContextService()
+                               .selectSimulationContext(productContextType, productName);
+               if (productCtx != null) {
+                       cprop.setIndex(productCtx.getIndex());
+               }
+
+               // Set a first scenario properties
+               Scenario.Properties oprop = new Scenario.Properties();
+               oprop.setTitle(I18nUtils.getMessageLocaleDefault("label.scenario")
+                               + " 1");
+
+               Study study = createStudy(sprop, oprop, cprop);
+               id = study.getIndex();
+
+               return id;
+       }
+
        /**
         * Create a new study with one scenario and "product" simulation context.
         * 
@@ -323,44 +373,45 @@ public class ScenarioServiceImpl implements ScenarioService {
                        throws MissedPropertyException, InvalidPropertyException,
                        MultiplyDefinedException {
                KnowledgeElement kelm = null;
-               try {
-                       long aScenarioId = aScenarioDTO.getIndex();
-                       if (LOG.isDebugEnabled()) {
-                               LOG.debug("Add a knowledge element to the scenario #"
-                                               + aScenarioId);
-                       }
-                       // Get the persistent scenario.
-                       Scenario aScenario = getScenarioDAO().get(aScenarioId);
-                       // Get persistent objects for creating a new knowledge.
-                       // TODO: Actions must use DTO instead of persistent objects.
-                       getUserDAO().merge(kprop.getAuthor());
-                       getKnowledgeElementTypeDAO().merge(kprop.getType());
-                       // Create a transient knowledge element related to the given scenario.
-                       kelm = new KnowledgeElement(kprop.setOwnerScenario(aScenario));
-                       // Save the new knowledge in the database.
-                       getKnowledgeElementDAO().create(kelm);
-                       // Update scenario transient data.
-                       if (kelm.getType().equals("usecase")) {
-                               aScenarioDTO.setUcase(kelm);
-                       } else if (aScenarioDTO.getKnowledgeElementsList() != null) { // If null, knowl will be initialized when needed
-                               aScenarioDTO.getKnowledgeElementsList().add(kelm);
-                       }
+               // try {
+               long aScenarioId = aScenarioDTO.getIndex();
+               if (LOG.isDebugEnabled()) {
+                       LOG
+                                       .debug("Add a knowledge element to the scenario #"
+                                                       + aScenarioId);
+               }
+               // Get the persistent scenario.
+               Scenario aScenario = getScenarioDAO().get(aScenarioId);
+               // Get persistent objects for creating a new knowledge.
+               // TODO: Actions must use DTO instead of persistent objects.
+               getUserDAO().merge(kprop.getAuthor());
+               getKnowledgeElementTypeDAO().merge(kprop.getType());
+               // Create a transient knowledge element related to the given scenario.
+               kelm = new KnowledgeElement(kprop.setOwnerScenario(aScenario));
+               // Save the new knowledge in the database.
+               getKnowledgeElementDAO().create(kelm);
+               // Update scenario transient data.
+               if (kelm.getType().equals("usecase")) {
+                       aScenarioDTO.setUcase(kelm);
+               } else if (aScenarioDTO.getKnowledgeElementsList() != null) { // If null, knowl will be initialized when needed
+                       aScenarioDTO.getKnowledgeElementsList().add(kelm);
+               }
 
-                       // Load the workflow for the parent study to take into account
-                       // all study actors durng reindexing.
-                       getStudyService().loadWorkflow(aScenario.getOwnerStudy());
+               // Load the workflow for the parent study to take into account
+               // all study actors durng reindexing.
+               getStudyService().loadWorkflow(aScenario.getOwnerStudy());
 
-                       // Update the lucene index of knowledge elements.
-                       getIndexService().add(kelm);
-                       if (LOG.isDebugEnabled()) {
-                               LOG.debug("A knowledge element #" + kelm.getIndex()
-                                               + " is added to the scenario #" + aScenario.getIndex());
-                       }
-               } catch (IOException error) {
-                       LOG.error("Unable to index the knowedge element '"
-                                       + kelm.getIndex() + "', reason:", error);
-                       kelm = null;
+               // // Update the lucene index of knowledge elements.
+               // getIndexService().add(kelm);
+               if (LOG.isDebugEnabled()) {
+                       LOG.debug("A knowledge element #" + kelm.getIndex()
+                                       + " is added to the scenario #" + aScenario.getIndex());
                }
+               // } catch (IOException error) {
+               // LOG.error("Unable to index the knowedge element '"
+               // + kelm.getIndex() + "', reason:", error);
+               // kelm = null;
+               // }
 
                return kelm;
        }
@@ -563,42 +614,20 @@ public class ScenarioServiceImpl implements ScenarioService {
                        Document.Properties dprop = new Document.Properties();
                        // NOTE: Process only the first attached file for each document
                        FileDTO file = doc.getFiles().get(0);
+                       dprop.setLocalPath(file.getPath());
 
                        // Get document title as the file name
                        java.io.File upfile = new java.io.File(file.getPath());
                        String fileFormat = upfile.getName().substring(
                                        upfile.getName().lastIndexOf('.') + 1);
 
-                       // Create a new document or a new version of the document
+                       // Attach the file via ConvertsRelation, create a new document or
+                       // create a new version of the document
                        dprop.setAuthor(aUser).setDate(aDate).setFormat(fileFormat);
-                       Publication pub, newPub;
 
                        if (doc.getId() > 0) {
-                               // If the document already exists then create a new version of it
-                               // Find the document publication
-                               pub = step.getDocument(doc.getId());
-                               if (pub == null) {
-                                       throw new InvalidPropertyException(
-                                                       MessageKeyEnum.SCN_000002.toString(), doc.getId());
-                               }
-                               if (pub.value() == null) {
-                                       throw new MismatchException(MessageKeyEnum.SCN_000002
-                                                       .toString(), doc.getId());
-                               }
-                               if (LOG.isDebugEnabled()) {
-                                       LOG.debug("Old format: " + pub.value().getFormat()
-                                                       + " => New format: " + fileFormat);
-                               }
-                               newPub = getStepService().versionDocument(step, pub, dprop);
-                               if (LOG.isDebugEnabled()) {
-                                       LOG.debug("Created document type: "
-                                                       + newPub.value().getType().getName() + ", format: "
-                                                       + newPub.value().getFormat());
-                               }
-                               // Remeber the link from the old document to the new document version
-                               newVersion.put(pub.value(), newPub.value());
-                               // Remember the new version publication
-                               newVers.add(newPub);
+                               checkinExistingDoc(step, doc, dprop, fileFormat, upfile,
+                                               newVersion, newVers);
                        } else {
 
                                // Otherwise create a new document of the result type
@@ -620,38 +649,154 @@ public class ScenarioServiceImpl implements ScenarioService {
                                docname += "_" + i; // The generated new document title
 
                                dprop.setDescription("Checked in").setName(docname);
-                               newPub = getStepService().createDocument(step, dprop);
+                               Publication newPub = getStepService().createDocument(step,
+                                               dprop);
 
                                // Remeber the new document
                                newDocs.add(newPub);
+
+                               saveFile(newPub, step, upfile);
                        }
+               }
+       }
 
-                       // Attach the file to the created document
-                       java.io.File updir = newPub.getSourceFile().asFile();
+       /**
+        * Check in existing document.
+        * 
+        * @param step
+        *            study step to check in
+        * @param doc
+        *            document DTO to check in
+        * @param dprop
+        *            document properties
+        * @param fileFormat
+        *            checked in file format
+        * @param upfile
+        *            the file to check in
+        * @param newVersion
+        *            the map of created versions during this check in
+        * @param newVers
+        *            the list of new versions created during this check in
+        * @throws InvalidPropertyException
+        *             if publication of the document is not found in the step
+        * @throws MismatchException
+        *             if the found publication does not point to a document
+        * @throws IOException
+        *             if can not move the file into the vault
+        * @throws MultiplyDefinedException
+        *             thrown by versionDocument
+        * @throws MissedPropertyException
+        *             thrown by versionDocument
+        * @throws NotApplicableException
+        *             if failed saving of a new publication with a given state
+        */
+       private void checkinExistingDoc(final Step step, final DocumentDTO doc,
+                       final Properties dprop, final String fileFormat,
+                       final java.io.File upfile,
+                       final Map<Document, Document> newVersion,
+                       final List<Publication> newVers) throws InvalidPropertyException,
+                       MismatchException, MissedPropertyException,
+                       MultiplyDefinedException, IOException, NotApplicableException {
+               // If the document already exists then
+               // Attach the file via ConvertsRelation if the extension of the
+               // new file differs from the old one.
+               // If file format (i.e. extension) is the same then create a new
+               // version of the document.
+               // Find the document publication
+               Publication pub = step.getDocument(doc.getId());
+               if (pub == null) {
+                       throw new InvalidPropertyException(MessageKeyEnum.SCN_000002
+                                       .toString(), doc.getId());
+               }
+               if (pub.value() == null) {
+                       throw new MismatchException(MessageKeyEnum.SCN_000002.toString(),
+                                       doc.getId());
+               }
+               if (LOG.isDebugEnabled()) {
+                       LOG.debug("Old format: " + pub.value().getFormat()
+                                       + " => New format: " + fileFormat);
+               }
+               // If formats are same then create a new document version
+               if (pub.value().getFormat() != null
+                               && pub.value().getFormat().equals(fileFormat)) {
+                       Publication newPub = getStepService().versionDocument(step, pub,
+                                       dprop);
                        if (LOG.isDebugEnabled()) {
-                               LOG.debug("Moving \"" + upfile.getName() + "\" to \""
-                                               + updir.getPath() + "\".");
+                               LOG.debug("Created document type: "
+                                               + newPub.value().getType().getName() + ", format: "
+                                               + newPub.value().getFormat());
                        }
-                       if (updir.exists()) {
-                               if (updir.delete()) {
-                                       LOG.info(MessageKeyEnum.SCN_000003.toString(), updir
-                                                       .getAbsoluteFile(), step.getOwner().getIndex());
-                               } else {
-                                       throw new IOException(
-                                                       "Can't delete the existing destination file to move file from "
-                                                                       + file.getPath() + " to "
-                                                                       + updir.getAbsolutePath());
+                       // Remeber the link from the old document to the new document version
+                       newVersion.put(pub.value(), newPub.value());
+                       // Remember the new version publication
+                       newVers.add(newPub);
+
+                       saveFile(newPub, step, upfile);
+
+               } else { // If formats are different then attach the new file via ConvertsRelation
+                       File attach = pub.value().getAttachedFile(fileFormat);
+                       if (attach == null) {
+                               // If there is no attachment with this extension then attach the new one
+                               ConvertsRelation export = getPublicationService().attach(pub,
+                                               fileFormat);
+                               if (LOG.isDebugEnabled()) {
+                                       LOG.debug("Moving " + upfile.getName() + " to "
+                                                       + export.getTo().asFile().getPath());
                                }
+                               upfile.renameTo(export.getTo().asFile());
+                       } else {
+                               // If an attachment with this extension already exists then
+                               // replace it by the new one
+                               upfile.renameTo(attach.asFile());
+                               // Update attached file modification date
+                               attach.setDate(new Date());
                        }
-                       if (upfile.renameTo(updir)) {
-                               // Save the new publication in the scenario.
-                               // The old publication is removed from the scenario here.
-                               getPublicationService().saveAs(newPub, ProgressState.inWORK); // May throw FileNotFound if rename was not done
+               }
+       }
+
+       /**
+        * Save the file in the vault and create its publication in the step.
+        * 
+        * @param newPub
+        *            the new publication to save
+        * @param step
+        *            the study step to publish the document
+        * @param upfile
+        *            the downloaded file
+        * @throws IOException
+        *             if a file can't be moved into the vault
+        * @throws NotApplicableException
+        *             if failed saving of a new publication with a given state
+        */
+       private void saveFile(final Publication newPub, final Step step,
+                       final java.io.File upfile) throws IOException,
+                       NotApplicableException {
+               // Attach the file to the created document
+               java.io.File updir = newPub.getSourceFile().asFile();
+               if (LOG.isDebugEnabled()) {
+                       LOG.debug("Moving \"" + upfile.getName() + "\" to \""
+                                       + updir.getPath() + "\".");
+               }
+               if (updir.exists()) {
+                       if (updir.delete()) {
+                               LOG.info(MessageKeyEnum.SCN_000003.toString(), updir
+                                               .getAbsoluteFile(), step.getOwner().getIndex());
                        } else {
-                               throw new IOException("Can't move file from " + file.getPath()
-                                               + " to " + updir.getAbsolutePath());
+                               throw new IOException(
+                                               "Can't delete the existing destination file to move file from "
+                                                               + upfile.getAbsolutePath() + " to "
+                                                               + updir.getAbsolutePath());
                        }
                }
+               if (upfile.renameTo(updir)) {
+                       // Save the new publication in the scenario.
+                       // The old publication is removed from the scenario here.
+                       getPublicationService().saveAs(newPub, ProgressState.inWORK); // May throw FileNotFound if rename was not done
+               } else {
+                       throw new IOException("Can't move file from "
+                                       + upfile.getAbsolutePath() + " to "
+                                       + updir.getAbsolutePath());
+               }
        }
 
        /**
@@ -918,6 +1063,17 @@ public class ScenarioServiceImpl implements ScenarioService {
                return isOk;
        }
 
+       /**
+        * 
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.ScenarioService#renameScenario(java.lang.String)
+        */
+       @Transactional
+       public void renameScenario(final Scenario scenario) {
+               getScenarioDAO().merge(scenario);
+       }
+
        /**
         * Get the knowledgeElementDAO.
         *