From 81e0cd22ce9eb29d2b36bbeb1eda8c9be0f5621c Mon Sep 17 00:00:00 2001 From: rkv Date: Wed, 21 Nov 2012 13:30:32 +0000 Subject: [PATCH] Default document types mappings are moved from application settings (my.xml) to project settings (som.xml). The first implementation and unit test for ScenarioService.checkin after SALOME is created. --- .../src/conf/log-messages.properties | 4 +- .../common/properties/MessageKeyEnum.java | 14 +- .../org/splat/dal/bo/som/ProgressState.java | 42 +- .../src/org/splat/dal/bo/som/Study.java | 128 +++-- .../kernel/InvalidPropertyException.java | 44 +- .../splat/service/DocumentServiceImpl.java | 7 +- .../org/splat/service/PublicationService.java | 67 ++- .../org/splat/service/ScenarioService.java | 29 +- .../splat/service/ScenarioServiceImpl.java | 210 ++++++- .../org/splat/service/StepServiceImpl.java | 6 +- .../org/splat/service/dto/DocumentDTO.java | 2 +- .../src/org/splat/service/dto/FileDTO.java | 2 +- .../src/org/splat/service/dto/StepDTO.java | 2 +- .../technical/ProjectSettingsService.java | 37 +- .../technical/ProjectSettingsServiceImpl.java | 144 ++++- .../src/spring/businessServiceContext.xml | 13 +- .../Siman-Common/src/test/siman.properties | 1 - Workspace/Siman-Common/src/test/som.xml | 30 + .../service/TestProjectSettingsService.java | 289 +++++++++- .../splat/service/TestScenarioService.java | 157 ++++-- Workspace/Siman/WebContent/conf/my.xml | 30 - Workspace/Siman/WebContent/conf/som.xml | 31 ++ .../org/splat/simer/ApplicationSettings.java | 94 +--- .../org/splat/simer/ImportDocumentAction.java | 525 +++++++++++------- .../src/org/splat/simer/UploadAction.java | 401 ++++++++----- .../org/splat/simer/UploadBaseNextAction.java | 191 +++---- .../splat/simer/VersionDocumentAction.java | 71 +-- .../Siman/src/org/splat/wapp/Constants.java | 18 + 28 files changed, 1819 insertions(+), 770 deletions(-) diff --git a/Workspace/Siman-Common/src/conf/log-messages.properties b/Workspace/Siman-Common/src/conf/log-messages.properties index 708f15d..05739d5 100644 --- a/Workspace/Siman-Common/src/conf/log-messages.properties +++ b/Workspace/Siman-Common/src/conf/log-messages.properties @@ -3,4 +3,6 @@ LCK-000001=Lock reference already exists for user {2}. LCK-000002=Lock reference does not exists. LCK-000003=Lock reference protected and can be only deleted or updated by user {2}. LCK-000004=Lock reference is timeout and could have been modified by user {2}. -STD-000001="Unable to re-index the study #{1}, reason: {2}" \ No newline at end of file +STD-000001=Unable to re-index the study #{1}, reason: {2} +SCN-000001=Scenario doesn't contain the step number #{1} +SCN-000002=Scenario doesn't contain the document #{1} \ No newline at end of file diff --git a/Workspace/Siman-Common/src/org/splat/common/properties/MessageKeyEnum.java b/Workspace/Siman-Common/src/org/splat/common/properties/MessageKeyEnum.java index b7c2921..12409ae 100644 --- a/Workspace/Siman-Common/src/org/splat/common/properties/MessageKeyEnum.java +++ b/Workspace/Siman-Common/src/org/splat/common/properties/MessageKeyEnum.java @@ -32,7 +32,19 @@ public enum MessageKeyEnum { /** * Lock reference is timeout and could have been modified by user {2}. */ - LCK_000004("LCK-000004"); + LCK_000004("LCK-000004"), + /** + * Unable to re-index the study #{1}, reason: {2}. + */ + STD_000001("STD-000001"), + /** + * Scenario doesn't contain the step number #{1}. + */ + SCN_000001("SCN-000001"), + /** + * Scenario doesn't contain the document #{1}. + */ + SCN_000002("SCN-000002"); /** * Value. diff --git a/Workspace/Siman-Common/src/org/splat/dal/bo/som/ProgressState.java b/Workspace/Siman-Common/src/org/splat/dal/bo/som/ProgressState.java index 78f1311..9a80331 100644 --- a/Workspace/Siman-Common/src/org/splat/dal/bo/som/ProgressState.java +++ b/Workspace/Siman-Common/src/org/splat/dal/bo/som/ProgressState.java @@ -1,7 +1,9 @@ package org.splat.dal.bo.som; + /** + * Study, scenario or document progress state enumeration. * - * @author Daniel Brunier-Coulin + * @author Daniel Brunier-Coulin * @copyright OPEN CASCADE 2012 */ @@ -9,17 +11,29 @@ public enum ProgressState { /** * Represents inWORK, inDRAFT and inCHECK states for search purpose. */ - inPROGRESS, - inWORK, - inDRAFT, - inCHECK, - APPROVED, - /** - * Document-specific state representing documents produced outside studies. - */ - EXTERN, - /** - * Study-specific state qualifying typical reference studies. - */ - TEMPLATE; + inPROGRESS, + /** + * The first possible state in a validation cycle. + */ + inWORK, + /** + * The state after promoting from inWORK state. + */ + inDRAFT, + /** + * The state after validating from inDRAFT or inWORK state. + */ + inCHECK, + /** + * The state after approving from inCHECK state. + */ + APPROVED, + /** + * Document-specific state representing documents produced outside studies. + */ + EXTERN, + /** + * Study-specific state qualifying typical reference studies. + */ + TEMPLATE; } \ No newline at end of file diff --git a/Workspace/Siman-Common/src/org/splat/dal/bo/som/Study.java b/Workspace/Siman-Common/src/org/splat/dal/bo/som/Study.java index 3af40f5..bcb760c 100644 --- a/Workspace/Siman-Common/src/org/splat/dal/bo/som/Study.java +++ b/Workspace/Siman-Common/src/org/splat/dal/bo/som/Study.java @@ -10,17 +10,17 @@ import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import org.splat.dal.bo.kernel.Persistent; import org.splat.dal.bo.kernel.User; -import org.splat.kernel.MultiplyDefinedException; import org.splat.kernel.InvalidPropertyException; import org.splat.kernel.MissedPropertyException; +import org.splat.kernel.MultiplyDefinedException; import org.splat.som.Revision; /** @@ -50,9 +50,9 @@ public class Study extends ProjectElement { */ private Visibility visibility; /** - * Persistent list of study scenarii. + * Persistent list of study scenarios. */ - private List scenarii = new LinkedList(); + private final List scenarii = new LinkedList(); private String version; /** * Persistent history property. It is a number of studies versioning this one, if any. @@ -63,15 +63,15 @@ public class Study extends ProjectElement { /** * Transient list of contributors. */ - private transient List contributor = new Vector(); // Shortcut to contributors + private transient final List contributor = new Vector(); /** * Transient map of document types to validation cycles. */ - private transient Map validactor = new HashMap(); // Shortcut to validation cycles + private transient final Map validactor = new HashMap(); /** * Transient set of all actors of the study, i.d. contributors and validation cycles participants. */ - private transient Set actor = new HashSet(); // Summary of above actors + private transient final Set actor = new HashSet(); // ============================================================================================================================== // Construction @@ -81,7 +81,6 @@ public class Study extends ProjectElement { * Fields initialization class. */ public static class Properties extends Persistent.Properties { - // ------------------------------------------------------------ private String sid = null; // Search criterion only private String title = null; private String summary = null; @@ -94,6 +93,7 @@ public class Study extends ProjectElement { // - Public services + @Override public void clear() { super.clear(); sid = null; @@ -158,58 +158,62 @@ public class Study extends ProjectElement { // - Property setters // For building a search query - public Properties setActor(User actor) { + public Properties setActor(final User actor) { this.actor = actor; return this; } - public Properties setDate(Date date) { + public Properties setDate(final Date date) { this.date = date; return this; } - public Properties setDescription(String summary) { - if (summary.length() > 0) + public Properties setDescription(final String summary) { + if (summary.length() > 0) { this.summary = summary; + } return this; } - public Properties setManager(User user) { + public Properties setManager(final User user) { this.manager = user; return this; } // For building a search query - public Properties setReference(String sid) + public Properties setReference(final String sid) throws InvalidPropertyException { - if (sid.length() == 0) + if (sid.length() == 0) { throw new InvalidPropertyException("reference"); + } this.sid = sid; return this; } // For building a search query - public Properties setSimulationContexts(List context) { + public Properties setSimulationContexts( + final List context) { this.context = context; return this; } // For building a search query - public Properties setState(ProgressState state) { + public Properties setState(final ProgressState state) { this.state = state; return this; } - public Properties setTitle(String title) + public Properties setTitle(final String title) throws InvalidPropertyException { - if (title.length() == 0) + if (title.length() == 0) { throw new InvalidPropertyException("title"); + } this.title = title; return this; } // For building a search query - public Properties setVisibility(Visibility area) { + public Properties setVisibility(final Visibility area) { this.visibility = area; return this; } @@ -218,31 +222,46 @@ public class Study extends ProjectElement { public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException { - if (title == null) + if (title == null) { throw new MissedPropertyException("title"); - if (manager == null) + } + if (manager == null) { throw new MissedPropertyException("manager"); + } } } - // Database fetch constructor + /** + * Database fetch constructor. + */ protected Study() { + super(); contributor.clear(); validactor.clear(); actor.clear(); } - // Internal constructor - public Study(Properties sprop) throws MissedPropertyException, + /** + * Constructor from properties. + * + * @param sprop + * study properties + * @throws MissedPropertyException + * if some mandatory property is missed + * @throws InvalidPropertyException + * if some property has invalid value + * @throws MultiplyDefinedException + * if some property is defined several times + */ + public Study(final Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException { - // ---------------------------------- super(sprop); // Throws one of the above exception if not valid sid = sprop.sid; // Reset after save title = sprop.title; // Inherited attribute manager = sprop.manager; docount = 0; history = 0; -//RKV scenarii = new LinkedList(); + // RKV scenarii = new LinkedList(); visibility = Visibility.PRIVATE; state = ProgressState.inWORK; @@ -254,8 +273,9 @@ public class Study extends ProjectElement { lasdate = credate; // Inherited attribute version = new Revision().incrementAs(state).toString(); - if (sprop.summary != null) + if (sprop.summary != null) { this.setAttribute(new DescriptionAttribute(this, sprop.summary)); + } contributor.clear(); validactor.clear(); @@ -275,27 +295,33 @@ public class Study extends ProjectElement { return sid; } - public void setReference(String aReference) { + public void setReference(final String aReference) { sid = aReference; } + /** + * Get persistent list of study scenarios as an array. + * + * @return array of scenarios + */ public Scenario[] getScenarii() { - // -------------------------------- return scenarii.toArray(new Scenario[scenarii.size()]); } + /** + * Get persistent list of study scenarios. + * + * @return the list of scenarios + */ public List getScenariiList() { - // -------------------------------- return scenarii; } public String getVersion() { - // --------------------------- return version; } public Visibility getVisibility() { - // ---------------------------------- return visibility; } @@ -307,32 +333,38 @@ public class Study extends ProjectElement { * @see #moveToReference() */ public boolean isPublic() { - // -------------------------- return (visibility != Visibility.PRIVATE); } public boolean isVersioned() { - // ----------------------------- return (history > 0); } - public boolean shares(Document doc) { - // ------------------------------------ + /** + * Check if the document is shared by scenarios of the study. + * + * @param doc + * the document to check + * @return true if the document is published in more then one scenario of the study + */ + public boolean shares(final Document doc) { Scenario[] scene = this.getScenarii(); // If shared from within the study, the document is shared by the scenarios int counter = 0; + boolean res = false; for (int i = 0; i < scene.length; i++) { - if (!scene[i].publishes(doc)) - continue; - if (counter == 1) - return true; - counter += 1; + if (scene[i].publishes(doc)) { + if (counter == 1) { + res = true; + break; + } + counter += 1; + } } - return false; + return res; } public int getLastLocalIndex() { - // ---------------------------------- return docount; } @@ -340,7 +372,7 @@ public class Study extends ProjectElement { * @param aVisibility * a study visibility to set */ - public void setVisibility(Visibility aVisibility) { + public void setVisibility(final Visibility aVisibility) { visibility = aVisibility; } @@ -348,14 +380,14 @@ public class Study extends ProjectElement { * @param aState * a study progress state to set */ - public void setProgressState(ProgressState aState) { + public void setProgressState(final ProgressState aState) { state = aState; } /** * @param aVersion */ - public void setVersion(String aVersion) { + public void setVersion(final String aVersion) { version = aVersion; } @@ -365,7 +397,7 @@ public class Study extends ProjectElement { * @param anIndex * a number of study documents */ - public void setLastLocalIndex(int anIndex) { + public void setLastLocalIndex(final int anIndex) { docount = anIndex; } diff --git a/Workspace/Siman-Common/src/org/splat/kernel/InvalidPropertyException.java b/Workspace/Siman-Common/src/org/splat/kernel/InvalidPropertyException.java index 660940e..68b60be 100644 --- a/Workspace/Siman-Common/src/org/splat/kernel/InvalidPropertyException.java +++ b/Workspace/Siman-Common/src/org/splat/kernel/InvalidPropertyException.java @@ -4,7 +4,8 @@ import org.splat.exception.BusinessException; /** * Exception thrown when the property is invalid. - * @author Daniel Brunier-Coulin + * + * @author Daniel Brunier-Coulin * @copyright OPEN CASCADE 2012 */ @@ -16,10 +17,41 @@ public class InvalidPropertyException extends BusinessException { private static final long serialVersionUID = -3988379180445723963L; /** - * Create a InvalidPropertyException. - * @param message the error message. + * Create a InvalidPropertyException. + * + * @param message + * the error message. */ - public InvalidPropertyException (final String message) { - super(message); - } + public InvalidPropertyException(final String message) { + super(message); + } + + /** + * Create a InvalidPropertyException. + * + * @param messageKey + * error message key + * @param context + * parameters + */ + public InvalidPropertyException(final String messageKey, + final Object... context) { + super(messageKey, context); + // TODO auto-generated constructor + } + + /** + * Create a InvalidPropertyException. + * + * @param messageKey + * error message key + * @param throwable + * the original exception + * @param context + * parameters + */ + public InvalidPropertyException(final String messageKey, + final Throwable throwable, final Object... context) { + super(messageKey, throwable, context); + } } \ No newline at end of file diff --git a/Workspace/Siman-Common/src/org/splat/service/DocumentServiceImpl.java b/Workspace/Siman-Common/src/org/splat/service/DocumentServiceImpl.java index 7e6947d..cfa4983 100644 --- a/Workspace/Siman-Common/src/org/splat/service/DocumentServiceImpl.java +++ b/Workspace/Siman-Common/src/org/splat/service/DocumentServiceImpl.java @@ -542,11 +542,10 @@ public class DocumentServiceImpl implements DocumentService { for (Iterator i = aDoc.getAllRelations().iterator(); i .hasNext();) { Relation link = i.next(); - if (!link.getClass().equals(VersionsRelation.class)) { - continue; + if (link.getClass().equals(VersionsRelation.class)) { + previous = (Document) link.getTo(); // Versioned document + break; } - previous = (Document) link.getTo(); // Versioned document - break; } } if (aDoc.getProgressState() != null) { diff --git a/Workspace/Siman-Common/src/org/splat/service/PublicationService.java b/Workspace/Siman-Common/src/org/splat/service/PublicationService.java index 9abcf75..e30099e 100644 --- a/Workspace/Siman-Common/src/org/splat/service/PublicationService.java +++ b/Workspace/Siman-Common/src/org/splat/service/PublicationService.java @@ -50,30 +50,47 @@ public interface PublicationService { /** * Create a new version of the document. - * @param step the study step where the document is published - * @param user the current user - * @param filename the new version file name - * @param docIndex the publication id - * @param docver new document version string, empty for external documents - * @param summary the version comment - * @param state the new state of the document - * @param date the new modification date - * @param docuses the array of documents ids used by the versioned document - * @param docusedby the array of impacted documents ids - * @throws MissedPropertyException if some mandatory property is missed - * @throws InvalidPropertyException if some property has invalid value - * @throws MultiplyDefinedException if some property occurs several times - * @throws IOException if file moving is failed - * @throws MismatchException if step number in properties doesn't match to the given step - * @throws NotApplicableException if publication's document is undefined - * @throws InterruptedException by Thread.sleep if interrupted + * + * @param step + * the study step where the document is published + * @param user + * the current user + * @param filename + * the new version file name + * @param docIndex + * the publication id + * @param docver + * new document version string, empty for external documents + * @param summary + * the version comment + * @param state + * the new state of the document + * @param date + * the new modification date + * @param docuses + * the array of documents ids used by the versioned document + * @param docusedby + * the array of impacted documents ids + * @throws MissedPropertyException + * if some mandatory property is missed + * @throws InvalidPropertyException + * if some property has invalid value + * @throws MultiplyDefinedException + * if some property occurs several times + * @throws IOException + * if file moving is failed + * @throws MismatchException + * if step number in properties doesn't match to the given step + * @throws NotApplicableException + * if publication's document is undefined + * @throws InterruptedException + * by Thread.sleep if interrupted */ - void versionDocument(Step step, User user, String filename, - long docIndex, String docver, String summary, ProgressState state, - Date date, String[] docuses, long[] docusedby) - throws MissedPropertyException, InvalidPropertyException, - MultiplyDefinedException, IOException, MismatchException, - NotApplicableException, InterruptedException; + void versionDocument(Step step, User user, String filename, long docIndex, + String docver, String summary, ProgressState state, Date date, + String[] docuses, long[] docusedby) throws MissedPropertyException, + InvalidPropertyException, MultiplyDefinedException, IOException, + MismatchException, NotApplicableException, InterruptedException; /** * Returns the study Step into which the document version referenced by this publication has been published. @@ -173,7 +190,7 @@ public interface PublicationService { /** * Publishes the document referenced by this publication into the owner Project Element under the given state, the revision number of * the document being automatically set accordingly. If the given state is In-Draft and the document is final result of the owner study, - * this automatically promotes the study to In-Draft. + * this automatically promotes the study to In-Draft. The old publication is removed from the scenario. * * @param aPublication * the document publication @@ -192,7 +209,7 @@ public interface PublicationService { * of the referenced document is supposed being automatically set according to the given revision number, but, due to the versioning * scheme, as it is not possible to differentiate In-Work and In-Draft states, this function has been deprecated (it is currently used * only for the need of integration of Microsoft Office which anyway has to be redesigned).
Note: in the context of branch - * versioning, the given revision may be modified by an update of the branch name. + * versioning, the given revision may be modified by an update of the branch name. The old publication is removed from the scenario. * * @param aPublication * the document publication diff --git a/Workspace/Siman-Common/src/org/splat/service/ScenarioService.java b/Workspace/Siman-Common/src/org/splat/service/ScenarioService.java index 150cd1f..de0ed29 100644 --- a/Workspace/Siman-Common/src/org/splat/service/ScenarioService.java +++ b/Workspace/Siman-Common/src/org/splat/service/ScenarioService.java @@ -9,6 +9,7 @@ package org.splat.service; +import java.io.IOException; import java.util.List; import org.splat.dal.bo.kernel.User; @@ -17,8 +18,10 @@ import org.splat.dal.bo.som.Scenario; import org.splat.dal.bo.som.SimulationContext; import org.splat.dal.bo.som.Study; import org.splat.kernel.InvalidPropertyException; +import org.splat.kernel.MismatchException; import org.splat.kernel.MissedPropertyException; import org.splat.kernel.MultiplyDefinedException; +import org.splat.kernel.NotApplicableException; import org.splat.service.dto.StepDTO; import org.splat.som.Step; @@ -98,7 +101,15 @@ public interface ScenarioService { InvalidPropertyException, MultiplyDefinedException; /** - * Check-in the scenario after SALOME session. + * Check-in the scenario after SALOME session. If a document to be checked in already exists then create a new version of it. Otherwise + * create a new document of the appropriate step result type. + *
    + *
  • For each new created document version we copy Uses relations from the previous document version. If used document has been also + * versioned during this check-in operation then refer to its new version.
  • + *
  • For each new document create uses relation to the last versions of results of a previous step.
  • + *
+ * NOTE: Only the first attached file is processed for each document.
All new documents/versions are created in inWORK + * state. * * @param scenId * the scenario id @@ -106,9 +117,23 @@ public interface ScenarioService { * the id of the user who modified documents * @param scInfo * the list of scenario steps DTO + * @throws InvalidPropertyException + * if the scenario hasn't some of given steps or documents + * @throws IOException + * if a file can't be moved into the vault + * @throws MismatchException + * if version creation in some of steps is failed + * @throws MissedPropertyException + * if some mandatory property is missed when new document or new document version is created + * @throws MultiplyDefinedException + * if some property is defined several times when new document or new document version is created + * @throws NotApplicableException + * if failed saving of a new publication with a given state */ void checkin(final long scenId, final long userId, - final List scInfo); + final List scInfo) throws InvalidPropertyException, + MissedPropertyException, MultiplyDefinedException, + MismatchException, IOException, NotApplicableException; /** * Check in the scenario. diff --git a/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java b/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java index b722a6e..4dc0648 100644 --- a/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java +++ b/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java @@ -12,29 +12,40 @@ package org.splat.service; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.apache.log4j.Logger; +import org.splat.common.properties.MessageKeyEnum; import org.splat.dal.bo.kernel.Relation; import org.splat.dal.bo.kernel.User; import org.splat.dal.bo.som.ConvertsRelation; +import org.splat.dal.bo.som.Document; +import org.splat.dal.bo.som.DocumentType; import org.splat.dal.bo.som.File; import org.splat.dal.bo.som.KnowledgeElement; import org.splat.dal.bo.som.KnowledgeElementType; +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.Study; +import org.splat.dal.bo.som.UsesRelation; 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.kernel.InvalidPropertyException; +import org.splat.kernel.MismatchException; import org.splat.kernel.MissedPropertyException; import org.splat.kernel.MultiplyDefinedException; +import org.splat.kernel.NotApplicableException; import org.splat.service.dto.DocumentDTO; +import org.splat.service.dto.FileDTO; import org.splat.service.dto.StepDTO; import org.splat.service.technical.IndexService; import org.splat.service.technical.ProjectSettingsService; @@ -119,6 +130,11 @@ public class ScenarioServiceImpl implements ScenarioService { */ private ProjectSettingsService _projectSettings; + /** + * Injected document type service. + */ + private DocumentTypeService _documentTypeService; + /** * Get the projectElementService. * @@ -183,7 +199,7 @@ public class ScenarioServiceImpl implements ScenarioService { * * @see org.splat.service.ScenarioService#getScenarioInfo(long) */ - @Transactional + @Transactional(readOnly = true) public List getScenarioInfo(final long scenarioId) { List res = new ArrayList(); // Get the scenario from the database by id @@ -362,9 +378,179 @@ public class ScenarioServiceImpl implements ScenarioService { * * @see org.splat.service.ScenarioService#checkin(long, long, java.util.List) */ + @Transactional public void checkin(final long scenId, final long userId, - final List scInfo) { + final List scInfo) throws InvalidPropertyException, + MissedPropertyException, MultiplyDefinedException, + MismatchException, IOException, NotApplicableException { + // Get the scenario from the database by id + Scenario aScenario = getScenarioDAO().get(scenId); + // Get the user who perform this check-in operation + User aUser = getUserService().selectUser(userId); + // Get activities of the scenario + Step[] steps = getProjectElementService().getSteps(aScenario); + // Find result document types + List resTypes = getDocumentTypeService() + .selectResultTypes(); + + // For each processed existing document keep its new version + Map newVersion = new HashMap(); + // For each processed existing document keep its previous version + Map prevVersion = new HashMap(); + // Keep newly created documents to create uses relations to results of a previous step. + List newVers = new ArrayList(); + List newDocs = new ArrayList(); + // For each step DTO + DocumentType resType; + java.io.File updir; + Document.Properties dprop = new Document.Properties(); + Date aDate = new Date(); + for (StepDTO stepDTO : scInfo) { + // Find a result document type of the step + int i = 0; + resType = null; + do { + if (resTypes.get(i).isResultOf( + getProjectSettings().getStep(stepDTO.getNumber()))) { + resType = resTypes.get(i); + } + i++; + } while ((resType == null) && (i < resTypes.size())); + + // Find the appropriate scenario step + Step step = findStep(stepDTO, steps); + + // Process documents of the step + for (DocumentDTO doc : stepDTO.getDocs()) { + if (doc.getFiles().size() > 0) { + // NOTE: Process only the first attached file for each document + FileDTO file = doc.getFiles().get(0); + + // 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); + String docname = upfile.getName().substring(0, + upfile.getName().lastIndexOf('.')); + + // Create a new document or a new version of the document + dprop.clear(); + dprop.setAuthor(aUser).setDate(aDate); + 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()); + } + newPub = getStepService().versionDocument(step, pub, + dprop); + // 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); + // Remember the previouse document version for the new publication + prevVersion.put(newPub, pub.value()); + } else { + + // Otherwise create a new document of the result type + // If result type is not found try to get type by file extension + if (resType == null) { + dprop.setType(getProjectSettings() + .getDefaultDocumentType(step.getStep(), + fileFormat)); + } else { + dprop.setType(resType); + } + dprop.setDescription("Checked in").setName(docname) + .setFormat(fileFormat); + newPub = getStepService().createDocument(step, dprop); + + // Remeber the new document + newDocs.add(newPub); + } + + // Attach the file to the created document + updir = newPub.getSourceFile().asFile(); + if (LOG.isInfoEnabled()) { + LOG.info("Moving \"" + upfile.getName() + "\" to \"" + + updir.getPath() + "\"."); + } + 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 + } + } + } + } + + // Set uses/used relations + + // For each new version copy uses relations from the previous version. + for (Publication newVer : newVers) { + // For each Uses relation of the previous version + for (Relation rel : prevVersion.get(newVer).getRelations( + UsesRelation.class)) { + // If used document has been also versioned then refer to its new version. + Document usedDoc = ((UsesRelation) rel).getTo(); + if (newVersion.containsKey(usedDoc)) { + usedDoc = newVersion.get(usedDoc); + } + // Build the appropriate relation for the new version. + newVer.addDependency(usedDoc); + } + // TODO: Outdate documents which depend from the previous version and were not checked in during this operation. + + } + + // For each new document create uses relation to the last versions of + // results of the previous step. + for (Publication newDoc : newDocs) { + // Find used document type according to the configuration. + // Find documents of used type in the previous study step. + + // Create uses relation from the new document + // to the found document in the previous step. + //newDoc.addDependency(to); + } + // Mark the scenario as checked in + checkin(aScenario); + } + + /** + * Find appropriate step in the array of scenario steps according to the given step DTO. + * + * @param stepDTO + * the stepDTO + * @param steps + * scenario steps + * @return appropriate scenario step + * @throws InvalidPropertyException + * if appropriate step is not found + */ + private Step findStep(final StepDTO stepDTO, final Step[] steps) + throws InvalidPropertyException { + int i = 0; + Step step = null; + do { + if (steps[i].getNumber() == stepDTO.getNumber()) { + step = steps[i]; + } + i++; + } while ((step == null) && (i < steps.length)); + + if (step == null) { + throw new InvalidPropertyException(MessageKeyEnum.SCN_000001 + .toString(), stepDTO.getNumber()); + } + return step; } /** @@ -748,4 +934,24 @@ public class ScenarioServiceImpl implements ScenarioService { _projectSettings = projectSettingsService; } + /** + * Get the documentTypeService. + * + * @return the documentTypeService + */ + public DocumentTypeService getDocumentTypeService() { + return _documentTypeService; + } + + /** + * Set the documentTypeService. + * + * @param documentTypeService + * the documentTypeService to set + */ + public void setDocumentTypeService( + final DocumentTypeService documentTypeService) { + _documentTypeService = documentTypeService; + } + } diff --git a/Workspace/Siman-Common/src/org/splat/service/StepServiceImpl.java b/Workspace/Siman-Common/src/org/splat/service/StepServiceImpl.java index fbbcb08..281d57c 100644 --- a/Workspace/Siman-Common/src/org/splat/service/StepServiceImpl.java +++ b/Workspace/Siman-Common/src/org/splat/service/StepServiceImpl.java @@ -24,7 +24,6 @@ import org.splat.dal.bo.som.KnowledgeElement; 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.Study; import org.splat.dal.bo.som.UsedByRelation; import org.splat.dal.bo.som.UsesRelation; import org.splat.dal.bo.som.VersionsRelation; @@ -378,7 +377,9 @@ public class StepServiceImpl implements StepService { newdoc.addRelation(aRel); // Update of usedby relations, if exist - List relist = previous.getRelations(UsedByRelation.class); +/* RKV: Consider the new version as not used by old dependent documents. + * So these documents must be marked as outdated then. + List relist = previous.getRelations(UsedByRelation.class); Study scope = aStep.getOwnerStudy(); for (Iterator i = relist.iterator(); i.hasNext();) { UsedByRelation relation = (UsedByRelation) i.next(); @@ -389,6 +390,7 @@ public class StepServiceImpl implements StepService { relation.moveTo(newdoc); } } +*/ return new Publication(newdoc, aStep.getOwner()); } diff --git a/Workspace/Siman-Common/src/org/splat/service/dto/DocumentDTO.java b/Workspace/Siman-Common/src/org/splat/service/dto/DocumentDTO.java index 1f3b3f3..c411370 100644 --- a/Workspace/Siman-Common/src/org/splat/service/dto/DocumentDTO.java +++ b/Workspace/Siman-Common/src/org/splat/service/dto/DocumentDTO.java @@ -44,7 +44,7 @@ public class DocumentDTO { } /** - * Constructor with initialization. + * Default constructor. */ public DocumentDTO() { } diff --git a/Workspace/Siman-Common/src/org/splat/service/dto/FileDTO.java b/Workspace/Siman-Common/src/org/splat/service/dto/FileDTO.java index e7e5c14..99405b6 100644 --- a/Workspace/Siman-Common/src/org/splat/service/dto/FileDTO.java +++ b/Workspace/Siman-Common/src/org/splat/service/dto/FileDTO.java @@ -53,7 +53,7 @@ public class FileDTO { } /** - * Constructor with initialization. + * Constructor with partial initialization. * * @param relativePath * relative file path diff --git a/Workspace/Siman-Common/src/org/splat/service/dto/StepDTO.java b/Workspace/Siman-Common/src/org/splat/service/dto/StepDTO.java index 0f1326a..6fad6ec 100644 --- a/Workspace/Siman-Common/src/org/splat/service/dto/StepDTO.java +++ b/Workspace/Siman-Common/src/org/splat/service/dto/StepDTO.java @@ -102,7 +102,7 @@ public class StepDTO { * * @return the number */ - public int getNumber() { + public Integer getNumber() { return _number; } diff --git a/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsService.java b/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsService.java index 576fd67..16a446c 100644 --- a/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsService.java +++ b/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsService.java @@ -15,6 +15,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.splat.dal.bo.som.DocumentType; import org.splat.dal.bo.som.ProjectElement; import org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming; import org.splat.service.technical.ProjectSettingsServiceImpl.ProjectSettingsValidationCycle; @@ -27,7 +28,7 @@ public interface ProjectSettingsService { /** * Transient study step data. */ - class Step { + class Step { /** * The sequential number of the step. */ @@ -149,6 +150,7 @@ public interface ProjectSettingsService { /** * Get the module. + * * @return the module */ public String getModule() { @@ -157,7 +159,9 @@ public interface ProjectSettingsService { /** * Set the module. - * @param module the module to set + * + * @param module + * the module to set */ public void setModule(final String module) { _module = module; @@ -165,6 +169,7 @@ public interface ProjectSettingsService { /** * Get the key. + * * @return the key */ public String getKey() { @@ -173,7 +178,9 @@ public interface ProjectSettingsService { /** * Set the key. - * @param key the key to set + * + * @param key + * the key to set */ public void setKey(final String key) { _key = key; @@ -247,7 +254,7 @@ public interface ProjectSettingsService { */ List getStepsOf( Class level); - + /** * Check if a file of the given format should be imported during check-in of a document of the given type. * @@ -257,5 +264,25 @@ public interface ProjectSettingsService { * file format * @return true if file should be imported */ - public boolean doImport(final String type, final String format); + boolean doImport(final String type, final String format); + + /** + * Get default document type for the given file format on the given study step. + * + * @param step + * the study step + * @param format + * the file format (extension) + * @return document type + */ + DocumentType getDefaultDocumentType(final Step step, final String format); + + /** + * Get the list of default formats for the given study step. + * + * @param step + * the study step + * @return list of formats (file extensions) + */ + List getDefaultFormats(final Step step); } diff --git a/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsServiceImpl.java b/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsServiceImpl.java index 49f84de..c9498f5 100644 --- a/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsServiceImpl.java +++ b/Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsServiceImpl.java @@ -53,6 +53,11 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { protected final static Logger LOG = Logger .getLogger(ProjectSettingsServiceImpl.class); + /** + * Type attribute name. + */ + private final static String TYPE_ATTR = "type"; + // Non persistent configuration information /** * Repository settings. @@ -77,11 +82,11 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { /** * Configuration document validation cycles. */ - private transient List _concycles; + private transient final List _concycles = new ArrayList(); /** * Document type mappings to file formats which should be imported into SALOME during check-out. */ - private transient Map> _mapimport; + private transient final Map> _mapimport = new HashMap>(); // Temporary attributes initialized from the configuration file for populating the database with object types /** @@ -123,8 +128,27 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { */ private DocumentTypeService _documentTypeService; + /** + * Default document types structured by step.formats. + */ + private transient final Map _defdoctype = new LinkedHashMap(); + + /** + * File naming strategy enumeration. + */ public enum FileNaming { - title, encoded, asis + /** + * Name by document title. + */ + title, + /** + * Generate encoded name. + */ + encoded, + /** + * Keep original file name. + */ + asis } /** @@ -318,6 +342,44 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { format)); } + /** + * Get default document type for the given file format on the given study step. + * + * @param step + * the study step + * @param format + * the file format (extension) + * @return document type + */ + public DocumentType getDefaultDocumentType(final Step step, + final String format) { + String[] table = format.split("\\x2E"); + return _defdoctype + .get(step.getNumber() + "." + table[table.length - 1]); // May be null + } + + /** + * Get the list of default formats for the given study step. + * + * @param step + * the study step + * @return list of formats (file extensions) + */ + public List getDefaultFormats(final Step step) { + Integer stepNumber = step.getNumber(); + List result = new ArrayList(); + + for (String i : _defdoctype.keySet()) { + String[] key = i.split("\\x2E"); + // PDF is not an authoring format + if (stepNumber.equals(Integer.valueOf(key[0])) + && (!key[1].equals("pdf"))) { + result.add(key[1]); // Formats are unique + } + } + return result; + } + /** * Initialize the database: create all necessary default staff defined in the configuration file. */ @@ -394,10 +456,13 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { resultype); } } - // Validations tag - _concycles = loadValidationCycles(children, resultype); - _mapimport = loadFormatMappings(children); + // Validations tag + loadValidationCycles(children, resultype); + // Load steps result document types mapped to file formats + loadFormatMappings(children); + // Load default mapping of file formats to document types for each step + loadDefaultDocTypes(children); if (!getDatabase().getCheckedDB().isInitialized()) { // Load object type definitions @@ -412,7 +477,8 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { child = nlist.item(i); if ("article".equals(child.getNodeName())) { natr = child.getAttributes(); - String type = natr.getNamedItem("type").getNodeValue(); + String type = natr.getNamedItem(TYPE_ATTR) + .getNodeValue(); String uses = null; child = natr.getNamedItem("uses"); if (child != null) { @@ -436,11 +502,9 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { * * @param children * XML nodes - * @return map of document type names to lists of file formats */ - private Map> loadFormatMappings( - final Map children) { - Map> res = new HashMap>(); + private void loadFormatMappings(final Map children) { + _mapimport.clear(); Element maps = (Element) children.get("mappings"); Element doc, imp; String type, format; @@ -451,7 +515,7 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { docs = maps.getElementsByTagName("document"); for (int i = 0; i < docs.getLength(); i++) { doc = (Element) docs.item(i); - type = doc.getAttribute("type"); + type = doc.getAttribute(TYPE_ATTR); if (!type.isEmpty()) { // Read file formats for the document type imports = doc.getElementsByTagName("import"); @@ -464,12 +528,50 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { } } if (!formats.isEmpty()) { - res.put(type, formats); + _mapimport.put(type, formats); } } } } - return res; + } + + /** + * Load default document types from XML configuration. + * + * @param children + * XML nodes + */ + private void loadDefaultDocTypes(final Map children) { + _defdoctype.clear(); + Node child = children.get("default-doctypes"); + NodeList nlist = child.getChildNodes(); + + List listype = getDocumentTypeService().selectAllTypes(); + Map maptype = new HashMap(); + for (Iterator i = listype.iterator(); i.hasNext();) { + DocumentType type = i.next(); + maptype.put(type.getName(), type); + } + for (int i = 0; i < nlist.getLength(); i++) { + child = nlist.item(i); + if (!child.getNodeName().equals("step")) { + continue; + } + + String nstep = child.getAttributes().getNamedItem("number") + .getNodeValue(); + NodeList map = child.getChildNodes(); + for (int j = 0; j < map.getLength(); j++) { + child = map.item(j); + if (!child.getNodeName().equals("mapping")) { + continue; + } + NamedNodeMap natr = child.getAttributes(); + String dext = natr.getNamedItem("extension").getNodeValue(); + String type = natr.getNamedItem(TYPE_ATTR).getNodeValue(); + _defdoctype.put(nstep + "." + dext, maptype.get(type)); + } + } } /** @@ -550,12 +652,11 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { * XML nodes * @param resultype * list of result types - * @return return list of validation cycles */ - private List loadValidationCycles( - final Map children, final List resultype) { + private void loadValidationCycles(final Map children, + final List resultype) { + _concycles.clear(); Node child = children.get("validations"); - List cycles = new ArrayList(); Map datag = XDOM.getNamedChildNodes(child); NamedNodeMap natr; @@ -574,11 +675,10 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { actor[j] = Actor.valueOf(child.getNodeValue()); // Validation step is required } } - cycles.add(new ProjectSettingsValidationCycle(name, actor)); + _concycles.add(new ProjectSettingsValidationCycle(name, actor)); } } - cycles.add(new ProjectSettingsValidationCycle()); // Adds the built-in validation cycle - return cycles; + _concycles.add(new ProjectSettingsValidationCycle()); // Adds the built-in validation cycle } /** @@ -599,7 +699,7 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService { for (int i = 0; i < nlist.getLength(); i++) { child = nlist.item(i); if (child.getNodeName().equals("article")) { - articles.add(child.getAttributes().getNamedItem("type") + articles.add(child.getAttributes().getNamedItem(TYPE_ATTR) .getNodeValue()); } } diff --git a/Workspace/Siman-Common/src/spring/businessServiceContext.xml b/Workspace/Siman-Common/src/spring/businessServiceContext.xml index 8fb2dbb..1329347 100644 --- a/Workspace/Siman-Common/src/spring/businessServiceContext.xml +++ b/Workspace/Siman-Common/src/spring/businessServiceContext.xml @@ -48,8 +48,8 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> - + - + + - + @@ -112,13 +113,13 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Workspace/Siman-Common/src/test/splat/service/TestProjectSettingsService.java b/Workspace/Siman-Common/src/test/splat/service/TestProjectSettingsService.java index f5f27f0..da005b3 100644 --- a/Workspace/Siman-Common/src/test/splat/service/TestProjectSettingsService.java +++ b/Workspace/Siman-Common/src/test/splat/service/TestProjectSettingsService.java @@ -62,9 +62,9 @@ public class TestProjectSettingsService extends BaseTest { * 2. call the method for a xml without mappings.
* 3. call the method for a not existing file.
* Test data :
- * no input parameters
- * no input parameters
- * no input parameters
+ * test/som.xml
+ * test/som-without-mappings.xml
+ * not existing xxx.xml
* * Outcome results:
* @@ -90,6 +90,7 @@ public class TestProjectSettingsService extends BaseTest { /* * geometry: brep model: med loads: c3m results: med */ + _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again try { _projectSettings.configure(ClassLoader.getSystemResource( "test/som.xml").getPath()); @@ -133,4 +134,286 @@ public class TestProjectSettingsService extends BaseTest { LOG.debug(">>>>> END testGetScenarioInfo()"); } + /** + * Test of loading file formats mappings to document types from customization XML file.
+ * Description :
+ * Load customization and check the result.
+ * Action :
+ * 1. call the method for som.xml
+ * 2. call the method for a xml without mappings.
+ * 3. call the method for a not existing file.
+ * Test data :
+ * test/som.xml
+ * test/som-without-mappings.xml
+ * not existing xxx.xml
+ * + * Outcome results:
+ * + *
    + *
  • Following mappings must be loaded:
    + *
      + *
    • step 1 + *
        + *
      • pdf: requirements
      • + *
      • doc: specification
      • + * + *
      • docx: specification
      • + * + *
      • xml: specification
      • + * + *
      + *
    • + *
    • step 2 + *
        + *
      • doc: design
      • + *
      • docx: design
      • + *
      • xml: design
      • + *
      + *
    • + *
    • step 3 + *
        + *
      • doc: memorandum
      • + *
      • docx: memorandum
      • + *
      • xml: memorandum
      • + *
      • sldprt: geometry
      • + * + *
      • sldasm: geometry
      • + * + *
      • part: geometry
      • + * + *
      • py: geometry
      • + * + *
      + *
    • + *
    • step 4 + *
        + *
      • doc: memorandum
      • + *
      • docx: memorandum
      • + *
      • xml: memorandum
      • + *
      • med: model
      • + *
      • py: model
      • + * + *
      + *
    • + *
    + *
  • + *
  • getDefaultDocumentType must always return null
    + *
  • + *
  • Exception is thrown
    + *
  • + *
+ *
+ * + * @throws IOException + * if configuration loading is failed + * @throws SQLException + * if configuration loading is failed + */ + @Test + public void testLoadDefaultDocTypes() throws IOException, SQLException { + LOG.debug(">>>>> BEGIN testLoadDefaultDocTypes()"); + // ////// Load good workflow customization + /* + * geometry: brep model: med loads: c3m results: med + */ + _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again + try { + _projectSettings.configure(ClassLoader.getSystemResource( + "test/som.xml").getPath()); + } catch (FileNotFoundException e) { + Assert.fail("Can't find configuration file: ", e); + } + List steps = _projectSettings.getStepsOf(Scenario.class); + Assert.assertTrue(steps.size() > 0, "No steps are created."); + + for (Step step : steps) { + List defTypes = _projectSettings.getDefaultFormats(step); + Assert.assertNotNull(defTypes, + "getDefaultFormats must always return not null list:"); + switch (step.getNumber()) { + case 1: + Assert.assertEquals(defTypes.size(), 4); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "pdf")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "pdf").getName(), + "requirements"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "doc")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "doc").getName(), + "specification"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "docx")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "docx").getName(), + "specification"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "xml")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "xml").getName(), + "specification"); + break; + case 2: + Assert.assertEquals(defTypes.size(), 3); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "pdf")); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "xml")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "xml").getName(), + "design"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "doc")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "doc").getName(), + "design"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "docx")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "docx").getName(), + "design"); + break; + case 3: + Assert.assertEquals(defTypes.size(), 7); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "pdf")); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "sldprt")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "sldprt").getName(), + "geometry"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "sldasm")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "sldasm").getName(), + "geometry"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "part")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "part").getName(), + "geometry"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "py")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "py").getName(), + "geometry"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "doc")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "doc").getName(), + "memorandum"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "docx")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "docx").getName(), + "memorandum"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "xml")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "xml").getName(), + "memorandum"); + break; + case 4: + Assert.assertEquals(defTypes.size(), 5); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "pdf")); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "med")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "med").getName(), + "model"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "py")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "py").getName(), + "model"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "doc")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "doc").getName(), + "memorandum"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "docx")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "docx").getName(), + "memorandum"); + Assert.assertNotNull(_projectSettings + .getDefaultDocumentType(step, "xml")); + Assert.assertEquals(_projectSettings + .getDefaultDocumentType(step, "xml").getName(), + "memorandum"); + break; + default: + Assert.assertEquals(defTypes.size(), 0); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "pdf")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "doc")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "docx")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "xml")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "sldprt")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "sldasm")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "part")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "py")); + Assert.assertNull(_projectSettings.getDefaultDocumentType( + step, "med")); + } + } + + // ////// Load workflow customization with empty mappings + _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again + try { + _projectSettings.configure(ClassLoader.getSystemResource( + "test/som-without-mappings.xml").getPath()); + } catch (FileNotFoundException e) { + Assert.fail("Can't find configuration file: ", e); + } + steps = _projectSettings.getStepsOf(Scenario.class); + Assert.assertTrue(steps.size() > 0, "No steps are created."); + for (Step step : steps) { + List defTypes = _projectSettings.getDefaultFormats(step); + Assert.assertNotNull(defTypes, + "getDefaultFormats must always return not null list:"); + Assert.assertEquals(defTypes.size(), 0); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "pdf")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "doc")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "docx")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "xml")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "sldprt")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "sldasm")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "part")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "py")); + Assert.assertNull(_projectSettings.getDefaultDocumentType(step, + "med")); + } + + // ////// Load workflow customization from not existing file + _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again + try { + _projectSettings.configure(ClassLoader.getSystemResource("/") + .getPath() + + "test/xxx.xml"); + Assert + .fail("Customization loading must fail for not existing configuration file."); + } catch (FileNotFoundException e) { + LOG.debug("Configuration file must not be found.", e); + } + + LOG.debug(">>>>> END testLoadDefaultDocTypes()"); + } } diff --git a/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java b/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java index 364e55f..cb12d2b 100644 --- a/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java +++ b/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java @@ -11,6 +11,7 @@ package test.splat.service; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -20,13 +21,14 @@ import org.splat.dal.bo.som.DocumentType; import org.splat.dal.bo.som.Publication; import org.splat.dal.bo.som.Scenario; import org.splat.dal.bo.som.Study; +import org.splat.dal.dao.som.ScenarioDAO; import org.splat.kernel.InvalidPropertyException; +import org.splat.kernel.MismatchException; import org.splat.kernel.MissedPropertyException; import org.splat.kernel.MultiplyDefinedException; +import org.splat.kernel.NotApplicableException; import org.splat.log.AppLogger; -import org.splat.service.DocumentService; import org.splat.service.DocumentTypeService; -import org.splat.service.ProjectElementService; import org.splat.service.PublicationService; import org.splat.service.ScenarioService; import org.splat.service.StepService; @@ -65,11 +67,11 @@ public class TestScenarioService extends BaseTest { private transient ScenarioService _scenarioService; /** - * The DocumentService. Later injected by Spring. + * The Scenario DAO. Later injected by Spring. */ @Autowired - @Qualifier("documentService") - private transient DocumentService _documentService; + @Qualifier("scenarioDAO") + private transient ScenarioDAO _scenarioDAO; /** * The PublicationService. Later injected by Spring. @@ -85,13 +87,6 @@ public class TestScenarioService extends BaseTest { @Qualifier("stepService") private transient StepService _stepService; - /** - * The ProjectElementService. Later injected by Spring. - */ - @Autowired - @Qualifier("projectElementService") - private transient ProjectElementService _projectElementService; - /** * The ProjectSettingsService. Later injected by Spring. */ @@ -109,7 +104,7 @@ public class TestScenarioService extends BaseTest { /** * Test of getting a scenario content for building siman-salome.conf.
* Description :
- * Create a scenario try to get an info for it.
+ * Create a scenario and try to get an info for it.
* Action :
* 1. call the method for an existing scenario id.
* 2. call the method for a not existing scenario id.
@@ -185,42 +180,28 @@ public class TestScenarioService extends BaseTest { Assert.assertEquals(doc.getTitle(), docName); Assert.assertNotNull(doc.getFiles(), "Document files list must not be null."); - Assert.assertTrue(doc.getFiles().size() > 1, - "Document must have more then 1 attached file."); - + Assert + .assertTrue(doc.getFiles().size() > 1, + "Document must have more then 1 attached file."); + for (FileDTO file : doc.getFiles()) { Assert.assertNotNull(file.getPath(), "File path must not be null."); Assert.assertFalse(file.getPath().isEmpty(), "File path must not be empty."); - /* - - - - - - - - - - - - - - + /* + * */ // Check state and processing instruction String fileFormat = file.getPath().substring( file.getPath().lastIndexOf('.') + 1); -/* if (_projectSettings.doImport(dtype.getName(), - fileFormat)) { - Assert.assertTrue(file.isResult(), - "The file must be a result file."); - } else { - Assert.assertFalse(file.isResult(), - "The file must be a source file."); - } -*/ if ((docIndex % 2) == 0) { // New + /* + * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file + * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); } + */if ((docIndex % 2) == 0) { // New Assert.assertEquals(file.getState(), 'Y', "File state must be actual ('Y')."); if (_projectSettings.doImport(dtype.getName(), @@ -262,9 +243,74 @@ public class TestScenarioService extends BaseTest { } /** - * Create a transient KnowledgeElement for tests. + * Test check-in scenario operation to be performed after SALOME session.
+ * Description :
+ * Create a scenario and try to check-in it with some simulated SALOME results data.
+ * Action :
+ * 1. call the method for an existing scenario id.
+ * 2. call the method for a not existing scenario id.
+ * Test data :
+ * no input parameters
+ * no input parameters
+ * + * Outcome results:
+ * + *
    + *
  • New version of existing documents must be created and new documents must be imported for documents with zero id. Correct + * relations must be created.
    + *
  • + *
  • Exception is thrown
    + *
  • + *
+ *
+ * + * @throws InvalidPropertyException + * if an invalid property is used when creating objects + * @throws MultiplyDefinedException + * when trying to create an object with already existing id + * @throws MissedPropertyException + * if a mandatory property is not defined for an object to be created + * @throws IOException + * if scenario creation is failed + * @throws SQLException + * if scenario creation is failed + * @throws NotApplicableException + * if checkin failed + * @throws MismatchException + * if checkin failed + */ + @Test + public void testCheckin() throws InvalidPropertyException, + MissedPropertyException, MultiplyDefinedException, IOException, + SQLException, MismatchException, NotApplicableException { + LOG.debug(">>>>> BEGIN testCheckin()"); + _projectSettings.configure(ClassLoader + .getSystemResource("test/som.xml").getPath()); + long scenarioId = createScenario(); + Scenario aScen = _scenarioDAO.get(scenarioId); + User user = aScen.getAuthor(); + long userId = user.getIndex(); // TODO: get id of a test user + // Call DAO's create method for a good transient knowledge element. + List steps = new ArrayList(); + + _scenarioService.checkin(scenarioId, userId, steps); + + // Call DAO's get method for a not existing id. + try { + _scenarioService.checkin(-1, userId, steps); + Assert + .fail("Check in for scenario with not existing id must be failed."); + } catch (Exception e) { + LOG.debug("Expected exception is thrown: " + + e.getClass().getSimpleName() + ": " + e.getMessage()); + } + LOG.debug(">>>>> END testCheckin()"); + } + + /** + * Create a persistent scenario for tests. * - * @return a transient KnowledgeElement + * @return a persistent scenario * @throws InvalidPropertyException * if an invalid property is used when creating objects * @throws MultiplyDefinedException @@ -284,7 +330,8 @@ public class TestScenarioService extends BaseTest { // Load workflow customization try { - _projectSettings.configure(ClassLoader.getSystemResource("test/som.xml").getPath()); + _projectSettings.configure(ClassLoader.getSystemResource( + "test/som.xml").getPath()); } catch (FileNotFoundException e) { Assert.fail("Can't find som.xml: ", e); } @@ -327,12 +374,12 @@ public class TestScenarioService extends BaseTest { List dtypes = _documentTypeService .selectTypesOf(step); for (DocumentType dtype : dtypes) { - dprop.setName("document" + i++).setType(dtype).setFormat( - "brep"); + dprop.setName("document" + i++).setType(dtype) + .setFormat("brep"); // Create a document published in the scenario // document: document type[0] - first type used on the step - // .brep - // .med + // .brep + // .med Publication pub = _stepService.createDocument(aScStep, dprop); Assert.assertNotNull(pub.getOwner(), "The publication must be attached to the scenario."); @@ -346,29 +393,29 @@ public class TestScenarioService extends BaseTest { // Attach a file ht.saveOrUpdate(pub.value()); ht.saveOrUpdate(_publicationService.attach(pub, "med")); - + // Create a document with outdated publication - dprop.setName("document" + i++).setType(dtype).setFormat( - "brep"); + dprop.setName("document" + i++).setType(dtype) + .setFormat("brep"); // Create a document published in the scenario // document: document type[0] - first type used on the step - // .brep - // .med + // .brep + // .med pub = _stepService.createDocument(aScStep, dprop); Assert.assertNotNull(pub.getOwner(), "The publication must be attached to the scenario."); Assert.assertEquals(pub.getOwner().getIndex(), aScenario .getIndex(), "The publication was not attached to the scenario."); - + pub.setIsnew('O'); aScenario.add(pub); ht.saveOrUpdate(pub); - + // Attach a file ht.saveOrUpdate(pub.value()); ht.saveOrUpdate(_publicationService.attach(pub, "med")); - + } if (dtypes.size() <= 0) { LOG.debug("No document types are found for scenario step " + i); diff --git a/Workspace/Siman/WebContent/conf/my.xml b/Workspace/Siman/WebContent/conf/my.xml index 6697d17..38f8d2c 100644 --- a/Workspace/Siman/WebContent/conf/my.xml +++ b/Workspace/Siman/WebContent/conf/my.xml @@ -2,36 +2,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Workspace/Siman/WebContent/conf/som.xml b/Workspace/Siman/WebContent/conf/som.xml index a8cb18e..af7c4a6 100644 --- a/Workspace/Siman/WebContent/conf/som.xml +++ b/Workspace/Siman/WebContent/conf/som.xml @@ -211,4 +211,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Workspace/Siman/src/org/splat/simer/ApplicationSettings.java b/Workspace/Siman/src/org/splat/simer/ApplicationSettings.java index a95b58b..9309647 100644 --- a/Workspace/Siman/src/org/splat/simer/ApplicationSettings.java +++ b/Workspace/Siman/src/org/splat/simer/ApplicationSettings.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; -import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -208,10 +207,6 @@ public class ApplicationSettings implements ServletContextAware { * Named search filters. */ private transient Map> _filter = null; - /** - * Default document types structured by step.formats. - */ - private transient Map _defdoctype = null; /** * Available template files. */ @@ -862,14 +857,14 @@ public class ApplicationSettings implements ServletContextAware { gprop.put("title", ""); gprop.put("context", new ArrayList()); - _defdoctype = new LinkedHashMap(); - _tempfile = new HashMap(); - _viewermap = new String[0]; - _convertmap = new HashMap(); _filter = new HashMap>(); _filter.put("study", fprop); _filter.put("knowledge", gprop); + _tempfile = new HashMap(); + _viewermap = new String[0]; + _convertmap = new HashMap(); + // Customization (must be done after above default settings) File config = new File(filename); if (config.exists()) { @@ -879,8 +874,6 @@ public class ApplicationSettings implements ServletContextAware { + config.getAbsolutePath() + "\", using default settings"); } // Settings based on the customization - _bars = new HashMap(); // May be empty if no module installed - configureToolbars(); } @@ -888,12 +881,14 @@ public class ApplicationSettings implements ServletContextAware { * Configure toolbars for steps. */ private void configureToolbars() { + _bars = new HashMap(); // May be empty if no module installed + List steps = getProjectSettings() .getAllSteps(); for (Iterator i = steps.iterator(); i .hasNext();) { ProjectSettingsService.Step step = i.next(); - List formats = getDefaultFormats(step); + List formats = getProjectSettings().getDefaultFormats(step); if (formats.isEmpty()) { continue; } @@ -912,8 +907,8 @@ public class ApplicationSettings implements ServletContextAware { module.add(command); String[] parsed = command.split("/"); String[] name = parsed[parsed.length - 1].split("\\x2E"); - DocumentType dtype = MY_APP._defdoctype.get(step.getNumber() - + "." + format); + DocumentType dtype = getProjectSettings() + .getDefaultDocumentType(step, format); String docname = ""; if (dtype != null) { docname = dtype.getName(); @@ -1000,11 +995,10 @@ public class ApplicationSettings implements ServletContextAware { return MY_APP._convertmap.get(format + type.getName()); // May be null; } - public static DocumentType getDefaultDocumentType(final Step step, + public DocumentType getDefaultDocumentType(final Step step, final String format) { - String[] table = format.split("\\x2E"); - return MY_APP._defdoctype.get(step.getNumber() + "." - + table[table.length - 1]); // May be null + return getProjectSettings().getDefaultDocumentType(step.getStep(), + format); // May be null } public static String getDownloadURL(final User user) { @@ -1058,28 +1052,11 @@ public class ApplicationSettings implements ServletContextAware { // Private services // ============================================================================================================================== - private List getDefaultFormats( - final ProjectSettingsService.Step step) { - Set keys = _defdoctype.keySet(); - int number = step.getNumber(); - List result = new ArrayList(); - - for (Iterator i = keys.iterator(); i.hasNext();) { - String[] key = i.next().split("\\x2E"); - if (Integer.valueOf(key[0]) != number) { - continue; - } - if (key[1].equals("pdf")) { - continue; // PDF is not an authoring format - } - result.add(key[1]); // Formats are unique - } - return result; - } - /** * Load customization of workflow from the given XML file. - * @param config the XML configuration file + * + * @param config + * the XML configuration file */ private void loadCustomization(final File config) { try { @@ -1091,9 +1068,6 @@ public class ApplicationSettings implements ServletContextAware { HashMap children = XDOM.getNamedChildNodes(conf .getDocumentElement()); - // Load default document types. - loadDocTypes(children); - // Modules tag loadModules(children); @@ -1178,44 +1152,6 @@ public class ApplicationSettings implements ServletContextAware { } } - /** - * Load default document types from XML configuration. - * - * @param children - * XML nodes - */ - private void loadDocTypes(final Map children) { - Node child = children.get("default-doctypes"); - NodeList nlist = child.getChildNodes(); - - List listype = getDocumentTypeService().selectAllTypes(); - Map maptype = new HashMap(); - for (Iterator i = listype.iterator(); i.hasNext();) { - DocumentType type = i.next(); - maptype.put(type.getName(), type); - } - for (int i = 0; i < nlist.getLength(); i++) { - child = nlist.item(i); - if (!child.getNodeName().equals("step")) { - continue; - } - - String nstep = child.getAttributes().getNamedItem("number") - .getNodeValue(); - NodeList map = child.getChildNodes(); - for (int j = 0; j < map.getLength(); j++) { - child = map.item(j); - if (!child.getNodeName().equals("mapping")) { - continue; - } - NamedNodeMap natr = child.getAttributes(); - String dext = natr.getNamedItem("extension").getNodeValue(); - String type = natr.getNamedItem("type").getNodeValue(); - _defdoctype.put(nstep + "." + dext, maptype.get(type)); - } - } - } - /** * Get the documentTypeService. * diff --git a/Workspace/Siman/src/org/splat/simer/ImportDocumentAction.java b/Workspace/Siman/src/org/splat/simer/ImportDocumentAction.java index beabeaa..c86a7d5 100644 --- a/Workspace/Siman/src/org/splat/simer/ImportDocumentAction.java +++ b/Workspace/Siman/src/org/splat/simer/ImportDocumentAction.java @@ -4,27 +4,28 @@ import java.io.File; import java.io.FileNotFoundException; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; -import java.util.Vector; import org.splat.dal.bo.kernel.User; -import org.splat.manox.Reader; -import org.splat.manox.Toolbox; import org.splat.dal.bo.som.Document; +import org.splat.dal.bo.som.DocumentType; import org.splat.dal.bo.som.ProgressState; +import org.splat.dal.bo.som.Publication; +import org.splat.manox.Reader; +import org.splat.manox.Toolbox; import org.splat.service.DocumentService; import org.splat.service.DocumentTypeService; import org.splat.service.PublicationService; import org.splat.service.StepService; import org.splat.service.technical.ProjectSettingsService; import org.splat.service.technical.RepositoryService; -import org.splat.dal.bo.som.Publication; -import org.splat.dal.bo.som.DocumentType; import org.splat.som.Revision; import org.splat.som.Step; +import org.splat.wapp.Constants; /** * Action for adding a document into a study step. @@ -36,15 +37,24 @@ public class ImportDocumentAction extends UploadBaseNextAction { */ private static final long serialVersionUID = 2587822564883588556L; - private List doctypes = null; - private long doctype = 0; - private String docref = null; // Reference extracted from the imported file, if exist - private String docver = ""; // Version number extracted from the imported file, if exist - private String date = ""; // Date extracted from the imported file, if exist + private transient List _documentTypes = null; + private long _documentType = 0; + /** + * Reference extracted from the imported file, if exist. + */ + private String _reference = null; + /** + * Version number extracted from the imported file, if exist. + */ + private String _version = ""; + /** + * Date extracted from the imported file, if exist. + */ + private String _documentDate = ""; /** * Injected project settings service. */ - private ProjectSettingsService _projectSettingsService; + private ProjectSettingsService _projectSettings; /** * Injected publication service. */ @@ -64,35 +74,30 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Injected repository service. */ - private RepositoryService _repositoryService; + private RepositoryService _repositoryService; /** - * Value of the menu property. - * It can be: none, create, open, study, knowledge, sysadmin, help. + * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help. */ private String _menuProperty; - + /** - * Value of the title bar property. - * It can be: study, knowledge. + * Value of the title bar property. It can be: study, knowledge. */ private String _titleProperty; - + /** - * Value of the tool bar property. - * It can be: none, standard, study, back. + * Value of the tool bar property. It can be: none, standard, study, back. */ private String _toolProperty; - + /** - * Value of the left menu property. - * It can be: open, study, knowledge, scenario. + * Value of the left menu property. It can be: open, study, knowledge, scenario. */ private String _leftMenuProperty; - + /** - * Property that indicates whether the current open study is editable or not. - * On the screen it looks like pen on the status icon, pop-up menu also can be called. - * It is necessary for correct building the title bar. + * Property that indicates whether the current open study is editable or not. On the screen it looks like pen on the status icon, pop-up + * menu also can be called. It is necessary for correct building the title bar. */ private String _editDisabledProperty = "false"; @@ -102,21 +107,23 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Initialize the operation. + * * @return SUCCESS in success, otherwise - ERROR */ public String doInitialize() { - - setMenuProperty("study"); - setTitleProperty("study"); + + setMenuProperty(Constants.STUDY_MENU); + setTitleProperty(Constants.STUDY_MENU); setEditDisabledProperty("true"); if ("true".equals(getWriteAccess())) { - setToolProperty("study"); + setToolProperty(Constants.STUDY_MENU); } else { - setToolProperty("none"); + setToolProperty(Constants.NONE); } - setLeftMenuProperty("study"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - + setLeftMenuProperty(Constants.STUDY_MENU); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); + User user = getConnectedUser(); File updir = getRepositoryService().getDownloadDirectory(user); File upfile = new File(updir.getPath() + "/" + filename); @@ -125,125 +132,172 @@ public class ImportDocumentAction extends UploadBaseNextAction { mystudy = getOpenStudy(); Step step = mystudy.getSelectedStep(); - doctypes = getStepService().getValidDocumentTypes(step); + _documentTypes = getStepService().getValidDocumentTypes(step); deftype = getApplicationSettings().getDefaultDocumentType(step, filext); - defuses = new Vector(); + defuses = new ArrayList(); state = ProgressState.inWORK; + String res = ERROR; + if (extractProperties(upfile, filext)) { + if (docname == null) { + docname = table[0]; + for (int i = 1; i < table.length - 1; i++) { + docname = docname + "." + table[i]; + } + } + if (deftype != null) { + setupDefaultUses(deftype); + } + + DocumentType[] types = _documentTypes + .toArray(new DocumentType[_documentTypes.size()]); + DocumentTypeComparator compare = new DocumentTypeComparator(); + Arrays.sort(types, compare); + _documentTypes = Arrays.asList(types); + res = SUCCESS; + } + return res; + } + + /** + * Extract properties from the uploaded file. + * + * @param upfile + * the file to parse + * @param filext + * the file extension + * @return true if succeeded, false if error + */ + private boolean extractProperties(final File upfile, final String filext) { + boolean isOk = true; Reader tool = Toolbox.getReader(upfile); - if (tool != null) { + if (tool == null) { + if ("pdf".equals(filext)) { + state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ? + } + } else { String fileref = tool.extractProperty("reference"); String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced - for (Iterator i = doctypes.iterator(); i.hasNext();) { + for (Iterator i = _documentTypes.iterator(); i + .hasNext();) { DocumentType type = i.next(); - if (!type.getName().equals(filetype)) - continue; - deftype = type; - doctype = type.getIndex(); // Disables the document type field - break; + if (type.getName().equals(filetype)) { + deftype = type; + _documentType = type.getIndex(); // Disables the document type field + break; + } } if (fileref != null) { - Document slot = getDocumentService().selectDocument(fileref, - new Revision().toString()); - if (slot == null) { - setErrorCode("message.error.reference.undefined"); - - setToolProperty("none"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - - return ERROR; - } else { - if (!slot.isUndefined()) { - setErrorCode("message.error.reference.duplicate"); - - setToolProperty("none"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - - return ERROR; - } - docref = fileref; // Disables document name and state fields - deftype = slot.getType(); // Just in case - doctype = deftype.getIndex(); // Disables the document type field - } + isOk = findTypeByDocRef(fileref); } - if (filever != null) - try { - Revision.Format get = new Revision.Format( - getProjectSettings().getRevisionPattern()); - Revision version = get.parse(filever); - if (version.isNull()) - throw new ParseException(filever, filever.length() - 1); - if (!version.isMinor()) - state = ProgressState.inCHECK; - docver = version.toString(); - } catch (ParseException e) { - setErrorCode("message.error.format.version"); - - setToolProperty("none"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - - return ERROR; + if (isOk) { + if (filever != null) { + try { + Revision.Format get = new Revision.Format( + getProjectSettings().getRevisionPattern()); + Revision version = get.parse(filever); + if (version.isNull()) { + throw new ParseException(filever, + filever.length() - 1); + } + if (!version.isMinor()) { + state = ProgressState.inCHECK; + } + _version = version.toString(); + } catch (ParseException e) { + setError("message.error.format.version"); + isOk = false; + } } - docname = tool.extractProperty("title"); // Property kept even if the file is not referenced - date = tool.extractProperty("date"); - if (date != null) { - ResourceBundle locale = ResourceBundle.getBundle("som", - getApplicationSettings().getCurrentLocale()); - SimpleDateFormat check = new SimpleDateFormat( - locale.getString("date.format")); - try { - check.parse(date); - } catch (ParseException e) { - setErrorCode("message.error.format.date"); - - setToolProperty("none"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - - return ERROR; + if (isOk) { + docname = tool.extractProperty("title"); // Property kept even if the file is not referenced + _documentDate = tool.extractProperty("date"); + if (_documentDate == null) { + _documentDate = ""; + } else { + ResourceBundle locale = ResourceBundle.getBundle("som", + getApplicationSettings().getCurrentLocale()); + SimpleDateFormat check = new SimpleDateFormat(locale + .getString("date.format")); + try { + check.parse(_documentDate); + } catch (ParseException e) { + setError("message.error.format.date"); + isOk = false; + } + } } - } else - date = ""; - } else if (filext.equals("pdf")) - state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ? - if (docname == null) { - docname = table[0]; - for (int i = 1; i < table.length - 1; i++) - docname = docname + "." + table[i]; + } + } + return isOk; + } + + /** + * Find document type by document reference. + * + * @param fileref + * the document reference + * @return true if succeeded, false if error + */ + private boolean findTypeByDocRef(final String fileref) { + boolean isOk = true; + Document slot = getDocumentService().selectDocument(fileref, + new Revision().toString()); + if (slot == null) { + setError("message.error.reference.undefined"); + isOk = false; + } else { + if (slot.isUndefined()) { + _reference = fileref; // Disables document name and state fields + deftype = slot.getType(); // Just in case + _documentType = deftype.getIndex(); // Disables the document type field + } else { + setError("message.error.reference.duplicate"); + isOk = false; + } } - if (deftype != null) - setupDefaultUses(deftype); + return isOk; + } - DocumentType[] types = doctypes.toArray(new DocumentType[doctypes - .size()]); - DocumentTypeComparator compare = new DocumentTypeComparator(); - Arrays.sort(types, compare); - doctypes = Arrays.asList(types); + /** + * Set error message and menus. + * + * @param errorCode + * error message key + */ + private void setError(final String errorCode) { + setErrorCode(errorCode); - return SUCCESS; + setToolProperty(Constants.NONE); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); } /** * Perform import of a document. + * * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error */ public String doImport() { - // ------------------------- - - setMenuProperty("study"); - setTitleProperty("study"); + + setMenuProperty(Constants.STUDY_MENU); + setTitleProperty(Constants.STUDY_MENU); setEditDisabledProperty("true"); - initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty); - - if (action == ToDo.cancel) + initializationScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty); + + if (action == ToDo.cancel) { return "cancel"; - if (doctype == 0) { + } + if (_documentType == 0) { setErrorCode("message.error.import.type"); - - setToolProperty("none"); - setLeftMenuProperty("study"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - + + setToolProperty(Constants.NONE); + setLeftMenuProperty(Constants.STUDY_MENU); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); + return ERROR; } try { @@ -251,7 +305,8 @@ public class ImportDocumentAction extends UploadBaseNextAction { mystudy = getOpenStudy(); User user = getConnectedUser(); Step step = mystudy.getSelectedStep(); - DocumentType type = getDocumentTypeService().selectType((int)doctype); + DocumentType type = getDocumentTypeService().selectType( + (int) _documentType); File updir = getRepositoryService().getDownloadDirectory(user); File upfile = new File(updir.getPath() + "/" + filename); String[] table = filename.split("\\x2E"); @@ -260,15 +315,17 @@ public class ImportDocumentAction extends UploadBaseNextAction { Document.Properties dprop = new Document.Properties(); Publication addoc; - if (docref.length() == 0) { // Importation of a foreign document - // TODO: Extract property of supported documents (DOCX, ODT...) - addoc = getStepService().createDocument(step, dprop.setName(docname) - .setType(type).setFormat(table[table.length - 1]) - .setAuthor(user)); + if (_reference.length() == 0) { // Importation of a foreign document + // TODO: Extract property of supported documents (DOCX, ODT...) + addoc = getStepService().createDocument( + step, + dprop.setName(docname).setType(type).setFormat( + table[table.length - 1]).setAuthor(user)); updir = addoc.getSourceFile().asFile(); - if (LOG.isInfoEnabled()) + if (LOG.isInfoEnabled()) { LOG.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\"."); + } upfile.renameTo(updir); try { getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done @@ -279,35 +336,38 @@ public class ImportDocumentAction extends UploadBaseNextAction { getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound } } else { // Importation of a previously created template-based document - if (date.length() > 0) { + if (_documentDate.length() > 0) { ResourceBundle locale = ResourceBundle.getBundle("som", getApplicationSettings().getCurrentLocale()); - SimpleDateFormat get = new SimpleDateFormat( - locale.getString("date.format")); - dprop.setDate(get.parse(date)); + SimpleDateFormat get = new SimpleDateFormat(locale + .getString("date.format")); + dprop.setDate(get.parse(_documentDate)); } - addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName( - docname)); + addoc = getStepService().assignDocument(step, + dprop.setReference(_reference).setName(docname)); updir = addoc.getSourceFile().asFile(); - if (LOG.isInfoEnabled()) + if (LOG.isInfoEnabled()) { LOG.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\"."); + } upfile.renameTo(updir); try { - if (docver.length() > 0) + if (_version.length() > 0) { getPublicationService().saveAs(addoc, - new Revision(docver)); - else + new Revision(_version)); + } else { getPublicationService().saveAs(addoc, state); + } } catch (FileNotFoundException saverror) { Thread.sleep(1000); LOG.info("Waiting for the file."); upfile.renameTo(updir); - if (docver.length() > 0) + if (_version.length() > 0) { getPublicationService().saveAs(addoc, - new Revision(docver)); - else + new Revision(_version)); + } else { getPublicationService().saveAs(addoc, state); + } } mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document } @@ -335,11 +395,12 @@ public class ImportDocumentAction extends UploadBaseNextAction { LOG.error("Reason:", error); setErrorCode("message.error.internal"); } - - setToolProperty("none"); - setLeftMenuProperty("study"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - + + setToolProperty(Constants.NONE); + setLeftMenuProperty(Constants.STUDY_MENU); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); + return ERROR; } @@ -347,72 +408,112 @@ public class ImportDocumentAction extends UploadBaseNextAction { // Getters and setters // ============================================================================================================================== + /** + * Date extracted from the imported file, if exist. + * + * @return the file date + */ public String getDocumentDate() { - // -------------------------------- - return date; + return _documentDate; } public List getDocumentTypes() { - // --------------------------------------------- - return doctypes; + return _documentTypes; } + /** + * Get document type id. + * + * @return document type id + */ public long getDocumentType() { - // ----------------------------- - return doctype; + return _documentType; } + /** + * Get reference extracted from the imported file, if exist. + * + * @return the document reference + */ public String getReference() { - // ----------------------------- - return docref; + return _reference; } + /** + * Get version number extracted from the imported file, if exist. + * + * @return the document version + */ public String getVersion() { - // --------------------------- - return docver; + return _version; } + /** + * Set date extracted from the imported file. + * + * @param date + * the date to set + */ public void setDocumentDate(final String date) { - // ----------------------------------------- - this.date = date; + this._documentDate = date; } + /** + * Set document name entered by the user if enabled. + * + * @param name + * the document name + */ public void setDocumentName(final String name) { - // ----------------------------------------- this.docname = name; // Name entered by the user if enabled } public void setDocumentTitle(final String name) { // Called even if DocumentName is enabled - // ----------------------------------------- - if (this.docname == null) + if (this.docname == null) { this.docname = name; + } } + /** + * Set document type id. + * + * @param value + * the id as string + */ public void setDocumentType(final String value) { - // ------------------------------------------ - this.doctype = Integer.valueOf(value); + this._documentType = Integer.valueOf(value); } public void setDefaultDocumentState(final String state) { // Called even if DocumentState is enabled - // -------------------------------------------------- - if (this.state == null) + if (this.state == null) { this.state = ProgressState.valueOf(state); + } } public void setDefaultDocumentType(final String value) { // Called even if DocumentType is enabled - // -------------------------------------------------- - if (this.doctype == 0) - this.doctype = Integer.valueOf(value); + if (this._documentType == 0) { + this._documentType = Integer.valueOf(value); + } } + /** + * Set document reference extracted from the imported file, if exist. + * + * @param value + * the reference + */ public void setReference(final String value) { - // --------------------------------------- - this.docref = value; + this._reference = value; } + /** + * Set version number extracted from the imported file, if exist. + * + * @param value + * the version + */ public void setVersion(final String value) { - // ------------------------------------- - this.docver = value; + this._version = value; } /** @@ -421,7 +522,7 @@ public class ImportDocumentAction extends UploadBaseNextAction { * @return Project settings service */ private ProjectSettingsService getProjectSettings() { - return _projectSettingsService; + return _projectSettings; } /** @@ -430,8 +531,9 @@ public class ImportDocumentAction extends UploadBaseNextAction { * @param projectSettingsService * project settings service */ - public void setProjectSettings(final ProjectSettingsService projectSettingsService) { - _projectSettingsService = projectSettingsService; + public void setProjectSettings( + final ProjectSettingsService projectSettingsService) { + _projectSettings = projectSettingsService; } /** @@ -449,12 +551,14 @@ public class ImportDocumentAction extends UploadBaseNextAction { * @param publicationService * the publicationService to set */ - public void setPublicationService(final PublicationService publicationService) { + public void setPublicationService( + final PublicationService publicationService) { _publicationService = publicationService; } /** * Get the stepService. + * * @return the stepService */ public StepService getStepService() { @@ -463,7 +567,9 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the stepService. - * @param stepService the stepService to set + * + * @param stepService + * the stepService to set */ public void setStepService(final StepService stepService) { _stepService = stepService; @@ -471,6 +577,7 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Get the documentService. + * * @return the documentService */ public DocumentService getDocumentService() { @@ -479,7 +586,9 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the documentService. - * @param documentService the documentService to set + * + * @param documentService + * the documentService to set */ public void setDocumentService(final DocumentService documentService) { _documentService = documentService; @@ -487,6 +596,7 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Get the repositoryService. + * * @return the repositoryService */ public RepositoryService getRepositoryService() { @@ -495,7 +605,9 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the repositoryService. - * @param repositoryService the repositoryService to set + * + * @param repositoryService + * the repositoryService to set */ public void setRepositoryService(final RepositoryService repositoryService) { _repositoryService = repositoryService; @@ -503,6 +615,7 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Get the documentTypeService. + * * @return the documentTypeService */ public DocumentTypeService getDocumentTypeService() { @@ -511,14 +624,18 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the documentTypeService. - * @param documentTypeService the documentTypeService to set + * + * @param documentTypeService + * the documentTypeService to set */ - public void setDocumentTypeService(final DocumentTypeService documentTypeService) { + public void setDocumentTypeService( + final DocumentTypeService documentTypeService) { _documentTypeService = documentTypeService; } - + /** * Get the menuProperty. + * * @return the menuProperty */ public String getMenuProperty() { @@ -527,14 +644,17 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the menuProperty. - * @param menuProperty the menuProperty to set + * + * @param menuProperty + * the menuProperty to set */ public void setMenuProperty(final String menuProperty) { this._menuProperty = menuProperty; } - + /** * Get the _titleProperty. + * * @return the _titleProperty */ public String getTitleProperty() { @@ -542,8 +662,10 @@ public class ImportDocumentAction extends UploadBaseNextAction { } /** - * Set the _titleProperty. - * @param _titleProperty the titleProperty to set + * Set the titleProperty. + * + * @param titleProperty + * the titleProperty to set */ public void setTitleProperty(final String titleProperty) { _titleProperty = titleProperty; @@ -551,6 +673,7 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Get the editDisabledProperty. + * * @return the editDisabledProperty */ public final String getEditDisabledProperty() { @@ -559,7 +682,9 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the editDisabledProperty. - * @param editDisabledProperty the editDisabledProperty to set + * + * @param editDisabledProperty + * the editDisabledProperty to set */ public final void setEditDisabledProperty(final String editDisabledProperty) { _editDisabledProperty = editDisabledProperty; @@ -567,6 +692,7 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Get the toolProperty. + * * @return the toolProperty */ public String getToolProperty() { @@ -575,14 +701,17 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the toolProperty. - * @param toolProperty the toolProperty to set + * + * @param toolProperty + * the toolProperty to set */ public void setToolProperty(final String toolProperty) { _toolProperty = toolProperty; } - + /** * Get the leftMenuProperty. + * * @return the leftMenuProperty */ public String getLeftMenuProperty() { @@ -591,7 +720,9 @@ public class ImportDocumentAction extends UploadBaseNextAction { /** * Set the leftMenuProperty. - * @param leftMenuProperty the leftMenuProperty to set + * + * @param leftMenuProperty + * the leftMenuProperty to set */ public void setLeftMenuProperty(final String leftMenuProperty) { _leftMenuProperty = leftMenuProperty; diff --git a/Workspace/Siman/src/org/splat/simer/UploadAction.java b/Workspace/Siman/src/org/splat/simer/UploadAction.java index b9a6e6f..4b9432b 100644 --- a/Workspace/Siman/src/org/splat/simer/UploadAction.java +++ b/Workspace/Siman/src/org/splat/simer/UploadAction.java @@ -4,161 +4,267 @@ import java.io.File; import org.splat.kernel.Do; import org.splat.service.technical.RepositoryService; -import org.splat.dal.dao.som.Database; - +import org.splat.wapp.Constants; +/** + * Action for uploading a file into the user's download directory. + */ public class UploadAction extends Action { - private File upload = null; - private String uploadMimeType = null; - private String uploadFileName = null; + /** + * Serialization version id. + */ + private static final long serialVersionUID = 6003880772275115923L; + + /** + * Uploaded file. + */ + private transient File _upload = null; + /** + * Mime type of the uploaded file. + */ + private transient String _uploadMimeType = null; + /** + * Uploaded file name. + */ + private transient String _uploadFileName = null; - private ToDo action; // Action to do - private String next = null; // Action to which the uploaded file is passed - private String index = null; // Depending on the next action, document index to which the action applies + /** + * Action to do. + */ + private transient ToDo _action; + /** + * Action to which the uploaded file is passed. + */ + private String _nextAction = null; + /** + * Depending on the next action, document index to which the action applies. + */ + private String _index = null; /** * Injected repository service. */ private RepositoryService _repositoryService; - + /** - * Value of the menu property. - * It can be: none, create, open, study, knowledge, sysadmin, help. + * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help. */ private String _menuProperty; - + /** - * Value of the title bar property. - * It can be: study, knowledge. + * Value of the title bar property. It can be: study, knowledge. */ private String _titleProperty; - + /** - * Value of the tool bar property. - * It can be: none, standard, study, back. + * Value of the tool bar property. It can be: none, standard, study, back. */ private String _toolProperty; - + /** - * Value of the left menu property. - * It can be: open, study, knowledge, scenario. + * Value of the left menu property. It can be: open, study, knowledge, scenario. */ private String _leftMenuProperty; - + /** - * Property that indicates whether the current open study is editable or not. - * On the screen it looks like pen on the status icon, pop-up menu also can be called. - * It is necessary for correct building the title bar. + * Property that indicates whether the current open study is editable or not. On the screen it looks like pen on the status icon, pop-up + * menu also can be called. It is necessary for correct building the title bar. */ private String _editDisabledProperty = "false"; - private static final long serialVersionUID = 6003880772275115923L; + /** + * Action modes enumeration. + */ + private enum ToDo { + /** + * Cancel the operation. + */ + cancel, + /** + * Perform uploading. + */ + upload + }; + + // ============================================================================================================================== + // Action methods + // ============================================================================================================================== + + /** + * Prepare form for the upload action. + * + * @return SUCCESS + */ + public String doInitialize() { + setMenuProperty(Constants.STUDY_MENU); + setToolProperty(Constants.NONE); + setLeftMenuProperty("open"); + initializationFullScreenContext(_menuProperty, _toolProperty, + _leftMenuProperty); + + return SUCCESS; + } + + /** + * Store uploaded file into the user's download directory. + * + * @return next action if ok, "cancel" if the operation is cancelled by user, "outofmemory" if there is no enough memory to upload the + * file or ERROR otherwise + */ + public String doUpload() { + setMenuProperty(Constants.STUDY_MENU); + setTitleProperty(Constants.STUDY_MENU); + setEditDisabledProperty("true"); + initializationScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty); + + String res; + if (_action == ToDo.cancel) { + res = "cancel"; + } else { + try { + File udir = getRepositoryService().getDownloadDirectory( + getConnectedUser()); + String path = udir.getPath() + "/" + _uploadFileName; + File file = new File(path); + + if (!udir.exists()) { + udir.mkdir(); + } + if (file.exists()) { + file.delete(); + } + Do.copy(_upload, file); + LOG.info("Uploading \"" + _uploadFileName + "\" " + + _uploadMimeType + " file."); + /* + * if (next == null || next.isEmpty()) { next = "import"; } + */ + + res = _nextAction; + } catch (OutOfMemoryError error) { + + setMenuProperty(Constants.NONE); + setTitleProperty(Constants.STUDY_MENU); + setEditDisabledProperty("true"); + setToolProperty(Constants.NONE); + setLeftMenuProperty(Constants.STUDY_MENU); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); + + setErrorCode("message.error.outofmemory"); + + res = "outofmemory"; + } catch (Exception error) { + LOG.error("Reason: ", error); + res = ERROR; + } + } + return res; + } + + // ============================================================================================================================== + // Getters and setters + // ============================================================================================================================== - private enum ToDo { cancel, upload }; - -// ============================================================================================================================== -// Action methods -// ============================================================================================================================== - - public String doInitialize () { -// ----------------------------- - setMenuProperty("study"); - setToolProperty("none"); - setLeftMenuProperty("open"); - initializationFullScreenContext(_menuProperty, _toolProperty, _leftMenuProperty); - - return SUCCESS; - } - - public String doUpload () { -// ------------------------- - setMenuProperty("study"); - setTitleProperty("study"); - setEditDisabledProperty("true"); - initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty); - - if (action == ToDo.cancel) return "cancel"; - try { - File udir = getRepositoryService().getDownloadDirectory(getConnectedUser()); - String path = udir.getPath() + "/" + uploadFileName; - File file = new File(path); - - if (!udir.exists()) udir.mkdir(); - if (file.exists()) file.delete(); - Do.copy(upload, file); - LOG.info("Uploading \"" + uploadFileName + "\" " + uploadMimeType + " file."); - /*if (next == null || next.isEmpty()) { - next = "import"; - }*/ - - return next; - } - catch (OutOfMemoryError error) { - - setMenuProperty("none"); - setTitleProperty("study"); - setEditDisabledProperty("true"); - setToolProperty("none"); - setLeftMenuProperty("study"); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - - setErrorCode("message.error.outofmemory"); - - return "outofmemory"; - } - catch (Exception error) { - LOG.error("Reason: ", error); - return ERROR; - } - } -// ============================================================================================================================== -// Getters and setters -// ============================================================================================================================== - - public String getIndex () { -// ------------------------- - return index; - } - public String getFileName () { -// ---------------------------- - return uploadFileName; - } - public String getNextAction () { -// ------------------------------ - return next; - } - - public void setCancel (final boolean back) { -// ------------------------------------ - this.action = ToDo.cancel; - } - public void setDoIt (final boolean upload) { -// -------------------------------- - this.action = ToDo.upload; - } - public void setIndex (final String index) { -// ----------------------------------- - this.index = index; - } - public void setNextAction (final String next) { -// --------------------------------------- - this.next = next; - } - public void setUpload (final File upload) { -// ----------------------------------- - this.upload = upload; - } - public void setUploadFileName (final String name) { -// ------------------------------------------- - this.uploadFileName = name; - } - public void setUploadContentType (final String mime) { -// ---------------------------------------------- - this.uploadMimeType = mime; - } + /** + * Get the document index to which the action applies. + * + * @return the document index to which the action applies + */ + public String getIndex() { + return _index; + } + + /** + * Get the uploaded file name. + * + * @return the uploaded file name + */ + public String getFileName() { + return _uploadFileName; + } + + /** + * Get the action to which the uploaded file is passed. + * + * @return the action to which the uploaded file is passed. + */ + public String getNextAction() { + return _nextAction; + } + + /** + * Cancel the uploading. + * + * @param back + */ + public void setCancel(final boolean back) { + this._action = ToDo.cancel; + } + + /** + * Set the flag to perform uploading. + * + * @param upload + */ + public void setDoIt(final boolean upload) { + this._action = ToDo.upload; + } + + /** + * Set the document index to which the action applies. + * + * @param index + * the document index to which the action applies. + */ + public void setIndex(final String index) { + this._index = index; + } + + /** + * Set the action to which the uploaded file is passed. + * + * @param next + * the action to which the uploaded file is passed. + */ + public void setNextAction(final String next) { + this._nextAction = next; + } + + /** + * Set the uploaded file. + * + * @param upload + * the file + */ + public void setUpload(final File upload) { + this._upload = upload; + } + + /** + * Set the uploaded file name. + * + * @param name + * the uploaded file name + */ + public void setUploadFileName(final String name) { + this._uploadFileName = name; + } + + /** + * Set the mime type of the uploaded file. + * + * @param mime + * the mime type of the uploaded file + */ + public void setUploadContentType(final String mime) { + this._uploadMimeType = mime; + } /** * Get the repositoryService. + * * @return the repositoryService */ public RepositoryService getRepositoryService() { @@ -167,14 +273,17 @@ public class UploadAction extends Action { /** * Set the repositoryService. - * @param repositoryService the repositoryService to set + * + * @param repositoryService + * the repositoryService to set */ public void setRepositoryService(final RepositoryService repositoryService) { _repositoryService = repositoryService; } - + /** * Get the menuProperty. + * * @return the menuProperty */ public String getMenuProperty() { @@ -183,14 +292,17 @@ public class UploadAction extends Action { /** * Set the menuProperty. - * @param menuProperty the menuProperty to set + * + * @param menuProperty + * the menuProperty to set */ public void setMenuProperty(final String menuProperty) { this._menuProperty = menuProperty; } - + /** * Get the _titleProperty. + * * @return the _titleProperty */ public String getTitleProperty() { @@ -199,7 +311,9 @@ public class UploadAction extends Action { /** * Set the _titleProperty. - * @param titleProperty the titleProperty to set + * + * @param titleProperty + * the titleProperty to set */ public void setTitleProperty(final String titleProperty) { _titleProperty = titleProperty; @@ -207,6 +321,7 @@ public class UploadAction extends Action { /** * Get the _editDisabledProperty. + * * @return the _editDisabledProperty */ public String getEditDisabledProperty() { @@ -214,15 +329,18 @@ public class UploadAction extends Action { } /** - * Set the _editDisabledProperty. - * @param _editDisabledProperty the _editDisabledProperty to set + * Set the editDisabledProperty. + * + * @param editDisabledProperty + * the editDisabledProperty to set */ - public void setEditDisabledProperty(final String _editDisabledProperty) { - this._editDisabledProperty = _editDisabledProperty; + public void setEditDisabledProperty(final String editDisabledProperty) { + this._editDisabledProperty = editDisabledProperty; } /** * Get the toolProperty. + * * @return the toolProperty */ public String getToolProperty() { @@ -231,14 +349,17 @@ public class UploadAction extends Action { /** * Set the toolProperty. - * @param toolProperty the toolProperty to set + * + * @param toolProperty + * the toolProperty to set */ public void setToolProperty(final String toolProperty) { _toolProperty = toolProperty; } - + /** * Get the leftMenuProperty. + * * @return the leftMenuProperty */ public String getLeftMenuProperty() { @@ -247,7 +368,9 @@ public class UploadAction extends Action { /** * Set the leftMenuProperty. - * @param leftMenuProperty the leftMenuProperty to set + * + * @param leftMenuProperty + * the leftMenuProperty to set */ public void setLeftMenuProperty(final String leftMenuProperty) { _leftMenuProperty = leftMenuProperty; diff --git a/Workspace/Siman/src/org/splat/simer/UploadBaseNextAction.java b/Workspace/Siman/src/org/splat/simer/UploadBaseNextAction.java index f3e1b96..bdea14f 100644 --- a/Workspace/Siman/src/org/splat/simer/UploadBaseNextAction.java +++ b/Workspace/Siman/src/org/splat/simer/UploadBaseNextAction.java @@ -10,104 +10,109 @@ import org.splat.dal.bo.som.ProgressState; import org.splat.dal.bo.som.Publication; import org.splat.som.Step; - public abstract class UploadBaseNextAction extends Action { - protected OpenStudy mystudy = null; - protected String filename = null; // Uploaded file name - protected DocumentType deftype = null; - protected List defuses = null; - protected String docname = null; - protected ProgressState state = null; - protected String docuses = null; - protected ToDo action = null; + protected OpenStudy mystudy = null; + protected String filename = null; // Uploaded file name + protected DocumentType deftype = null; + protected List defuses = null; + protected String docname = null; + protected ProgressState state = null; + protected String docuses = null; + protected ToDo action = null; /** * Serial version ID. */ - private static final long serialVersionUID = -6925961099244461039L; - - protected enum ToDo { cancel, save }; - -// ============================================================================================================================== -// Getters and setters -// ============================================================================================================================== - - public DocumentType getDefaultDocumentType () { -// --------------------------------------------- - return deftype; - } - public List getDefaultDocumentUses () { -// ----------------------------------------------- - return defuses; - } - public String getDocumentName () { -// -------------------------------- - return docname; - } - public String getDocumentState () { -// --------------------------------- - return state.toString(); - } - public String getFileName () { -// ---------------------------- - return filename; - } - - public void setCancel (boolean cancel) { -// -------------------------------------- - this.action = ToDo.cancel; - } - public void setDocumentState (String state) { -// ------------------------------------------- - this.state = ProgressState.valueOf(state); - } - public void setFileName (String path) { -// ------------------------------------- - this.filename = path; - } - public void setUses (String list) { -// --------------------------------- - this.docuses = list; - } - public void setSave (boolean save) { -// ---------------------------------- - this.action = ToDo.save; - } - - public String getWriteAccess() { - if (mystudy == null) { - return "false"; - } - return String.valueOf(mystudy.isOpenForWriting()); + private static final long serialVersionUID = -6925961099244461039L; + + protected enum ToDo { + cancel, save + }; + + // ============================================================================================================================== + // Getters and setters + // ============================================================================================================================== + + public DocumentType getDefaultDocumentType() { + return deftype; + } + + public List getDefaultDocumentUses() { + return defuses; + } + + public String getDocumentName() { + return docname; + } + + public String getDocumentState() { + return state.toString(); + } + + public String getFileName() { + return filename; + } + + public void setCancel(final boolean cancel) { + this.action = ToDo.cancel; + } + + public void setDocumentState(final String state) { + this.state = ProgressState.valueOf(state); + } + + public void setFileName(final String path) { + this.filename = path; + } + + public void setUses(final String list) { + this.docuses = list; + } + + public void setSave(final boolean save) { + this.action = ToDo.save; + } + + public String getWriteAccess() { + Boolean res = (mystudy != null); + if (res) { + res = mystudy.isOpenForWriting(); + } + return res.toString(); + } + + // ============================================================================================================================== + // Protected services + // ============================================================================================================================== + + protected void setupDefaultUses(final DocumentType type) { + Set uses = type.getDefaultUses(); + + for (Iterator i = uses.iterator(); i.hasNext();) { + DocumentType usetype = i.next(); + List usedoc = mystudy.collectInvolvedDocuments(usetype); + if (usedoc.isEmpty()) { + setupDefaultUses(usetype); + } else { + defuses.addAll(usedoc); + } + } + } + + protected Publication getPublication(final int index) { + List steps = mystudy.getInvolvedSteps(); + Publication found = null, pub; + for (Iterator i = steps.iterator(); i.hasNext();) { + List published = i.next().getAllDocuments(); + for (Iterator j = published.iterator(); j.hasNext();) { + pub = j.next(); // In a given study step, + if (pub.value().getIndex() == index) { + found = pub; // there is only one publication of a given document + break; + } + } + } + return found; } -// ============================================================================================================================== -// Protected services -// ============================================================================================================================== - - protected void setupDefaultUses (DocumentType type) { -// ------------------------------------------------- - Set uses = type.getDefaultUses(); - - for (Iterator i=uses.iterator(); i.hasNext();) { - DocumentType usetype = i.next(); - List usedoc = mystudy.collectInvolvedDocuments(usetype); - if (usedoc.isEmpty()) setupDefaultUses(usetype); - else defuses.addAll(usedoc); - } - } - - protected Publication getPublication (int index) { -// ------------------------------------------------ - List steps = mystudy.getInvolvedSteps(); - - for (Iterator i=steps.iterator(); i.hasNext(); ) { - List published = i.next().getAllDocuments(); - for (Iterator j=published.iterator(); j.hasNext();) { - Publication found = j.next(); // In a given study step, - if (found.value().getIndex() == index) return found; // there is only one publication of a given document - } - } - return null; - } } \ No newline at end of file diff --git a/Workspace/Siman/src/org/splat/simer/VersionDocumentAction.java b/Workspace/Siman/src/org/splat/simer/VersionDocumentAction.java index ac94f13..9f975c0 100644 --- a/Workspace/Siman/src/org/splat/simer/VersionDocumentAction.java +++ b/Workspace/Siman/src/org/splat/simer/VersionDocumentAction.java @@ -79,33 +79,28 @@ public class VersionDocumentAction extends UploadBaseNextAction { */ private RepositoryService _repositoryService; /** - * Value of the menu property. - * It can be: none, create, open, study, knowledge, sysadmin, help. + * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help. */ private String _menuProperty; /** - * Value of the title bar property. - * It can be: study, knowledge. + * Value of the title bar property. It can be: study, knowledge. */ private String _titleProperty; /** - * Value of the tool bar property. - * It can be: none, standard, study, back. + * Value of the tool bar property. It can be: none, standard, study, back. */ private String _toolProperty; - + /** - * Value of the left menu property. - * It can be: open, study, knowledge, scenario. + * Value of the left menu property. It can be: open, study, knowledge, scenario. */ private String _leftMenuProperty; /** - * Property that indicates whether the current open study is editable or not. - * On the screen it looks like pen on the status icon, pop-up menu also can be called. - * It is necessary for correct building the title bar. + * Property that indicates whether the current open study is editable or not. On the screen it looks like pen on the status icon, pop-up + * menu also can be called. It is necessary for correct building the title bar. */ private String _editDisabledProperty = "false"; @@ -129,8 +124,9 @@ public class VersionDocumentAction extends UploadBaseNextAction { setToolProperty(Constants.NONE); } setLeftMenuProperty(Constants.STUDY_MENU); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); - + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); + User user = getConnectedUser(); File updir = getRepositoryService().getDownloadDirectory(user); File upfile = new File(updir.getPath() + "/" + filename); @@ -162,7 +158,8 @@ public class VersionDocumentAction extends UploadBaseNextAction { if (!(Constants.NONE.equals(_toolProperty))) { setToolProperty(Constants.NONE); setLeftMenuProperty(Constants.STUDY_MENU); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); } res = ERROR; } @@ -241,12 +238,13 @@ public class VersionDocumentAction extends UploadBaseNextAction { setMenuProperty(Constants.STUDY_MENU); setTitleProperty(Constants.STUDY_MENU); setEditDisabledProperty("true"); - initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty); - + initializationScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty); + if (action == ToDo.cancel) { res = "cancel"; } else { - + try { // Getting user inputs mystudy = getOpenStudy(); @@ -260,19 +258,19 @@ public class VersionDocumentAction extends UploadBaseNextAction { .getString("date.format")); aDate = get.parse(_date); } - + String[] listDocuses = null; if (docuses != null) { listDocuses = docuses.split(","); } getPublicationService().versionDocument(step, user, filename, - Integer.valueOf(_index), _version, _description, state, aDate, - listDocuses, _docusedby); - + Integer.valueOf(_index), _version, _description, state, + aDate, listDocuses, _docusedby); + // Update of the open study mystudy.setSelection(mystudy.getSelection()); // Rebuilds the presentation // TODO: Look is an optimization is possible (for example by updating the presentation of versioned document) - + res = SUCCESS; } catch (FileNotFoundException error) { LOG.error("Reason:", error); @@ -283,11 +281,12 @@ public class VersionDocumentAction extends UploadBaseNextAction { } if (!SUCCESS.equals(res)) { setToolProperty(Constants.NONE); - + setLeftMenuProperty(Constants.STUDY_MENU); - initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty); + initializationFullScreenContext(_menuProperty, _titleProperty, + _editDisabledProperty, _toolProperty, _leftMenuProperty); } - } + } return res; } @@ -356,7 +355,8 @@ public class VersionDocumentAction extends UploadBaseNextAction { * @param projectSettingsService * project settings service */ - public void setProjectSettings(final ProjectSettingsService projectSettingsService) { + public void setProjectSettings( + final ProjectSettingsService projectSettingsService) { _projectSettings = projectSettingsService; } @@ -375,7 +375,8 @@ public class VersionDocumentAction extends UploadBaseNextAction { * @param publicationService * the publicationService to set */ - public void setPublicationService(final PublicationService publicationService) { + public void setPublicationService( + final PublicationService publicationService) { _publicationService = publicationService; } @@ -473,9 +474,10 @@ public class VersionDocumentAction extends UploadBaseNextAction { public void setEditDisabledProperty(final String editDisabledProperty) { this._editDisabledProperty = editDisabledProperty; } - + /** * Get the toolProperty. + * * @return the toolProperty */ public String getToolProperty() { @@ -484,14 +486,17 @@ public class VersionDocumentAction extends UploadBaseNextAction { /** * Set the toolProperty. - * @param toolProperty the toolProperty to set + * + * @param toolProperty + * the toolProperty to set */ public void setToolProperty(final String toolProperty) { _toolProperty = toolProperty; } - + /** * Get the leftMenuProperty. + * * @return the leftMenuProperty */ public String getLeftMenuProperty() { @@ -500,7 +505,9 @@ public class VersionDocumentAction extends UploadBaseNextAction { /** * Set the leftMenuProperty. - * @param leftMenuProperty the leftMenuProperty to set + * + * @param leftMenuProperty + * the leftMenuProperty to set */ public void setLeftMenuProperty(final String leftMenuProperty) { _leftMenuProperty = leftMenuProperty; diff --git a/Workspace/Siman/src/org/splat/wapp/Constants.java b/Workspace/Siman/src/org/splat/wapp/Constants.java index 54fc75f..67ca84e 100644 --- a/Workspace/Siman/src/org/splat/wapp/Constants.java +++ b/Workspace/Siman/src/org/splat/wapp/Constants.java @@ -14,10 +14,28 @@ package org.splat.wapp; * SIMAN constants. */ public class Constants { + /** + * Standard menu key. + */ public final static String STANDARD_MENU = "standard"; + /** + * Study menu key. + */ public final static String STUDY_MENU = "study"; + /** + * Knowledge menu key. + */ public final static String KNOWLEDGE_MENU = "knowledge"; + /** + * No selected item key. + */ public final static String NONE = "none"; + /** + * TRUE literal constant. + */ public final static String TRUE = "true"; + /** + * Scenario properties menu key. + */ public final static String PROP_SCENARIO = "prop-scenario"; } -- 2.39.2