From: rkv Date: Mon, 25 Mar 2013 08:34:23 +0000 (+0000) Subject: Creation of a new study from an existing one is implemented. X-Git-Tag: Root_Delivery2_2013_04_22~82 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=7680c3b72fcb15167bdceff688a859bd517446c1;p=tools%2Fsiman.git Creation of a new study from an existing one is implemented. --- diff --git a/Workspace/Siman-Common/src/org/splat/common/Constants.java b/Workspace/Siman-Common/src/org/splat/common/Constants.java new file mode 100644 index 0000000..6e6836b --- /dev/null +++ b/Workspace/Siman-Common/src/org/splat/common/Constants.java @@ -0,0 +1,23 @@ +/***************************************************************************** + * Company OPEN CASCADE + * Application SIMAN + * File $Id$ + * Creation date 22.03.2013 + * @author $Author$ + * @version $Revision$ + * @copyright OPEN CASCADE 2012 + *****************************************************************************/ + +package org.splat.common; + +/** + * Common constants. + * + * @author Roman Kozlov (RKV) + */ +public class Constants { + /** + * Unchecked warning specification. + */ + public static final String UNCHECKED = "unchecked"; +} diff --git a/Workspace/Siman-Common/src/org/splat/dal/bo/kernel/GenericEnumType.java b/Workspace/Siman-Common/src/org/splat/dal/bo/kernel/GenericEnumType.java index 3f3ba07..1413f0e 100644 --- a/Workspace/Siman-Common/src/org/splat/dal/bo/kernel/GenericEnumType.java +++ b/Workspace/Siman-Common/src/org/splat/dal/bo/kernel/GenericEnumType.java @@ -1,121 +1,200 @@ package org.splat.dal.bo.kernel; + /** * * @author Daniel Brunier-Coulin * @copyright OPEN CASCADE 2012 */ - import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; - + import org.hibernate.HibernateException; import org.hibernate.usertype.EnhancedUserType; import org.hibernate.usertype.ParameterizedType; +import org.splat.common.Constants; - +/** + * Base class for persistent enumerations.
+ * Parameter enumClassName defines the enumeration implementation class in
+ * hibernate mapping like this:
+ * + * <typedef name="ProgressState" class="org.splat.dal.bo.kernel.GenericEnumType">
+ *   <param name="enumClassName">org.splat.dal.bo.som.ProgressState</param>
+ * </typedef>
+ *
+ */ public class GenericEnumType implements EnhancedUserType, ParameterizedType { - - @SuppressWarnings("unchecked") - private Class enumClass; - - @SuppressWarnings("unchecked") - public void setParameterValues (Properties parameters) { -// ------------------------------------------------------ - String enumClassName = parameters.getProperty("enumClassName"); - try { - enumClass = (Class) Class.forName(enumClassName); - } - catch (ClassNotFoundException cnfe) { - throw new HibernateException("Enum class not found", cnfe); - } - } - - public Object assemble (Serializable cached, Object owner) throws HibernateException { -// ---------------------------------------------------------- - return cached; - } - - public Object deepCopy (Object value) throws HibernateException { -// ------------------------------------- - return value; - } - - @SuppressWarnings("unchecked") - public Serializable disassemble (Object value) throws HibernateException { -// ---------------------------------------------- - return (Enum) value; - } - - public boolean equals (Object x, Object y) throws HibernateException { -// ------------------------------------------ - return x==y; - } - - public int hashCode (Object x) throws HibernateException { -// ------------------------------ - return x.hashCode(); - } - - public boolean isMutable () { -// --------------------------- - return false; - } - - @SuppressWarnings("unchecked") - public Object nullSafeGet (ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { -// ---------------------------------------------------------------------- - String name = rs.getString( names[0] ); - return rs.wasNull() ? null : Enum.valueOf(enumClass, name); - } - - @SuppressWarnings("unchecked") - public void nullSafeSet (PreparedStatement st, Object value, int index) throws HibernateException, SQLException { -// ----------------------------------------------------------------------- - if (value==null) { - st.setNull(index, Types.VARCHAR); - } - else { - st.setString( index, ( (Enum) value ).name() ); - } - } - - public Object replace (Object original, Object target, Object owner) throws HibernateException { -// -------------------------------------------------------------------- - return original; - } - - @SuppressWarnings("unchecked") - public Class returnedClass () { -// ----------------------------- - return enumClass; - } - - public int[] sqlTypes () { -// ------------------------ - return new int[] { Types.VARCHAR }; - } - - @SuppressWarnings("unchecked") - public Object fromXMLString (String xmlValue) { -// --------------------------------------------- - return Enum.valueOf(enumClass, xmlValue); - } - - @SuppressWarnings("unchecked") - public String objectToSQLString (Object value) { -// ---------------------------------------------- - return '\'' + ( (Enum) value ).name() + '\''; - } - - @SuppressWarnings("unchecked") - public String toXMLString (Object value) { -// ---------------------------------------- - return ( (Enum) value ).name(); - } - + /** + * Enumeration implementation class. + */ + @SuppressWarnings(Constants.UNCHECKED) + private transient Class _enumClass; + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.ParameterizedType#setParameterValues(java.util.Properties) + */ + @SuppressWarnings(Constants.UNCHECKED) + public void setParameterValues(final Properties parameters) { + String enumClassName = parameters.getProperty("enumClassName"); + try { + _enumClass = (Class) Class.forName(enumClassName); + } catch (ClassNotFoundException cnfe) { + throw new HibernateException("Enum class not found", cnfe); + } + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, java.lang.Object) + */ + public Object assemble(final Serializable cached, final Object owner) + throws HibernateException { + return cached; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object) + */ + public Object deepCopy(final Object value) throws HibernateException { + return value; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#disassemble(java.lang.Object) + */ + @SuppressWarnings(Constants.UNCHECKED) + public Serializable disassemble(final Object value) + throws HibernateException { + return (Enum) value; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#equals(java.lang.Object, java.lang.Object) + */ + public boolean equals(final Object x, final Object y) + throws HibernateException { + return x.equals(y); + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#hashCode(java.lang.Object) + */ + public int hashCode(final Object x) throws HibernateException { + return x.hashCode(); + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#isMutable() + */ + public boolean isMutable() { + return false; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object) + */ + @SuppressWarnings(Constants.UNCHECKED) + public Object nullSafeGet(final ResultSet rs, final String[] names, + final Object owner) throws HibernateException, SQLException { + Object res = null; + if (!rs.wasNull()) { + String name = rs.getString(names[0]); + res = Enum.valueOf(_enumClass, name); + } + return res; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int) + */ + @SuppressWarnings(Constants.UNCHECKED) + public void nullSafeSet(final PreparedStatement st, final Object value, + final int index) throws HibernateException, SQLException { + if (value == null) { + st.setNull(index, Types.VARCHAR); + } else { + st.setString(index, ((Enum) value).name()); + } + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#replace(java.lang.Object, java.lang.Object, java.lang.Object) + */ + public Object replace(final Object original, final Object target, + final Object owner) throws HibernateException { + return original; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#returnedClass() + */ + @SuppressWarnings(Constants.UNCHECKED) + public Class returnedClass() { + return _enumClass; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.UserType#sqlTypes() + */ + public int[] sqlTypes() { + return new int[] { Types.VARCHAR }; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.EnhancedUserType#fromXMLString(java.lang.String) + */ + @SuppressWarnings(Constants.UNCHECKED) + public Object fromXMLString(final String xmlValue) { + return Enum.valueOf(_enumClass, xmlValue); + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.EnhancedUserType#objectToSQLString(java.lang.Object) + */ + @SuppressWarnings(Constants.UNCHECKED) + public String objectToSQLString(final Object value) { + return '\'' + ((Enum) value).name() + '\''; + } + + /** + * {@inheritDoc} + * + * @see org.hibernate.usertype.EnhancedUserType#toXMLString(java.lang.Object) + */ + @SuppressWarnings(Constants.UNCHECKED) + public String toXMLString(final Object value) { + return ((Enum) value).name(); + } } \ No newline at end of file diff --git a/Workspace/Siman-Common/src/org/splat/dal/bo/som/Document.java b/Workspace/Siman-Common/src/org/splat/dal/bo/som/Document.java index 70ec817..79bf7ca 100644 --- a/Workspace/Siman-Common/src/org/splat/dal/bo/som/Document.java +++ b/Workspace/Siman-Common/src/org/splat/dal/bo/som/Document.java @@ -53,7 +53,6 @@ public class Document extends Entity { * Fields initialization class. */ public static class Properties extends Persistent.Properties { - // ------------------------------------------------------------ private DocumentType type = null; private String did = null; // Only for searching from a given reference private ProjectElement owner = null; // Only for constructing a document diff --git a/Workspace/Siman-Common/src/org/splat/dal/bo/som/ValidationCycle.java b/Workspace/Siman-Common/src/org/splat/dal/bo/som/ValidationCycle.java index 5c67d1e..f08829b 100644 --- a/Workspace/Siman-Common/src/org/splat/dal/bo/som/ValidationCycle.java +++ b/Workspace/Siman-Common/src/org/splat/dal/bo/som/ValidationCycle.java @@ -1,4 +1,5 @@ package org.splat.dal.bo.som; + /** * Class defining the validation cycle applicable to documents of a given type.
* A validation cycle specifies the validation steps of documents complying with by this cycle, as well as the actors @@ -26,7 +27,8 @@ package org.splat.dal.bo.som; * @copyright OPEN CASCADE 2012 */ -import java.util.Vector; +import java.util.ArrayList; +import java.util.List; import org.splat.dal.bo.kernel.Persistent; import org.splat.dal.bo.kernel.User; @@ -36,277 +38,307 @@ import org.splat.kernel.MultiplyDefinedException; public class ValidationCycle extends Persistent { - private ValidationCycleRelation context; - private DocumentType mytype; // Null if the referenced validation cycle is a default one - private User publisher; - private User reviewer; // Null if no REVIEW validation step - private User approver; // Null if no APPROVAL validation step - private User signatory; // Null if no ACCEPTANCE validation step - - public enum Actor { - manager, // Responsible of study - Nx1, // N+1 manager of the responsible of study - Nx2, // N+2 manager of the responsible of study - customer // Customer - } - -// ============================================================================================================================== -// Construction -// ============================================================================================================================== - -// Fields initialization class - public static class Properties extends Persistent.Properties { -// ------------------------------------------------------------ - DocumentType doctype = null; - User publisher = null; - User reviewer = null; - User approver = null; - User signatory = null; - -// - Public services - - @Override - public void clear () { - super.clear(); - doctype = null; - publisher = null; - reviewer = null; - approver = null; - signatory = null; - } -// - Protected services - - public Properties setDocumentType (final DocumentType type) - { - doctype = type; - return this; - } -// - Properties setter - - public Properties setActor (final ValidationStep step, final User actor) - { - if (step == ValidationStep.PROMOTION) { - publisher = actor; - } else if (step == ValidationStep.REVIEW) { - reviewer = actor; - } else if (step == ValidationStep.APPROVAL) { - approver = actor; - } else if (step == ValidationStep.ACCEPTANCE || step == ValidationStep.REFUSAL) { - signatory = actor; + private ValidationCycleRelation context; + private DocumentType mytype; // Null if the referenced validation cycle is a default one + private User publisher; + private User reviewer; // Null if no REVIEW validation step + private User approver; // Null if no APPROVAL validation step + private User signatory; // Null if no ACCEPTANCE validation step + + public enum Actor { + manager, // Responsible of study + Nx1, // N+1 manager of the responsible of study + Nx2, // N+2 manager of the responsible of study + customer + // Customer + } + + // ============================================================================================================================== + // Construction + // ============================================================================================================================== + + // Fields initialization class + public static class Properties extends Persistent.Properties { + DocumentType doctype = null; + User publisher = null; + User reviewer = null; + User approver = null; + User signatory = null; + + // - Public services + + @Override + public void clear() { + super.clear(); + doctype = null; + publisher = null; + reviewer = null; + approver = null; + signatory = null; + } + + // - Protected services + + public Properties setDocumentType(final DocumentType type) { + doctype = type; + return this; + } + + // - Properties setter + + public Properties setActor(final ValidationStep step, final User actor) { + if (step == ValidationStep.PROMOTION) { + publisher = actor; + } else if (step == ValidationStep.REVIEW) { + reviewer = actor; + } else if (step == ValidationStep.APPROVAL) { + approver = actor; + } else if (step == ValidationStep.ACCEPTANCE + || step == ValidationStep.REFUSAL) { + signatory = actor; + } + return this; + } + + // - Global validity check + + public void checkValidity() throws MissedPropertyException { + if (doctype == null) { + throw new MissedPropertyException("type"); + } + } + + /** + * Get the publisher. + * + * @return the publisher + */ + public User getPublisher() { + return publisher; + } + + /** + * Get the reviewer. + * + * @return the reviewer + */ + public User getReviewer() { + return reviewer; + } + + /** + * Get the approver. + * + * @return the approver + */ + public User getApprover() { + return approver; } - return this; - } -// - Global validity check - - public void checkValidity() throws MissedPropertyException - { - if (doctype == null) { - throw new MissedPropertyException("type"); + + /** + * Get the signatory. + * + * @return the signatory + */ + public User getSignatory() { + return signatory; } - } + } + + // Database fetch constructor + public ValidationCycle() { + super(); + } + + public ValidationCycle(final Study from, final Properties vprop) + throws MissedPropertyException, InvalidPropertyException, + MultiplyDefinedException { + super(vprop); // Throws one of the above exception if not valid + mytype = vprop.doctype; + publisher = vprop.publisher; // May be null + reviewer = vprop.reviewer; // May be null + approver = vprop.approver; // May be null + signatory = vprop.signatory; // May be null + context = new ValidationCycleRelation(from, this); + } /** - * Get the publisher. - * @return the publisher + * Create a copy of the given cycle for the given study. + * + * @param study + * the owner study + * @return the cloned validation cycle */ - public User getPublisher() { - return publisher; + public ValidationCycle clone(final Study study) { + ValidationCycle res = new ValidationCycle(); + res.mytype = this.mytype; + res.publisher = this.publisher; // May be null + res.reviewer = this.reviewer; // May be null + res.approver = this.approver; // May be null + res.signatory = this.signatory; // May be null + res.context = new ValidationCycleRelation(study, res); + return res; } + // ============================================================================================================================== + // Public member functions + // ============================================================================================================================== /** - * Get the reviewer. - * @return the reviewer + * Checks if a given validation step is enabled in this validation cycle. + * + * @param step + * the validation step checked. + * @return true if the given validation step is enabled. */ - public User getReviewer() { - return reviewer; + public boolean enables(final ValidationStep step) { + boolean res = false; + if (step == ValidationStep.PROMOTION) { + res = true; + } else if (step == ValidationStep.REVIEW) { + res = (reviewer != null); + } else if (step == ValidationStep.APPROVAL) { + res = (approver != null); + } else if (step == ValidationStep.ACCEPTANCE + || step == ValidationStep.REFUSAL) { + res = (signatory != null); + } + return res; } /** - * Get the approver. - * @return the approver + * Returns the user involved in a given step of this document validation cycle. When enabled, the Review and Approval steps have one + * explicit actor returned by this function. On the other hand, Promotion and Acceptance have default actors - they respectively are the + * author of the document or the responsible of study, and the customer or its representative internal user. In this context, a null + * user is returned. + * + * @param step + * the validation step + * @return the user involved by the given step or null if the step is disabled or the actors are the default ones + * @see #getAllActors() + * @see #enables */ - public User getApprover() { - return approver; + public User getActor(final ValidationStep step) { + User res = null; + if (step == ValidationStep.PROMOTION) { + res = publisher; + } else if (step == ValidationStep.REVIEW) { + res = reviewer; + } else if (step == ValidationStep.APPROVAL) { + res = approver; + } else if (step == ValidationStep.ACCEPTANCE + || step == ValidationStep.REFUSAL) { + res = signatory; + } + return res; } /** - * Get the signatory. - * @return the signatory + * Returns all explicit actors of this document validation cycle, that is, actors of enabled validation cycles, excluding the default + * actors. + * + * @return the users explicitly involved by the steps of this validation cycle + * @see #getActor(ValidationStep) + * @see #enables(ValidationStep) */ - public User getSignatory() { - return signatory; - } - } -// Database fetch constructor - public ValidationCycle () { - } - public ValidationCycle (final Study from, final Properties vprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException { - super(vprop); // Throws one of the above exception if not valid - mytype = vprop.doctype; - publisher = vprop.publisher; // May be null - reviewer = vprop.reviewer; // May be null - approver = vprop.approver; // May be null - signatory = vprop.signatory; // May be null - context = new ValidationCycleRelation(from, this); - } - - /** - * Create a copy of the given cycle for the given study. - * @param study the owner study - * @param src the original validation cycle - */ - public ValidationCycle (final Study study, final ValidationCycle src) { - super(); // Throws one of the above exception if not valid - mytype = src.getDocumentType(); - publisher = src.publisher; // May be null - reviewer = src.reviewer; // May be null - approver = src.approver; // May be null - signatory = src.signatory; // May be null - context = new ValidationCycleRelation(study, this); - } - -// ============================================================================================================================== -// Public member functions -// ============================================================================================================================== -/** - * Checks if a given validation step is enabled in this validation cycle. - * - * @param step the validation step checked. - * @return true if the given validation step is enabled. - */ - public boolean enables (final ValidationStep step) { - if (step == ValidationStep.PROMOTION) { - return true; - } else if (step == ValidationStep.REVIEW) { - return (reviewer != null); - } else if (step == ValidationStep.APPROVAL) { - return (approver != null); - } else if (step == ValidationStep.ACCEPTANCE || step == ValidationStep.REFUSAL) { - return (signatory != null); + public User[] getAllActors() { + List result = new ArrayList(); + if (publisher != null) { + result.add(publisher); + } + if (reviewer != null) { + result.add(reviewer); + } + if (approver != null) { + result.add(approver); + } + if (signatory != null) { + result.add(signatory); + } + return result.toArray(new User[result.size()]); } - return false; - } -/** - * Returns the user involved in a given step of this document validation cycle. - * When enabled, the Review and Approval steps have one explicit actor returned by this function. On the other hand, - * Promotion and Acceptance have default actors - they respectively are the author of the document or the responsible of study, - * and the customer or its representative internal user. In this context, a null user is returned. - * - * @param step the validation step - * @return the user involved by the given step or null if the step is disabled or the actors are the default ones - * @see #getAllActors() - * @see #enables - */ - public User getActor (final ValidationStep step) { - if (step == ValidationStep.PROMOTION) { - return publisher; - } else if (step == ValidationStep.REVIEW) { - return reviewer; - } else if (step == ValidationStep.APPROVAL) { - return approver; - } else if (step == ValidationStep.ACCEPTANCE || step == ValidationStep.REFUSAL) { - return signatory; + /** + * Return the document type to which this validation cycle applies. If this validation cycle is a default one, the document type is not + * defined. + * + * @return the document type involved by this validation cycle, or null if this validation cycle is a default one. + * @see #isDefault() + */ + public DocumentType getDocumentType() { + return mytype; // May be null } - return null; - } -/** - * Returns all explicit actors of this document validation cycle, that is, actors of enabled validation cycles, excluding - * the default actors. - * - * @return the users explicitly involved by the steps of this validation cycle - * @see #getActor(ValidationStep) - * @see #enables(ValidationStep) - */ - public User[] getAllActors () { -// ----------------------------- - Vector result = new Vector(); - if (publisher != null) { - result.add(publisher); - } - if (reviewer != null) { - result.add(reviewer); - } - if (approver != null) { - result.add(approver); + /** + * Set a document type for the validation cycle. + * + * @param aType + * the document type + */ + public void setDocumentType(final DocumentType aType) { + mytype = aType; // May be null } - if (signatory != null) { - result.add(signatory); + + /** + * Checks if this validation cycle is assigned to a study. If not, it is common to all studies of the workflow in which it has been + * defined. + * + * @return true if this validation cycle is assigned to a study. + */ + public boolean isAssigned() { + return (context != null); } - return result.toArray(new User[result.size()]); - } -/** - * Return the document type to which this validation cycle applies. If this validation cycle is a default one, the document - * type is not defined. - * - * @return the document type involved by this validation cycle, or null if this validation cycle is a default one. - * @see #isDefault() - */ - public DocumentType getDocumentType () { - return mytype; // May be null - } - - /** - * Set a document type for the validation cycle. - * @param aType the document type - */ - public void setDocumentType (final DocumentType aType) { - mytype = aType; // May be null - } + /** + * Checks if this validation cycle is a default one, either specific to a Study or defined in the configuration workflow or built-in.
+ * Default validation cycle are not attached to any document type. As for built-in ones, they doesn't include any validation step other + * than Promotion. + * + * @return true if this validation cycle is a default one. + * @see #getDocumentType() + */ + public boolean isDefault() { + return (mytype == null); + } -/** - * Checks if this validation cycle is assigned to a study. If not, it is common to all studies of the workflow in which it has - * been defined. - * - * @return true if this validation cycle is assigned to a study. - */ - public boolean isAssigned () { - return (context != null); - } + public ValidationCycleRelation getContext() { + return context; + } -/** - * Checks if this validation cycle is a default one, either specific to a Study or defined in the configuration workflow or - * built-in.
- * Default validation cycle are not attached to any document type. As for built-in ones, they doesn't include any validation step - * other than Promotion. - * - * @return true if this validation cycle is a default one. - * @see #getDocumentType() - */ - public boolean isDefault () { - return (mytype == null); - } - - public ValidationCycleRelation getContext () { -// ----------------------------------------------- - return context; - } /** * Set the publisher. - * @param publisher the publisher to set + * + * @param publisher + * the publisher to set */ public void setPublisher(final User publisher) { this.publisher = publisher; } + /** * Set the reviewer. - * @param reviewer the reviewer to set + * + * @param reviewer + * the reviewer to set */ public void setReviewer(final User reviewer) { this.reviewer = reviewer; } + /** * Set the approver. - * @param approver the approver to set + * + * @param approver + * the approver to set */ public void setApprover(final User approver) { this.approver = approver; } + /** * Set the signatory. - * @param signatory the signatory to set + * + * @param signatory + * the signatory to set */ public void setSignatory(final User signatory) { this.signatory = signatory; diff --git a/Workspace/Siman-Common/src/org/splat/dal/dao/kernel/AbstractGenericDAOImpl.java b/Workspace/Siman-Common/src/org/splat/dal/dao/kernel/AbstractGenericDAOImpl.java index 393c124..296df73 100644 --- a/Workspace/Siman-Common/src/org/splat/dal/dao/kernel/AbstractGenericDAOImpl.java +++ b/Workspace/Siman-Common/src/org/splat/dal/dao/kernel/AbstractGenericDAOImpl.java @@ -20,6 +20,7 @@ import org.hibernate.criterion.Criterion; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; +import org.splat.common.Constants; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** @@ -34,10 +35,6 @@ import org.springframework.orm.hibernate3.support.HibernateDaoSupport; */ public abstract class AbstractGenericDAOImpl extends HibernateDaoSupport implements GenericDAO { - /** - * Unchecked warning specification. - */ - private static final String UNCHECKED = "unchecked"; /** * Persist the newInstance object into database. @@ -47,7 +44,7 @@ public abstract class AbstractGenericDAOImpl * @return new primary key for the created persistent object * @see Session#save(Object) */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public PK create(final T newInstance) { return (PK) getSession().save(newInstance); } @@ -59,7 +56,7 @@ public abstract class AbstractGenericDAOImpl * new object as a transient instance * @see Session#saveOrUpdate(Object) */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public void saveOrUpdate(final T newInstance) { getSession().saveOrUpdate(newInstance); } @@ -72,7 +69,7 @@ public abstract class AbstractGenericDAOImpl * @return an object found by the given key * @see Session#get(Class, Serializable) */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public T get(final PK id) { return (T) getSession().get(getType(), id); } @@ -84,7 +81,7 @@ public abstract class AbstractGenericDAOImpl * a search condition * @return an object found according to the given criteria */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public T findByCriteria(final Criterion aCondition) { return (T) getSession().createCriteria(getType()).add(aCondition) .uniqueResult(); @@ -111,7 +108,7 @@ public abstract class AbstractGenericDAOImpl * * @return a list of all objects of the considered type T */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getAll() { return getSession().createCriteria(getType()).list(); } @@ -123,7 +120,7 @@ public abstract class AbstractGenericDAOImpl * a result list order. Null is ignored and in such case the result list is unordered. * @return an ordered list of all objects of the considered type T */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getAll(final Order... anOrder) { Criteria aCriteria = getSession().createCriteria(getType()); for (Order order : anOrder) { @@ -141,7 +138,7 @@ public abstract class AbstractGenericDAOImpl * search criteria * @return a list of objects filtered according to the given criteria */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getFilteredList(final DetachedCriteria aDetachedCriteria) { return aDetachedCriteria.getExecutableCriteria(getSession()).list(); } @@ -155,7 +152,7 @@ public abstract class AbstractGenericDAOImpl * search criteria * @return a list of DTO objects filtered according to the given criteria */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getFilteredDTOList( final DetachedCriteria aDetachedCriteria) { return aDetachedCriteria.getExecutableCriteria(getSession()).list(); @@ -168,7 +165,7 @@ public abstract class AbstractGenericDAOImpl * a search condition * @return a list of objects filtered according to the given criteria */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getFilteredList(final Criterion aCondition) { return getSession().createCriteria(getType()).add(aCondition).list(); } @@ -182,7 +179,7 @@ public abstract class AbstractGenericDAOImpl * a result list order. Null is ignored and in such case the result list is unordered. * @return a list of objects filtered according to the given criteria */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getFilteredList(final Criterion aCondition, final Order... anOrder) { Criteria aCriteria = getSession().createCriteria(getType()).add( @@ -222,7 +219,7 @@ public abstract class AbstractGenericDAOImpl * a result list order. Null is ignored and in such case the result list is unordered. * @return a list of objects filtered according to the given criteria */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public List getFilteredList(final String joinField, final Criterion aCondition, final Order... anOrder) { Criteria aCriteria = getSession().createCriteria(getType()); @@ -348,7 +345,7 @@ public abstract class AbstractGenericDAOImpl * @return merged persistent object * @see Session#merge(Object) */ - @SuppressWarnings(UNCHECKED) + @SuppressWarnings(Constants.UNCHECKED) public T merge(final T transientObject) { return (T) getSession().merge(transientObject); } @@ -362,7 +359,6 @@ public abstract class AbstractGenericDAOImpl * the object to be removed from session cache * @see Session#evict(Object) */ - @SuppressWarnings(UNCHECKED) public void evict(final T persistentObject) { getSession().evict(persistentObject); } diff --git a/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java b/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java index 9340c5c..794dd90 100644 --- a/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java +++ b/Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java @@ -66,6 +66,7 @@ import org.splat.service.dto.ScenarioDTO; import org.splat.service.dto.StepDTO; import org.splat.service.technical.IndexService; import org.splat.service.technical.ProjectSettingsService; +import org.splat.service.technical.RepositoryService; import org.splat.service.technical.StepsConfigService; import org.splat.som.Step; import org.splat.util.BeanHelper; @@ -178,6 +179,11 @@ public class ScenarioServiceImpl implements ScenarioService { */ private StepsConfigService _stepsConfigService; + /** + * Injected repository service. + */ + private RepositoryService _repositoryService; + /** * Get the projectElementService. * @@ -278,6 +284,7 @@ public class ScenarioServiceImpl implements ScenarioService { for (Scenario scen : fromStudy.getScenariiList()) { if (scen.getIndex() == fromScenId) { fromScen = scen; + break; } } @@ -296,14 +303,7 @@ public class ScenarioServiceImpl implements ScenarioService { } // Copy validation cycles - for (ValidationCycle fromCycle : fromStudy.getValidationCycles() - .values()) { - ValidationCycle cycle = new ValidationCycle(toStudy, fromCycle); - getValidationCycleDAO().create(cycle); - toStudy.addRelation(cycle.getContext()); - toStudy.getValidationCycles().put( - cycle.getDocumentType().getName(), cycle); // Replaces the cycle if exists as default, - } + copyValidationCycles(fromStudy, toStudy); // Copy content of the study up to the given step Map oldToNewPub = new HashMap(); @@ -318,6 +318,27 @@ public class ScenarioServiceImpl implements ScenarioService { } } + /** + * Copy validation cycles from study to study. + * + * @param fromStudy + * the source study + * @param toStudy + * the destination study + */ + private void copyValidationCycles(final Study fromStudy, final Study toStudy) { + for (ValidationCycle fromCycle : fromStudy.getValidationCycles() + .values()) { + if (fromCycle.isAssigned()) { + ValidationCycle cycle = fromCycle.clone(toStudy); + getValidationCycleDAO().create(cycle); + toStudy.addRelation(cycle.getContext()); + toStudy.getValidationCycles().put( + cycle.getDocumentType().getName(), cycle); // Replaces the cycle if exists as default, + } + } + } + /** * Copy dependencies between documents from the given project element up to
* the given step according to the given map of old publications to new publications. @@ -408,22 +429,38 @@ public class ScenarioServiceImpl implements ScenarioService { throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, IOException, NotApplicableException { - java.io.File upfile = fromDoc.getSourceFile().asFile(); + java.io.File srcFile = fromDoc.getSourceFile().asFile(); // Creation of the document Document.Properties dprop = new Document.Properties().setName( fromDoc.getTitle()).setType(fromDoc.getType()).setFormat( fromDoc.getFormat()).setAuthor(fromDoc.getAuthor()); + + java.io.File tmpDir = getRepositoryService().getDownloadDirectory( + step.getOwnerStudy().getAuthor()); + + // Remove local file index prefix to get original filename. + java.io.File upfile = new java.io.File(tmpDir.getPath() + + "/" + + srcFile.getName().substring( + srcFile.getName().indexOf('_') + 1)); + // Copy the source file into the temporary folder with original filename. + copyFile(srcFile, upfile); + dprop.setLocalPath(upfile.getPath()); Publication addoc = getStepService().createDocument(step, dprop); - copyFile(upfile, addoc.getSourceFile()); + + // Move the temporary file into the repository + moveFile(upfile, addoc.getSourceFile().asFile()); + getPublicationService().saveAs(addoc, fromDoc.getProgressState()); // Copy attached files - for (Relation rel : addoc.value().getRelations(ConvertsRelation.class)) { + for (Relation rel : fromDoc.getRelations(ConvertsRelation.class)) { File attach = ((ConvertsRelation) rel).getTo(); ConvertsRelation export = getPublicationService().attach(addoc, attach.getFormat()); - copyFile(attach.asFile(), export.getTo()); + // Copy the source document attachment file to the new study vault + copyFile(attach.asFile(), export.getTo().asFile()); } return addoc; } @@ -433,18 +470,33 @@ public class ScenarioServiceImpl implements ScenarioService { * * @param upfile * the source file. - * @param targetFile + * @param file * the target file * @throws IOException * if failed */ - private void copyFile(final java.io.File upfile, final File targetFile) + private void copyFile(final java.io.File upfile, final java.io.File file) throws IOException { if (LOG.isInfoEnabled()) { - LOG.info("Copy " + upfile.getAbsolutePath() + TO - + targetFile.asFile().getPath()); + LOG.info("Copy " + upfile.getAbsolutePath() + TO + file.getPath()); } - IOUtils.copy(upfile, targetFile.asFile()); + IOUtils.copy(upfile, file); + } + + /** + * Copy a file. Print info message. + * + * @param upfile + * the source file. + * @param file + * the target file + * @return true if renamed otherwise return false + */ + private boolean moveFile(final java.io.File upfile, final java.io.File file) { + if (LOG.isInfoEnabled()) { + LOG.info("Move " + upfile.getAbsolutePath() + TO + file.getPath()); + } + return upfile.renameTo(file); } /** @@ -993,15 +1045,11 @@ public class ScenarioServiceImpl implements ScenarioService { // If there is no attachment with this extension then attach the new one ConvertsRelation export = getPublicationService().attach(pub, fileFormat); - if (LOG.isDebugEnabled()) { - LOG.debug("Moving " + upfile.getName() + TO - + export.getTo().asFile().getPath()); - } - upfile.renameTo(export.getTo().asFile()); + moveFile(upfile, export.getTo().asFile()); } else { // If an attachment with this extension already exists then // replace it by the new one - upfile.renameTo(attach.asFile()); + moveFile(upfile,attach.asFile()); // Update attached file modification date attach.setDate(new Date()); } @@ -1027,10 +1075,6 @@ public class ScenarioServiceImpl implements ScenarioService { NotApplicableException { // Attach the file to the created document java.io.File updir = newPub.getSourceFile().asFile(); - if (LOG.isDebugEnabled()) { - LOG.debug("Moving \"" + upfile.getName() + "\" to \"" - + updir.getPath() + "\"."); - } if (updir.exists()) { if (updir.delete()) { LOG.info(MessageKeyEnum.SCN_000003.toString(), updir @@ -1042,7 +1086,7 @@ public class ScenarioServiceImpl implements ScenarioService { + updir.getAbsolutePath()); } } - if (upfile.renameTo(updir)) { + if (moveFile(upfile, 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 @@ -1640,4 +1684,23 @@ public class ScenarioServiceImpl implements ScenarioService { _stepsConfigService = stepsConfigService; } + /** + * Get the repositoryService. + * + * @return the repositoryService + */ + public RepositoryService getRepositoryService() { + return _repositoryService; + } + + /** + * Set the repositoryService. + * + * @param repositoryService + * the repositoryService to set + */ + public void setRepositoryService(final RepositoryService repositoryService) { + _repositoryService = repositoryService; + } + } diff --git a/Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java b/Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java index d6bf598..40f106c 100644 --- a/Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java +++ b/Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java @@ -196,7 +196,9 @@ public class StudyServiceImpl implements StudyService { @Transactional public Study selectStudy(final long index) { Study result = getStudyDAO().get(index); - loadWorkflow(result); + if (result != null) { + loadWorkflow(result); + } return result; } @@ -241,14 +243,16 @@ public class StudyServiceImpl implements StudyService { // Remove all relations of study documents for (org.splat.dal.bo.som.Document doc : docums) { - LOG.debug("Found doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]"); + LOG.debug("Found doc: " + doc.getTitle() + " [" + + doc.getReference() + "]" + " [" + doc.getRid() + "]"); doc.getAllRelations().clear(); } getDocumentDAO().flush(); // Remove all documents of the study for (org.splat.dal.bo.som.Document doc : docums) { - LOG.debug("Remove doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]"); + LOG.debug("Remove doc: " + doc.getTitle() + " [" + + doc.getReference() + "]" + " [" + doc.getRid() + "]"); getDocumentDAO().delete(doc); } } @@ -400,17 +404,9 @@ public class StudyServiceImpl implements StudyService { * the document * @return true if the document is published in the study */ -/* private boolean publishes(final Study aStudy, final Document doc) { - if (!aStudy.publishes(doc)) { - Scenario[] scene = aStudy.getScenarii(); - for (int i = 0; i < scene.length; i++) { - if (scene[i].publishes(doc)) { - return true; - } - } - } - return false; - } + /* + * private boolean publishes(final Study aStudy, final Document doc) { if (!aStudy.publishes(doc)) { Scenario[] scene = + * aStudy.getScenarii(); for (int i = 0; i < scene.length; i++) { if (scene[i].publishes(doc)) { return true; } } } return false; } */ /** * {@inheritDoc} @@ -488,8 +484,7 @@ public class StudyServiceImpl implements StudyService { validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default, } catch (BusinessException error) { - LOG.error("Unable to create validation cycle, reason:", - error); + LOG.error("Unable to create validation cycle, reason:", error); return; } } @@ -1177,7 +1172,8 @@ public class StudyServiceImpl implements StudyService { } Study study = _studyDAO.get(studyId); if (study == null) { - throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString()); + throw new InvalidParameterException(PARAM_STUDY_ID, studyId + .toString()); } return study.getDescription(); } @@ -1196,7 +1192,8 @@ public class StudyServiceImpl implements StudyService { } Study study = _studyDAO.get(studyId); if (study == null) { - throw new InvalidParameterException(PARAM_STUDY_ID, studyId.toString()); + throw new InvalidParameterException(PARAM_STUDY_ID, studyId + .toString()); } study.setAttribute(new DescriptionAttribute(study, descriptionText)); } @@ -1252,17 +1249,19 @@ public class StudyServiceImpl implements StudyService { + "downloads" + File.separator + userName + File.separator + "ComparisonResult.pdf"; - XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle()); + XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + + docDTO.getDocumentTitle()); // read the file and get points information. try { Scanner input = new Scanner(compDocFile); - //get the title of the chart. + // get the title of the chart. if (input.hasNext()) { chartTitle = input.nextLine(); } - + // get the name of the axis. if (input.hasNext()) { String[] tokens = input.nextLine().split(","); @@ -1309,8 +1308,7 @@ public class StudyServiceImpl implements StudyService { } } // for - JFreeChart chart = ChartFactory.createXYLineChart( - chartTitle, // Title + JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // Title axis1Name, // x-axis Label axis2Name, // y-axis Label dataset, // Dataset @@ -1552,98 +1550,102 @@ public class StudyServiceImpl implements StudyService { * @see org.splat.service.StudyService#getComparableStudies() */ @Transactional(readOnly = true) - public List getComparableStudies(final long userId) throws MismatchException { - //retrieve the number of the "Analyze the results" step + public List getComparableStudies(final long userId) + throws MismatchException { + // retrieve the number of the "Analyze the results" step List allSteps = _projectSettings.getAllSteps(); Step theAnalyzeStep = null; - for(Step step : allSteps) { - if(step.getKey().equals("postprocessing")) { + for (Step step : allSteps) { + if (step.getKey().equals("postprocessing")) { theAnalyzeStep = step; } } - if(theAnalyzeStep == null) { //TODO: throw some other exception - throw new MismatchException("no step with key 'postprocessing' found." + - "Probably, customization settings have been changed."); + if (theAnalyzeStep == null) { // TODO: throw some other exception + throw new MismatchException( + "no step with key 'postprocessing' found." + + "Probably, customization settings have been changed."); } - List publications = _publicationDAO.getFilteredList("mydoc", - Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber()))); + List publications = _publicationDAO.getFilteredList( + "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep + .getNumber()))); - //split retrieved publications into groups by studies and scenarios + // split retrieved publications into groups by studies and scenarios Map> studyMap = new HashMap>(); - Map> scenarioMap = - new HashMap>(); - - for(Publication publication : publications) { - //filter out publications corresponding to a document of given step which is not a _result_ document - if(!publication.value().getType().isResultOf(theAnalyzeStep) + Map> scenarioMap = new HashMap>(); + + for (Publication publication : publications) { + // filter out publications corresponding to a document of given step which is not a _result_ document + if (!publication.value().getType().isResultOf(theAnalyzeStep) || !"srd".equals(publication.getSourceFile().getFormat())) { continue; } - - //check the study visibility to the user - if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId)) - && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) { + + // check the study visibility to the user + if (!isStaffedBy(publication.getOwnerStudy(), _userService + .selectUser(userId)) + && Visibility.PUBLIC.equals(publication.getOwnerStudy() + .getVisibility())) { continue; } - + Study study = publication.getOwnerStudy(); ProjectElement scenario = publication.getOwner(); - + Hibernate.initialize(scenario); - if (scenario instanceof HibernateProxy) { - scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer() - .getImplementation(); - } - - if(!(scenario instanceof Scenario)) { + if (scenario instanceof HibernateProxy) { + scenario = (ProjectElement) ((HibernateProxy) scenario) + .getHibernateLazyInitializer().getImplementation(); + } + + if (!(scenario instanceof Scenario)) { throw new MismatchException( "publications from postprocessing step are supposed to have owner scenario"); } - if(!studyMap.containsKey(study)) { + if (!studyMap.containsKey(study)) { studyMap.put(study, new ArrayList()); } - - if(!studyMap.get(study).contains(scenario)) { + + if (!studyMap.get(study).contains(scenario)) { studyMap.get(study).add(scenario); } - if(!scenarioMap.containsKey(scenario)) { + if (!scenarioMap.containsKey(scenario)) { scenarioMap.put(scenario, new ArrayList()); } scenarioMap.get(scenario).add(publication); } - - //Create the result DTOs + + // Create the result DTOs List result = new ArrayList(); - for(Study study : studyMap.keySet()) { - + for (Study study : studyMap.keySet()) { + StudyFacadeDTO studyDTO = new StudyFacadeDTO(); studyDTO.setName(study.getTitle()); studyDTO.setScenarios(new ArrayList()); result.add(studyDTO); - - for(ProjectElement scenario : studyMap.get(study)) { - + + for (ProjectElement scenario : studyMap.get(study)) { + StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO(); scenarioDTO.setName(scenario.getTitle()); scenarioDTO.setDocs(new ArrayList()); studyDTO.getScenarios().add(scenarioDTO); - for(Publication publication : scenarioMap.get(scenario)) { + for (Publication publication : scenarioMap.get(scenario)) { DocumentDTO documentDTO = new DocumentDTO(); documentDTO.setId(publication.getIndex()); documentDTO.setTitle(publication.value().getTitle()); - + scenarioDTO.getDocs().add(documentDTO); } } - } + } return result; } - + /** * Get the publicationDAO. * diff --git a/Workspace/Siman-Common/src/org/splat/util/IOUtils.java b/Workspace/Siman-Common/src/org/splat/util/IOUtils.java index 3bf960e..e0a7898 100644 --- a/Workspace/Siman-Common/src/org/splat/util/IOUtils.java +++ b/Workspace/Siman-Common/src/org/splat/util/IOUtils.java @@ -117,6 +117,10 @@ public final class IOUtils { FileInputStream inputStream = new FileInputStream(src); try { + // Create target directory if necessary + if (!target.getParentFile().exists()) { + target.getParentFile().mkdirs(); + } FileOutputStream outputStream = new FileOutputStream(target); try { diff --git a/Workspace/Siman-Common/src/spring/businessServiceContext.xml b/Workspace/Siman-Common/src/spring/businessServiceContext.xml index 538a4ed..8c62f8c 100644 --- a/Workspace/Siman-Common/src/spring/businessServiceContext.xml +++ b/Workspace/Siman-Common/src/spring/businessServiceContext.xml @@ -84,7 +84,8 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> ref="projectElementService" /> - + + @@ -92,6 +93,7 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + diff --git a/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java b/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java index b402d1d..ddb34ac 100644 --- a/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java +++ b/Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java @@ -27,6 +27,7 @@ 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.KnowledgeElementType; +import org.splat.dal.bo.som.ProjectElement; import org.splat.dal.bo.som.Publication; import org.splat.dal.bo.som.Scenario; import org.splat.dal.bo.som.SimulationContext; @@ -34,12 +35,17 @@ import org.splat.dal.bo.som.SimulationContextType; import org.splat.dal.bo.som.Study; import org.splat.dal.bo.som.UsedByRelation; import org.splat.dal.bo.som.UsesRelation; +import org.splat.dal.bo.som.ValidationCycle; +import org.splat.dal.bo.som.ValidationCycleRelation; +import org.splat.dal.bo.som.ValidationStep; import org.splat.dal.bo.som.Document.Properties; import org.splat.dal.dao.kernel.UserDAO; import org.splat.dal.dao.som.Database; import org.splat.dal.dao.som.ScenarioDAO; import org.splat.dal.dao.som.StudyDAO; +import org.splat.dal.dao.som.ValidationCycleDAO; import org.splat.exception.BusinessException; +import org.splat.exception.InvalidParameterException; import org.splat.i18n.I18nUtils; import org.splat.kernel.InvalidPropertyException; import org.splat.kernel.MismatchException; @@ -49,6 +55,7 @@ import org.splat.kernel.NotApplicableException; import org.splat.log.AppLogger; import org.splat.service.DocumentTypeService; import org.splat.service.KnowledgeElementTypeService; +import org.splat.service.ProjectElementService; import org.splat.service.PublicationService; import org.splat.service.ScenarioService; import org.splat.service.SimulationContextService; @@ -177,6 +184,20 @@ public class TestScenarioService extends BaseTest { @Qualifier("studyDAO") private transient StudyDAO _studyDAO; + /** + * The ValidationCycleDAO. Later injected by Spring. + */ + @Autowired + @Qualifier("validationCycleDAO") + private transient ValidationCycleDAO _validationCycleDAO; + + /** + * The ProjectElementService. Later injected by Spring. + */ + @Autowired + @Qualifier("projectElementService") + private transient ProjectElementService _projectElementService; + /** * Test of getting a scenario content for building siman-salome.conf.
* Description :
@@ -804,6 +825,23 @@ public class TestScenarioService extends BaseTest { return new FileDTO(filePath); } + /** + * Create a file. + * + * @param fname + * file name + * @throws IOException + * if file creation failed + */ + private void createFile(final String fname) throws IOException { + // Create a file in the download directory + LOG.debug("Create file: " + fname); + String filePath = fname; + FileWriter fw = new FileWriter(filePath); + fw.write("Simulation of " + fname + " data file at " + new Date()); + fw.close(); + } + /** * Get path to the user's downloads directory. The directory is created if it is not exist yet. * @@ -1161,13 +1199,13 @@ public class TestScenarioService extends BaseTest { BusinessException { LOG.debug(">>>>> BEGIN testCreateStudyFromPython()"); startNestedTransaction(); - + HibernateTemplate ht = getHibernateTemplate(); - + Database.getInstance().reset(); _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again _projectSettings.configure("classpath:test/som.xml"); - + // Create a test user User goodUser = TestEntitiesGenerator.getTestUser("goodUser"); _userDAO.create(goodUser); @@ -1176,15 +1214,15 @@ public class TestScenarioService extends BaseTest { Assert .assertNotNull(prodtype, "Simulation context type 'product' must be created in the database."); - + String productName = "New Test Product " + new Date().toString(); - + ht.flush(); ht.clear(); long studyId1 = _scenarioService.createStudy("goodUser", "Test Study 1", productName, "Test description"); Assert.assertTrue(studyId1 > 0); - + ht.flush(); ht.clear(); try { @@ -1194,26 +1232,26 @@ public class TestScenarioService extends BaseTest { } catch (InvalidPropertyException ipe) { LOG.debug("Expected exception: " + ipe.getMessage()); } - + ht.flush(); ht.clear(); long studyId3 = _scenarioService.createStudy("goodUser", "Test Study 3", productName, "Test description"); Assert.assertTrue(studyId3 > 0); - + // Check that the simulation context is the same Study study1 = _studyService.selectStudy(studyId1); Study study3 = _studyService.selectStudy(studyId3); Assert.assertEquals(study1.SimulationContextIterator().next(), study3 .SimulationContextIterator().next()); - + // Check the title of the created scenario String scTitle = study1.getScenarii()[0].getTitle(); Assert.assertEquals(scTitle, I18nUtils .getMessageLocaleDefault("label.scenario") + " 1"); Assert.assertFalse(scTitle.equals("label.scenario 1")); - + rollbackNestedTransaction(); LOG.debug(">>>>> END testCreateStudyFromPython()"); } @@ -1224,19 +1262,19 @@ public class TestScenarioService extends BaseTest { * Create a study.
* Action :
* 1. call the method for a not existing source study.
- * 1. call the method for a not existing source scenario.
- * 1. call the method for a not existing source study.
- * 2. call the method for an existing username and an existing product.
- * 3. call the method for a not existing username expecting an exception.
+ * 2. call the method for a not existing source scenario with not evolving step.
+ * 3. call the method for a not existing source scenario with evolving step.
+ * 4. call the method for an existing source scenario with evolving step.
* Test data :
* no input parameters
* * Outcome results:
* *
    - *
  • 1: The new study must be created. The new product simulation context must be created.
  • - *
  • 2: The new study must be created.
  • - *
  • 3: The new study must not be created. Exception must be thrown.
  • + *
  • 1: Exception must be thrown.
  • + *
  • 2: The study content must be copied.
  • + *
  • 3: Exception must be thrown.
  • + *
  • 4: The study content must be copied.
  • *
*
* @@ -1259,56 +1297,269 @@ public class TestScenarioService extends BaseTest { _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again _projectSettings.configure("classpath:test/som.xml"); - // Create a test user - User goodUser = TestEntitiesGenerator.getTestUser("goodUser"); + User goodUser = TestEntitiesGenerator.getTestUser("GoodUser"); _userDAO.create(goodUser); - SimulationContextType prodtype = _simulationContextService - .selectType("product"); - Assert - .assertNotNull(prodtype, - "Simulation context type 'product' must be created in the database."); + User otherUser = TestEntitiesGenerator.getTestUser("otherUser"); + _userDAO.create(otherUser); - String productName = "New Test Product " + new Date().toString(); + // Create private study + Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser); + aStudy.setTitle("0.This is private study"); + Long studyId = _studyDAO.create(aStudy); + // Add a scenario to the study + Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy); + _scenarioDAO.create(scen); ht.flush(); - ht.clear(); - long studyId1 = _scenarioService.createStudy("goodUser", - "Test Study 1", productName, "Test description"); - Assert.assertTrue(studyId1 > 0); + // Add a second scenario to the study + scen = TestEntitiesGenerator.getTestScenario(aStudy); + Long aScenId = _scenarioDAO.create(scen); + ht.flush(); + + // Add a validation cycle with otherUser as a reviewer + ValidationCycle.Properties vprop = new ValidationCycle.Properties(); + DocumentType dtype = _documentTypeService.selectType("minutes"); + vprop.setDocumentType(dtype); + vprop.setActor(ValidationStep.REVIEW, otherUser); + ValidationCycle cycle = new ValidationCycle(aStudy, vprop); + _validationCycleDAO.create(cycle); + ValidationCycleRelation link = cycle.getContext(); + aStudy.addRelation(link); + ht.flush(); + + // Add documents to the first study activity + // Add a converts relations + Map stSteps = _projectElementService + .getStepsMap(aStudy); + org.splat.som.Step aStep = stSteps.get(1); + Publication pub1 = addDoc(aStudy, aStep, "document1", dtype); + Publication pub2 = addDoc(aStudy, aStep, "document2", dtype); + Publication pub3 = addDoc(aStudy, aStep, "document3", dtype); + ht.flush(); + + LOG.debug("pub1 version doc: " + pub1.value().getTitle() + " [" + + pub1.value().getReference() + "]" + " [" + + pub1.value().getRid() + "]"); + LOG.debug("pub2 version doc: " + pub2.value().getTitle() + " [" + + pub2.value().getReference() + "]" + " [" + + pub2.value().getRid() + "]"); + LOG.debug("pub3 version doc: " + pub3.value().getTitle() + " [" + + pub3.value().getReference() + "]" + " [" + + pub3.value().getRid() + "]"); + ht.update(aStudy); + + ht.flush(); + LOG.debug("Before versioning:"); + for (Publication doc : _projectElementService.getFirstStep(aStudy) + .getAllDocuments()) { + LOG.debug("Study doc: " + doc.value().getTitle() + " [" + + doc.value().getReference() + "]" + " [" + + doc.value().getRid() + "]"); + } + // // Add a version relations + // Publication pub31 = version(pub3); + // + // LOG.debug("pub31 version doc: " + pub31.value().getTitle() + " [" + // + pub31.value().getReference() + "]" + " [" + // + pub31.value().getRid() + "]"); + // ht.saveOrUpdate(aStudy); + + // LOG.debug("After versioning:"); + // for (Publication doc : aStudy.getDocums()) { + // LOG.debug("Study doc: " + doc.value().getTitle() + " [" + // + doc.value().getReference() + "]" + " [" + // + doc.value().getRid() + "]"); + // } + + // Add documents to the first scenario activity + Map scSteps = _projectElementService + .getStepsMap(scen); + aStep = scSteps.get(2); + Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype); + Publication spub2 = addDoc(scen, aStep, "sdocument2", dtype); + Publication spub3 = addDoc(scen, aStep, "sdocument3", dtype); + LOG.debug("spub1 version doc: " + spub1.value().getTitle() + " [" + + spub1.value().getReference() + "]" + " [" + + spub1.value().getRid() + "]"); + LOG.debug("spub2 version doc: " + spub2.value().getTitle() + " [" + + spub2.value().getReference() + "]" + " [" + + spub2.value().getRid() + "]"); + LOG.debug("spub3 version doc: " + spub3.value().getTitle() + " [" + + spub3.value().getReference() + "]" + " [" + + spub3.value().getRid() + "]"); + ht.flush(); + + // Create a scenario document version + // Publication spub31 = version(spub3); + // LOG.debug("spub31 version doc: " + spub31.value().getTitle() + " [" + // + spub31.value().getReference() + "]" + " [" + // + spub31.value().getRid() + "]"); + + // Add uses relations + pub2.addDependency(pub1); + ht.saveOrUpdate(pub2.value()); + pub3.addDependency(pub2); + ht.saveOrUpdate(pub3.value()); + + spub2.addDependency(pub1); + spub2.addDependency(spub1); + spub2.addDependency(pub2); + spub2.addDependency(pub3); + ht.saveOrUpdate(spub2.value()); + spub3.addDependency(spub2); + ht.saveOrUpdate(spub3.value()); + // spub31.addDependency(spub31); + // ht.saveOrUpdate(spub31.value()); + ht.flush(); + + // Create target study1 + Study aStudy1 = TestEntitiesGenerator.getTestStudy(goodUser); + aStudy1.setTitle("1.This is a target study1"); + aStudy1.setReference("tst1"); + Long studyId1 = _studyDAO.create(aStudy1); + + // Add a scenario to the study + Scenario scen1 = TestEntitiesGenerator.getTestScenario(aStudy1); + _scenarioDAO.create(scen1); + ht.flush(); + + // Create target study2 + Study aStudy2 = TestEntitiesGenerator.getTestStudy(goodUser); + aStudy2.setTitle("2.This is a target study2"); + aStudy2.setReference("tst2"); + Long studyId2 = _studyDAO.create(aStudy2); + + // Add a scenario to the study + Scenario scen2 = TestEntitiesGenerator.getTestScenario(aStudy2); + _scenarioDAO.create(scen2); ht.flush(); ht.clear(); + + // //////////////////// TEST CALL ///////////////////////////////////// + // 1. call the method for a not existing source study. try { - _scenarioService.createStudy("badbadUser", "Test Study 2", - productName, "Test description"); - Assert.fail("Study must not be created for not existing user."); - } catch (InvalidPropertyException ipe) { - LOG.debug("Expected exception: " + ipe.getMessage()); + _scenarioService.copyStudyContent(-1, -1, -1, -1); + Assert.fail("Exception must be thrown for not existing study id."); + } catch (InvalidParameterException e) { + LOG.debug("Expected exception: " + e.getClass().getSimpleName() + + ": " + e.getMessage()); } ht.flush(); ht.clear(); - long studyId3 = _scenarioService.createStudy("goodUser", - "Test Study 3", productName, "Test description"); - Assert.assertTrue(studyId3 > 0); - // Check that the simulation context is the same - Study study1 = _studyService.selectStudy(studyId1); - Study study3 = _studyService.selectStudy(studyId3); - Assert.assertEquals(study1.SimulationContextIterator().next(), study3 - .SimulationContextIterator().next()); + // 2. call the method for a not existing source scenario with not evolving step. + _scenarioService.copyStudyContent(studyId, -1, 1, studyId1); - // Check the title of the created scenario - String scTitle = study1.getScenarii()[0].getTitle(); - Assert.assertEquals(scTitle, I18nUtils - .getMessageLocaleDefault("label.scenario") - + " 1"); - Assert.assertFalse(scTitle.equals("label.scenario 1")); + ht.flush(); + ht.clear(); + + aStudy = _studyService.selectStudy(studyId); + aStudy1 = _studyService.selectStudy(studyId1); + for (Publication pub : aStudy.getDocums()) { + // Find the same document in the created copy of the study + Publication found = null; + for (Publication newPub : aStudy1.getDocums()) { + if (pub.value().getTitle().equals(newPub.value().getTitle()) + && pub.value().getType().equals( + newPub.value().getType())) { + found = newPub; + break; + } + } + Assert.assertNotNull(found, "The document " + + pub.value().getTitle() + "is not copied"); + // Check that all files are copied (source and attached) + } + + // 3. call the method for a not existing source scenario with evolving step. + try { + _scenarioService.copyStudyContent(studyId, -1, 2, studyId2); + Assert + .fail("Exception must be thrown for not existing scenario id and evolving step."); + } catch (InvalidParameterException e) { + LOG.debug("Expected exception: " + e.getClass().getSimpleName() + + ": " + e.getMessage()); + } + + ht.flush(); + ht.clear(); + + // 4. call the method for an existing source scenario with evolving step. + _scenarioService.copyStudyContent(studyId, aScenId, 9, studyId2); + ht.flush(); rollbackNestedTransaction(); LOG.debug(">>>>> END testCopyStudyContent()"); } + /** + * Create a document and publish it in the project element. + * + * @param aProjElem + * the project element + * @param aStep + * the project element step + * @param docname + * document name + * @param dtype + * document type + * @return publication of the created document + * @throws BusinessException + * if document creation is failed + * @throws IOException + * if file creation is failed + */ + private Publication addDoc(final ProjectElement aProjElem, + final org.splat.som.Step aStep, final String docname, + final DocumentType dtype) throws BusinessException, IOException { + HibernateTemplate ht = getHibernateTemplate(); + // Add documents to the study activity + Document.Properties dprop = new Document.Properties().setAuthor( + aProjElem.getAuthor()).setDate(new Date()).setName(docname) + .setType(dtype).setFormat("py"); + dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat()); + dprop.setStep(aStep.getStep()); + Publication pub = _stepService.createDocument(aStep, dprop); + pub.setStep(aStep); + aProjElem.add(pub); + aStep.getDocuments().add(pub); + ht.saveOrUpdate(pub); + ht.save(pub.value()); + // Add a converts relation + // Attach a med file + ht.saveOrUpdate(_publicationService.attach(pub, "med")); + String filepath = pub.getSourceFile().asFile().getAbsolutePath(); + createFile(filepath); + createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med"); + return pub; + } + + /** + * Create a new version of the document. + * + * @param pub + * the current document publication + * @return the new document version publication + * @throws IOException + * if versioning is failed + * @throws BusinessException + * if versioning is failed + */ + private Publication version(final Publication pub) + throws BusinessException, IOException { + Document.Properties dprop = new Document.Properties(); + dprop.setDocument(pub.value(), pub.getStep().getStep()); + Publication newpub = _stepService.versionDocument(pub.getStep(), pub, + dprop); + pub.getOwner().getDocums().remove(pub); + pub.getStep().getDocuments().remove(pub); + pub.getOwner().add(newpub); + pub.getStep().getDocuments().add(newpub); + return newpub; + } + /** * Test assigning a simulation context to a study.
* Description :
@@ -1347,13 +1598,13 @@ public class TestScenarioService extends BaseTest { SQLException, BusinessException { LOG.debug(">>>>> BEGIN testAssignStudyContextFromPython()"); startNestedTransaction(); - + HibernateTemplate ht = getHibernateTemplate(); - + Database.getInstance().reset(); _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again _projectSettings.configure("classpath:test/som.xml"); - + // Create a test user User goodUser = TestEntitiesGenerator.getTestUser("goodUser"); _userDAO.create(goodUser); @@ -1362,18 +1613,18 @@ public class TestScenarioService extends BaseTest { Assert .assertNotNull(prodtype, "Simulation context type 'product' must be created in the database."); - + String productName = "New Test Product " + new Date().toString(); - + ht.flush(); ht.clear(); long studyId1 = _scenarioService.createStudy("goodUser", "Test Study 1", productName, "Test description"); Assert.assertTrue(studyId1 > 0); - + ht.flush(); ht.clear(); - + // //////// START OF TESTS // 1. call the method for not existing study id.
try { @@ -1383,37 +1634,37 @@ public class TestScenarioService extends BaseTest { } catch (InvalidPropertyException ipe) { LOG.debug("Expected exception: " + ipe.getMessage()); } - + // 2. call the method for not existing context type and context value.
_scenarioService.assignStudyContext(studyId1, "new context type", "new context value"); - + ht.flush(); ht.clear(); - + // Check the assigned simulation context checkCtx(studyId1, "new context type", "new context value"); - + // 3. call the method for existing context type and context value.
_scenarioService.assignStudyContext(studyId1, "new context type", "new context value"); - + ht.flush(); ht.clear(); - + // Check the assigned simulation context checkCtx(studyId1, "new context type", "new context value"); - + // 4. call the method for existing context type and not existing context value.
_scenarioService.assignStudyContext(studyId1, "new context type", "new context value1"); - + ht.flush(); ht.clear(); - + // Check the assigned simulation context checkCtx(studyId1, "new context type", "new context value1"); - + // 5. call the method for empty context type.
try { _scenarioService.assignStudyContext(studyId1, "", @@ -1430,7 +1681,7 @@ public class TestScenarioService extends BaseTest { } catch (InvalidPropertyException ipe) { LOG.debug("Expected exception: " + ipe.getMessage()); } - + rollbackNestedTransaction(); LOG.debug(">>>>> END testAssignStudyContextFromPython()"); } @@ -1463,8 +1714,8 @@ public class TestScenarioService extends BaseTest { * if test data creation is failed */ @Test(groups = { "study", "sevice", "functional", "business" }) - public void testGetStudyScenarios() throws IOException, - SQLException, BusinessException { + public void testGetStudyScenarios() throws IOException, SQLException, + BusinessException { LOG.debug(">>>>> BEGIN testGetStudyScenarios()"); startNestedTransaction(); @@ -1480,7 +1731,8 @@ public class TestScenarioService extends BaseTest { Study study = TestEntitiesGenerator.getTestStudy(goodUser); long studyId1 = _studyDAO.create(study); ht.flush(); - Scenario scen = TestEntitiesGenerator.getTestScenario(study, "test scen11"); + Scenario scen = TestEntitiesGenerator.getTestScenario(study, + "test scen11"); long id11 = _scenarioDAO.create(scen); ht.flush(); study = TestEntitiesGenerator.getTestStudy(goodUser); @@ -1496,14 +1748,14 @@ public class TestScenarioService extends BaseTest { long id23 = _scenarioDAO.create(scen); ht.flush(); ht.clear(); - + // //////// START OF TESTS // 1. call the method for not existing study id. List scens = _scenarioService.getStudyScenarios(-1L); Assert.assertNotNull(scens); Assert.assertTrue(scens.isEmpty()); - + // 2. call the method for a study with one scenario. scens = _scenarioService.getStudyScenarios(studyId1); diff --git a/Workspace/Siman/WebContent/study/copyStudy.jsp b/Workspace/Siman/WebContent/study/copyStudy.jsp index 29aca70..6625458 100644 --- a/Workspace/Siman/WebContent/study/copyStudy.jsp +++ b/Workspace/Siman/WebContent/study/copyStudy.jsp @@ -1,87 +1,112 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> - + + function selectSourceStudy() { + $("#create").submit(); + } + + $(document).ready(function () { + create.projectContextId.value = ; + setValue(); + }); + -
-
-
-
- +
+
+ +
+
+ +
- - - + + + - - - - + + + + - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + -
-  *:  - - "> -
 *:  +
-  *:  - - - - - - - "/> -
 *:  +
 *:  +
 *:  +
 *:  +
-
-
-
+ + +
+ -
-
+
+
diff --git a/Workspace/Siman/src/labels.properties b/Workspace/Siman/src/labels.properties index b2b1f95..5e296bf 100644 --- a/Workspace/Siman/src/labels.properties +++ b/Workspace/Siman/src/labels.properties @@ -181,6 +181,9 @@ field.code = Code interne field.step = Activité concernée field.label = Nom en field.context.value = Valeur +field.fromStudy = Source study +field.fromScenario = Source scenario +field.finalStep = Up to the step criterion.study = Les études diff --git a/Workspace/Siman/src/labels_en.properties b/Workspace/Siman/src/labels_en.properties index b7723fb..c17c89d 100644 --- a/Workspace/Siman/src/labels_en.properties +++ b/Workspace/Siman/src/labels_en.properties @@ -182,6 +182,9 @@ field.code = Internal code field.step = Involved activity field.label = Name in field.context.value = Value +field.fromStudy = Source study +field.fromScenario = Source scenario +field.finalStep = Up to the step criterion.study = All studies diff --git a/Workspace/Siman/src/org/splat/simer/CopyStudyAction.java b/Workspace/Siman/src/org/splat/simer/CopyStudyAction.java index 1286f51..edd7643 100644 --- a/Workspace/Siman/src/org/splat/simer/CopyStudyAction.java +++ b/Workspace/Siman/src/org/splat/simer/CopyStudyAction.java @@ -10,13 +10,12 @@ package org.splat.simer; +import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.splat.kernel.InvalidPropertyException; -import org.splat.kernel.MissedPropertyException; -import org.splat.kernel.MultiplyDefinedException; +import org.splat.exception.BusinessException; import org.splat.service.SearchService; import org.splat.service.dto.Proxy; import org.splat.service.dto.ScenarioDTO; @@ -50,6 +49,15 @@ public class CopyStudyAction extends NewStudyAction { * The selected source study id. */ private long _fromStudyId = 0; + /** + * The selected source scenario id. + */ + private long _fromScenarioId = 0; + + /** + * The selected source study id. + */ + private int _finalStep = 0; /** * Injected search service. */ @@ -62,14 +70,19 @@ public class CopyStudyAction extends NewStudyAction { /** * {@inheritDoc} * + * @throws IOException + * * @see org.splat.simer.NewStudyAction#doCreate() */ @Override - public String doCreate() throws InvalidPropertyException, - MissedPropertyException, MultiplyDefinedException { + public String doCreate() throws BusinessException, IOException { String res = super.doCreate(); if (SUCCESS.equals(res)) { // Copy content from the selected study + getScenarioService().copyStudyContent(_fromStudyId, + _fromScenarioId, _finalStep, getOpenStudy().getIndex()); + } else { + doInitialize(); } return res; } @@ -83,31 +96,35 @@ public class CopyStudyAction extends NewStudyAction { public String doInitialize() { // Initialize contexts list, study title and menus. super.doInitialize(); - + // Initialize source studies list, scenarios list and steps list - + // Get visible studies StudySearchFilterDTO filter = new StudySearchFilterDTO(); if (getConnectedUser() != null) { filter.setConnectedUserId(getConnectedUser().getIndex()); } List studies = getSearchService().selectStudiesWhere(filter); - + // Fill the studies list - for (Proxy study: studies) { + _studies.put(0L, ""); + for (Proxy study : studies) { _studies.put(study.getIndex(), study.getTitle()); } - + // Fill lists of scenarios and steps according to the selected study if (_fromStudyId > 0 && _studies.containsKey(_fromStudyId)) { // Get scenarios from the selected study - List scens = getScenarioService().getStudyScenarios(_fromStudyId); - for (ScenarioDTO scen: scens) { + List scens = getScenarioService().getStudyScenarios( + _fromStudyId); + for (ScenarioDTO scen : scens) { _scenarios.put(scen.getIndex(), scen.getTitle()); } // Fill steps - for (ProjectSettingsService.Step step: getStepsConfigService().getSteps()) { - _steps.put(step.getNumber(), getText("folder.step." + step.getNumber())); + for (ProjectSettingsService.Step step : getStepsConfigService() + .getSteps()) { + _steps.put(step.getNumber(), + getText("folder.step." + step.getNumber())); } } @@ -198,4 +215,42 @@ public class CopyStudyAction extends NewStudyAction { final StepsConfigService stepsConfigService) { _stepsConfigService = stepsConfigService; } + + /** + * Get the fromScenarioId. + * + * @return the fromScenarioId + */ + public long getFromScenarioId() { + return _fromScenarioId; + } + + /** + * Set the fromScenarioId. + * + * @param fromScenarioId + * the fromScenarioId to set + */ + public void setFromScenarioId(final long fromScenarioId) { + _fromScenarioId = fromScenarioId; + } + + /** + * Get the finalStep. + * + * @return the finalStep + */ + public int getFinalStep() { + return _finalStep; + } + + /** + * Set the finalStep. + * + * @param finalStep + * the finalStep to set + */ + public void setFinalStep(final int finalStep) { + _finalStep = finalStep; + } } diff --git a/Workspace/Siman/src/org/splat/simer/NewStudyAction.java b/Workspace/Siman/src/org/splat/simer/NewStudyAction.java index 4a7e0a9..2058b08 100644 --- a/Workspace/Siman/src/org/splat/simer/NewStudyAction.java +++ b/Workspace/Siman/src/org/splat/simer/NewStudyAction.java @@ -1,15 +1,15 @@ package org.splat.simer; +import java.io.IOException; import java.util.List; import java.util.ResourceBundle; +import org.apache.commons.lang3.StringUtils; import org.splat.dal.bo.som.Scenario; import org.splat.dal.bo.som.SimulationContext; import org.splat.dal.bo.som.SimulationContextType; import org.splat.dal.bo.som.Study; -import org.splat.kernel.InvalidPropertyException; -import org.splat.kernel.MissedPropertyException; -import org.splat.kernel.MultiplyDefinedException; +import org.splat.exception.BusinessException; import org.splat.service.ScenarioService; import org.splat.service.SimulationContextService; import org.splat.wapp.Constants; @@ -37,10 +37,13 @@ public class NewStudyAction extends Action { */ private transient List _contelm = null; /** - * Project context. + * Selected project context string value. */ private String _projectContext = null; - + /** + * Selected project context id. + */ + private long _projectContextId = -1; /** * Injected simulation context service. */ @@ -65,10 +68,9 @@ public class NewStudyAction extends Action { _contelm = getSimulationContextService().getSimulationContextList(); // set the default name of the new study - ResourceBundle locale = ResourceBundle.getBundle("labels", - getApplicationSettings().getCurrentLocale()); - _title = locale.getString("label.study") + " " - + (number + 1); + if (StringUtils.isBlank(_title)) { + _title = getText("label.study") + " " + (number + 1); + } initializationFullScreenContext(Constants.CREATE_MENU, Constants.NONE, Constants.OPEN); @@ -80,21 +82,16 @@ public class NewStudyAction extends Action { * Create a new study. * * @return SUCCESS if the new study is created, INPUT if project context is not defined, ERROR if failed - * @throws InvalidPropertyException - * if some property has invalid value - * @throws MultiplyDefinedException - * if some property is defined several times - * @throws MissedPropertyException - * if properties of the new study are invalid + * @throws BusinessException + * if new study creation is failed + * @throws IOException + * if file operations are failed */ - public String doCreate() throws InvalidPropertyException, - MissedPropertyException, MultiplyDefinedException { + public String doCreate() throws BusinessException, IOException { String res = SUCCESS; - String[] input = _projectContext.split(","); - int valid = Integer.valueOf(input[0]); // Check arguments and creation of the study - if (valid == -1) { + if (_projectContextId == -1) { SimulationContext.Properties cprop = new SimulationContext.Properties(); SimulationContextType product = getSimulationContextService() .selectType("product"); @@ -103,9 +100,9 @@ public class NewStudyAction extends Action { // Title empty, simply wait for input without error message res = INPUT; } else { - String value; // input[1] if exists - if (valid == 0) { - value = input[1].trim(); + String value; // if new a project context has to be created + if (_projectContextId == 0) { + value = _projectContext.trim(); if (value.length() == 0) { initializationScreenContext(Constants.CREATE_MENU); // No need to reinitialize the list of existing products @@ -126,34 +123,36 @@ public class NewStudyAction extends Action { getApplicationSettings().getCurrentLocale()); Scenario.Properties oprop = new Scenario.Properties(); oprop.setTitle(locale.getString("label.scenario") + " 1"); - + // Addition of the entered project context SimulationContext.Properties cprop = new SimulationContext.Properties(); - if (valid == 0) { // Input of new project context + if (_projectContextId == 0) { // Input of new project context SimulationContextType product = getSimulationContextService() .selectType("product"); - - SimulationContext testContext = getSimulationContextService().selectSimulationContext(product, value); - + + SimulationContext testContext = getSimulationContextService() + .selectSimulationContext(product, value); + if (testContext == null) { - cprop.setType( - getSimulationContextService().selectType("product")) - .setValue(value); + cprop.setType( + getSimulationContextService().selectType( + "product")).setValue(value); } else { cprop.setIndex(testContext.getIndex()); } } else { // Selection of existing project context - cprop.setIndex(valid); + cprop.setIndex(_projectContextId); } - Study study = getScenarioService().createStudy(sprop, oprop, cprop); + Study study = getScenarioService().createStudy(sprop, + oprop, cprop); // Update of the session number += 1; open(study); // Opens the study, - + initializationFullScreenContext(Constants.STUDY_MENU, Constants.NONE, Constants.OPEN); - - } catch (Exception error) { + + } catch (BusinessException error) { LOG.error("Unable to save the study, reason:", error); setErrorCode("message.error.newstudy"); initializationScreenContext(Constants.NONE); @@ -163,21 +162,23 @@ public class NewStudyAction extends Action { } return res; } - + /** * * {@inheritDoc} + * * @see com.opensymphony.xwork2.ActionSupport#validate() */ @Override public void validate() { - - if( LOG.isDebugEnabled() ) { + + if (LOG.isDebugEnabled()) { LOG.debug("--- validate"); } - if( LOG.isDebugEnabled() ) { + if (LOG.isDebugEnabled()) { LOG.debug("======> MKA test"); - LOG.debug(com.opensymphony.xwork2.ActionContext.getContext().getName()); + LOG.debug(com.opensymphony.xwork2.ActionContext.getContext() + .getName()); } } @@ -270,4 +271,23 @@ public class NewStudyAction extends Action { public void setScenarioService(final ScenarioService scenarioService) { _scenarioService = scenarioService; } + + /** + * Get the projectContextId. + * + * @return the projectContextId + */ + public long getProjectContextId() { + return _projectContextId; + } + + /** + * Set the projectContextId. + * + * @param projectContextId + * the projectContextId to set + */ + public void setProjectContextId(final long projectContextId) { + _projectContextId = projectContextId; + } } \ No newline at end of file