]> SALOME platform Git repositories - tools/siman.git/blobdiff - Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java
Salome HOME
Satisfy some PMD rules.
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / StudyServiceImpl.java
index 5cd8631a3b3d80d1c697355d9158751c4ada02f0..d75d3ccfa29cd440919d9bd6ac10de208b6a8753 100644 (file)
@@ -51,6 +51,7 @@ import org.splat.dal.bo.som.IDBuilder;
 import org.splat.dal.bo.som.ProgressState;
 import org.splat.dal.bo.som.ProjectElement;
 import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.ReaderRelation;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
 import org.splat.dal.bo.som.Study;
@@ -68,6 +69,7 @@ import org.splat.dal.dao.som.ScenarioDAO;
 import org.splat.dal.dao.som.StudyDAO;
 import org.splat.dal.dao.som.UsedByRelationDAO;
 import org.splat.dal.dao.som.ValidationCycleDAO;
+import org.splat.exception.BusinessException;
 import org.splat.exception.IncompatibleDataException;
 import org.splat.exception.InvalidParameterException;
 import org.splat.kernel.InvalidPropertyException;
@@ -78,12 +80,14 @@ import org.splat.log.AppLogger;
 import org.splat.service.dto.DocToCompareDTO;
 import org.splat.service.dto.DocumentDTO;
 import org.splat.service.dto.StudyFacadeDTO;
+import org.splat.service.dto.UserDTO;
 import org.splat.service.technical.IndexService;
 import org.splat.service.technical.ProjectSettingsService;
 import org.splat.service.technical.ProjectSettingsServiceImpl;
 import org.splat.service.technical.RepositoryService;
 import org.splat.service.technical.ProjectSettingsService.Step;
 import org.splat.som.Revision;
+import org.splat.util.BeanHelper;
 import org.springframework.transaction.annotation.Transactional;
 
 import com.lowagie.text.Document;
@@ -195,7 +199,9 @@ public class StudyServiceImpl implements StudyService {
        @Transactional
        public Study selectStudy(final long index) {
                Study result = getStudyDAO().get(index);
-               loadWorkflow(result);
+               if (result != null) {
+                       loadWorkflow(result);
+               }
                return result;
        }
 
@@ -240,14 +246,16 @@ public class StudyServiceImpl implements StudyService {
 
                        // Remove all relations of study documents
                        for (org.splat.dal.bo.som.Document doc : docums) {
-                               LOG.debug("Found doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
+                               LOG.debug("Found doc: " + doc.getTitle() + " ["
+                                               + doc.getReference() + "]" + " [" + doc.getRid() + "]");
                                doc.getAllRelations().clear();
                        }
                        getDocumentDAO().flush();
 
                        // Remove all documents of the study
                        for (org.splat.dal.bo.som.Document doc : docums) {
-                               LOG.debug("Remove doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
+                               LOG.debug("Remove doc: " + doc.getTitle() + " ["
+                                               + doc.getReference() + "]" + " [" + doc.getRid() + "]");
                                getDocumentDAO().delete(doc);
                        }
                }
@@ -330,13 +338,25 @@ public class StudyServiceImpl implements StudyService {
         */
        @Transactional
        public boolean addContributor(final Study aStudy, final User user) {
-               List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
-               for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
-                       User present = i.next();
-                       if (present.equals(user)) {
-                               return false;
+               List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
+               
+               if(contributors.contains(user)) {
+                       return false;
+               }
+               
+               //Remove user from readers
+               try {
+                       List<UserDTO> readers = getReaders(aStudy.getIndex());
+                       for(UserDTO reader : readers) {
+                               if(reader.getIndex() == user.getIndex()) {
+                                       //user must be the actual user in the relationship object in the aStudy object for this to work
+                                       aStudy.removeRelation(ReaderRelation.class, user);
+                               }
                        }
+               } catch(InvalidParameterException e) {
+                       LOG.error(e.getMessage(), e);   
                }
+               
                boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
 
                aStudy.addRelation(new ContributorRelation(aStudy, user));
@@ -357,6 +377,7 @@ public class StudyServiceImpl implements StudyService {
         * @see #isPublic()
         * @see Publication#approve(Date)
         */
+       @Transactional
        public boolean moveToReference(final Study aStudy) {
                if (aStudy.getProgressState() != ProgressState.APPROVED) {
                        return false;
@@ -377,6 +398,7 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
         */
+       @Transactional
        public boolean update(final Study aStudy, final Properties sprop)
                        throws InvalidPropertyException {
                if (sprop.getTitle() != null) {
@@ -399,17 +421,9 @@ public class StudyServiceImpl implements StudyService {
         *            the document
         * @return true if the document is published in the study
         */
-/*     private boolean publishes(final Study aStudy, final Document doc) {
-               if (!aStudy.publishes(doc)) {
-                       Scenario[] scene = aStudy.getScenarii();
-                       for (int i = 0; i < scene.length; i++) {
-                               if (scene[i].publishes(doc)) {
-                                       return true;
-                               }
-                       }
-               }
-               return false;
-       }
+       /*
+        * private boolean publishes(final Study aStudy, final Document doc) { if (!aStudy.publishes(doc)) { Scenario[] scene =
+        * aStudy.getScenarii(); for (int i = 0; i < scene.length; i++) { if (scene[i].publishes(doc)) { return true; } } } return false; }
         */
        /**
         * {@inheritDoc}
@@ -418,20 +432,13 @@ public class StudyServiceImpl implements StudyService {
         */
        @Transactional
        public boolean removeContributor(final Study aStudy, final User... users) {
-               List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
+               List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
                Boolean done = false;
-               for (int i = 0; i < users.length; i++) {
-                       User user = users[i];
-                       for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
-                               User present = j.next();
-                               if (!present.equals(user)) {
-                                       continue;
-                               }
-
+               for(User user : users) {
+                       if(contributors.contains(user)) {
                                aStudy.removeRelation(ContributorRelation.class, user);
-                               j.remove(); // Updates the contributor shortcut
+                               contributors.remove(user);
                                done = true;
-                               break;
                        }
                }
                if (done) {
@@ -445,6 +452,7 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
         */
+       @Transactional
        public boolean removeProjectContext(final Study aStudy,
                        final SimulationContext context) {
                boolean done = getStepService().removeSimulationContext(
@@ -483,12 +491,12 @@ public class StudyServiceImpl implements StudyService {
 
                                ValidationCycleRelation link = cycle.getContext();
                                aStudy.addRelation(link);
+                               getValidationCycleDAO().flush();
                                aStudyDTO.getAllRelations().add(link); // RKV
 
                                validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
-                       } catch (Exception error) {
-                               LOG.error("Unable to re-index Knowledge Elements, reason:",
-                                               error);
+                       } catch (BusinessException error) {
+                               LOG.error("Unable to create validation cycle, reason:", error);
                                return;
                        }
                }
@@ -504,6 +512,7 @@ public class StudyServiceImpl implements StudyService {
         *            a study to demote
         * @return true if the demotion succeeded.
         */
+       @Transactional
        public boolean demote(final Study aStudy) {
                if (aStudy.getProgressState() == ProgressState.inCHECK) {
                        aStudy.setProgressState(ProgressState.inDRAFT);
@@ -600,13 +609,12 @@ public class StudyServiceImpl implements StudyService {
         *            the study to update
         * @return true if the study is updated successfully
         */
-       @Transactional
        private boolean update(final Study aStudy) {
                boolean isOk = false;
                try {
                        getStudyDAO().merge(aStudy); // Update of relational base
                        setShortCuts(aStudy); // RKV: initialize transient actors set
-                       // RKV: getIndex().update(aStudy); // Update of Lucene index
+                       //RKV: getIndex().update(aStudy); // Update of Lucene index
                        isOk = true;
                } catch (Exception e) {
                        LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
@@ -754,25 +762,20 @@ public class StudyServiceImpl implements StudyService {
         * @return true if reindexing succeeded
         */
        private boolean updateKnowledgeElementsIndex(final Study aStudy) {
-               // boolean isOk = false;
-               // try {
-               // IndexService lucin = getIndex();
-               //
-               // for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
-               // .hasNext();) {
-               // Scenario scene = i.next();
-               // for (Iterator<KnowledgeElement> j = scene
-               // .getAllKnowledgeElements().iterator(); j.hasNext();) {
-               // KnowledgeElement kelm = j.next();
-               // lucin.update(kelm);
-               // }
-               // }
-               // isOk = true;
-               // } catch (Exception error) {
-               // LOG.error("Unable to re-index Knowledge Elements, reason:",
-               // error);
-               // }
-               // return isOk;
+//             boolean isOk = false;
+//              try {
+//                      IndexService lucin = getIndex();
+//                      for(Scenario scenario : aStudy.getScenariiList()) {
+//                              for (KnowledgeElement element : scenario.getAllKnowledgeElements()) {
+//                                      lucin.update(element);
+//                              }
+//                      }
+//                      isOk = true;
+//              } catch (Exception error) {
+//                      LOG.error("Unable to re-index Knowledge Elements, reason:",
+//                      error);
+//              }
+//              return isOk;
                return true;
        }
 
@@ -1138,7 +1141,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
         */
-       @Override
        @Transactional
        public void markStudyAsReference(final Study aStudy) {
 
@@ -1153,7 +1155,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
         */
-       @Override
        @Transactional
        public void removeStudyAsReference(final Study aStudy) {
 
@@ -1176,7 +1177,8 @@ public class StudyServiceImpl implements StudyService {
                }
                Study study = _studyDAO.get(studyId);
                if (study == null) {
-                       throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString());
+                       throw new InvalidParameterException(PARAM_STUDY_ID, studyId
+                                       .toString());
                }
                return study.getDescription();
        }
@@ -1186,7 +1188,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
         */
-       @Override
        @Transactional
        public void setDescription(final Long studyId, final String descriptionText)
                        throws InvalidParameterException {
@@ -1195,7 +1196,8 @@ public class StudyServiceImpl implements StudyService {
                }
                Study study = _studyDAO.get(studyId);
                if (study == null) {
-                       throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString());
+                       throw new InvalidParameterException(PARAM_STUDY_ID, studyId
+                                       .toString());
                }
                study.setAttribute(new DescriptionAttribute(study, descriptionText));
        }
@@ -1205,7 +1207,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
         */
-       @Override
        @Transactional
        public boolean removeDescription(final Long studyId)
                        throws InvalidParameterException {
@@ -1251,17 +1252,19 @@ public class StudyServiceImpl implements StudyService {
                                        + "downloads" + File.separator + userName + File.separator
                                        + "ComparisonResult.pdf";
 
-                       XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle());
+                       XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle()
+                                       + " Scenario: " + docDTO.getScenarioTitle() + " Document: "
+                                       + docDTO.getDocumentTitle());
 
                        // read the file and get points information.
                        try {
                                Scanner input = new Scanner(compDocFile);
 
-                               //get the title of the chart.
+                               // get the title of the chart.
                                if (input.hasNext()) {
                                        chartTitle = input.nextLine();
                                }
-                               
+
                                // get the name of the axis.
                                if (input.hasNext()) {
                                        String[] tokens = input.nextLine().split(",");
@@ -1304,14 +1307,11 @@ public class StudyServiceImpl implements StudyService {
                                dataset.addSeries(series);
 
                        } catch (FileNotFoundException e) {
-                               // TODO Auto-generated catch block
-                               e.printStackTrace();
-                               return "ERROR";
+                               LOG.error("Sorry, the file is not found.", e);
                        }
                } // for
 
-               JFreeChart chart = ChartFactory.createXYLineChart(
-                               chartTitle, // Title
+               JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // Title
                                axis1Name, // x-axis Label
                                axis2Name, // y-axis Label
                                dataset, // Dataset
@@ -1345,16 +1345,77 @@ public class StudyServiceImpl implements StudyService {
                        document.close();
 
                } catch (FileNotFoundException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+                       LOG.error("Sorry, the file is not found.", e);
                } catch (DocumentException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+                       LOG.error("Sorry, the DocumentException is thrown.", e);
                }
-
+       
                return resultPath;
        }
+       
+       /** 
+        * {@inheritDoc}
+        * @see org.splat.service.StudyService#getReaders(long)
+        */
+       @Transactional(readOnly = true)
+       public List<UserDTO> getReaders(final long studyId) throws InvalidParameterException {
+               Study aStudy = selectStudy(studyId);
+               if(aStudy == null){
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String.valueOf(studyId));
+               }
+               List<Relation> relations = aStudy.getRelations(ReaderRelation.class);
+               List<UserDTO> result = new ArrayList<UserDTO>();
+               for(Relation relation : relations){
+                       result.add(BeanHelper.copyBean(relation.getTo(), UserDTO.class));
+               }
+               return Collections.unmodifiableList(result);
+       }
+       
+       /** 
+        * {@inheritDoc}
+        * @see org.splat.service.StudyService#addReader(long, long)
+        */
+       @Transactional
+       public boolean addReader(final long studyId, final long userId) throws InvalidParameterException {
+               Study aStudy = selectStudy(studyId);
+               if(aStudy == null){
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String.valueOf(studyId));
+               }
+               User user = _userService.selectUser(userId);
+               if(user == null){
+                       throw new InvalidParameterException("userId", String.valueOf(userId));
+               }
+
+               for(Relation relation : aStudy.getRelations(ReaderRelation.class)) {
+                       if(user.equals(relation.getTo())) {
+                               return false;
+                       }
+               }
+               aStudy.addRelation(new ReaderRelation(aStudy, user));
+               update(aStudy);
+               return true;
+       }
+
+       /** 
+        * {@inheritDoc}
+        * @see org.splat.service.StudyService#removeReader(long, long)
+        */
+       @Transactional
+       public boolean removeReader(final long studyId, final long userId) throws InvalidParameterException {
+               Study aStudy = selectStudy(studyId);
+               if(aStudy == null){
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String.valueOf(studyId));
+               }
+               User user = _userService.selectUser(userId);
+               if(user == null){
+                       throw new InvalidParameterException("userId", String.valueOf(userId));
+               }
 
+               Relation relation = aStudy.removeRelation(ReaderRelation.class, user);
+               update(aStudy);
+               return relation != null;
+       }
+       
        /**
         * Get project settings.
         * 
@@ -1555,98 +1616,102 @@ public class StudyServiceImpl implements StudyService {
         * @see org.splat.service.StudyService#getComparableStudies()
         */
        @Transactional(readOnly = true)
-       public List<StudyFacadeDTO> getComparableStudies(final long userId) throws MismatchException {
-               //retrieve the number of the "Analyze the results" step 
+       public List<StudyFacadeDTO> getComparableStudies(final long userId)
+                       throws MismatchException {
+               // retrieve the number of the "Analyze the results" step
                List<Step> allSteps = _projectSettings.getAllSteps();
                Step theAnalyzeStep = null;
-               for(Step step : allSteps) {
-                       if(step.getKey().equals("postprocessing")) {
+               for (Step step : allSteps) {
+                       if (step.getKey().equals("postprocessing")) {
                                theAnalyzeStep = step;
                        }
                }
-               if(theAnalyzeStep == null) {    //TODO: throw some other exception
-                       throw new MismatchException("no step with key 'postprocessing' found." +
-                                       "Probably, customization settings have been changed.");
+               if (theAnalyzeStep == null) { // TODO: throw some other exception
+                       throw new MismatchException(
+                                       "no step with key 'postprocessing' found."
+                                                       + "Probably, customization settings have been changed.");
                }
 
-               List<Publication> publications = _publicationDAO.getFilteredList("mydoc",
-                               Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber())));
+               List<Publication> publications = _publicationDAO.getFilteredList(
+                               "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep
+                                               .getNumber())));
 
-               //split retrieved publications into groups by studies and scenarios
+               // split retrieved publications into groups by studies and scenarios
                Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
-               Map<ProjectElement, List<Publication>> scenarioMap = 
-                               new HashMap<ProjectElement, List<Publication>>();
-               
-               for(Publication publication : publications) {                   
-                       //filter out publications corresponding to a document of given step which is not a _result_ document
-                       if(!publication.value().getType().isResultOf(theAnalyzeStep)
+               Map<ProjectElement, List<Publication>> scenarioMap = new HashMap<ProjectElement, List<Publication>>();
+
+               for (Publication publication : publications) {
+                       // filter out publications corresponding to a document of given step which is not a _result_ document
+                       if (!publication.value().getType().isResultOf(theAnalyzeStep)
                                        || !"srd".equals(publication.getSourceFile().getFormat())) {
                                continue;
                        }
-                       
-                       //check the study visibility to the user
-                       if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId))
-                                       && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) {
+
+                       // check the study visibility to the user
+                       if (!isStaffedBy(publication.getOwnerStudy(), _userService
+                                       .selectUser(userId))
+                                       && Visibility.PUBLIC.equals(publication.getOwnerStudy()
+                                                       .getVisibility())) {
                                continue;
                        }
-       
+
                        Study study = publication.getOwnerStudy();
                        ProjectElement scenario = publication.getOwner();
-                       
+
                        Hibernate.initialize(scenario);
-                   if (scenario instanceof HibernateProxy) {
-                       scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer()
-                               .getImplementation();
-                   }
-                       
-                       if(!(scenario instanceof Scenario)) {
+                       if (scenario instanceof HibernateProxy) {
+                               scenario = (ProjectElement) ((HibernateProxy) scenario)
+                                               .getHibernateLazyInitializer().getImplementation();
+                       }
+
+                       if (!(scenario instanceof Scenario)) {
                                throw new MismatchException(
                                                "publications from postprocessing step are supposed to have owner scenario");
                        }
 
-                       if(!studyMap.containsKey(study)) {
+                       if (!studyMap.containsKey(study)) {
                                studyMap.put(study, new ArrayList<ProjectElement>());
                        }
-                       
-                       if(!studyMap.get(study).contains(scenario)) {
+
+                       if (!studyMap.get(study).contains(scenario)) {
                                studyMap.get(study).add(scenario);
                        }
 
-                       if(!scenarioMap.containsKey(scenario)) {
+                       if (!scenarioMap.containsKey(scenario)) {
                                scenarioMap.put(scenario, new ArrayList<Publication>());
                        }
                        scenarioMap.get(scenario).add(publication);
                }
-               
-               //Create the result DTOs
+
+               // Create the result DTOs
                List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
-               for(Study study : studyMap.keySet()) {
-                       
+               for (Study study : studyMap.keySet()) {
+
                        StudyFacadeDTO studyDTO = new StudyFacadeDTO();
                        studyDTO.setName(study.getTitle());
                        studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
                        result.add(studyDTO);
-                       
-                       for(ProjectElement scenario : studyMap.get(study)) {
-                               
+
+                       for (ProjectElement scenario : studyMap.get(study)) {
+
                                StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
                                scenarioDTO.setName(scenario.getTitle());
                                scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
                                studyDTO.getScenarios().add(scenarioDTO);
 
-                               for(Publication publication : scenarioMap.get(scenario)) {
+                               for (Publication publication : scenarioMap.get(scenario)) {
 
                                        DocumentDTO documentDTO = new DocumentDTO();
                                        documentDTO.setId(publication.getIndex());
                                        documentDTO.setTitle(publication.value().getTitle());
-                                       
+
                                        scenarioDTO.getDocs().add(documentDTO);
                                }
                        }
-               }               
+               }
                return result;
        }
-       
+
        /**
         * Get the publicationDAO.
         *