--- /dev/null
+/*****************************************************************************
+ * 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 <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
+ */
+public class Constants {
+ /**
+ * Unchecked warning specification.
+ */
+ public static final String UNCHECKED = "unchecked";
+}
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. <BR>
+ * Parameter enumClassName defines the enumeration implementation class in <BR>
+ * hibernate mapping like this:<BR>
+ * <code>
+ * <typedef name="ProgressState" class="<i>org.splat.dal.bo.kernel.GenericEnumType</i>"><BR>
+ * <param name="<i>enumClassName</i>">org.splat.dal.bo.som.ProgressState</param><BR>
+ * </typedef><BR>
+ * </code>
+ */
public class GenericEnumType implements EnhancedUserType, ParameterizedType {
-
- @SuppressWarnings("unchecked")
- private Class<Enum> enumClass;
-
- @SuppressWarnings("unchecked")
- public void setParameterValues (Properties parameters) {
-// ------------------------------------------------------
- String enumClassName = parameters.getProperty("enumClassName");
- try {
- enumClass = (Class<Enum>) 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<Enum> _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<Enum>) 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
* 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
package org.splat.dal.bo.som;
+
/**
* Class defining the validation cycle applicable to documents of a given type.<br/>
* A validation cycle specifies the validation steps of documents complying with by this cycle, as well as the actors
* @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;
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<User> result = new ArrayList<User>();
+ 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<User> result = new Vector<User>();
- 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.<br/>
+ * 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.<br/>
- * 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;
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;
/**
*/
public abstract class AbstractGenericDAOImpl<T, PK extends Serializable>
extends HibernateDaoSupport implements GenericDAO<T, PK> {
- /**
- * Unchecked warning specification.
- */
- private static final String UNCHECKED = "unchecked";
/**
* Persist the newInstance object into database.
* @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);
}
* new object as a transient instance
* @see Session#saveOrUpdate(Object)
*/
- @SuppressWarnings(UNCHECKED)
+ @SuppressWarnings(Constants.UNCHECKED)
public void saveOrUpdate(final T newInstance) {
getSession().saveOrUpdate(newInstance);
}
* @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);
}
* 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();
*
* @return a list of all objects of the considered type T
*/
- @SuppressWarnings(UNCHECKED)
+ @SuppressWarnings(Constants.UNCHECKED)
public List<T> getAll() {
return getSession().createCriteria(getType()).list();
}
* 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<T> getAll(final Order... anOrder) {
Criteria aCriteria = getSession().createCriteria(getType());
for (Order order : anOrder) {
* search criteria
* @return a list of objects filtered according to the given criteria
*/
- @SuppressWarnings(UNCHECKED)
+ @SuppressWarnings(Constants.UNCHECKED)
public List<T> getFilteredList(final DetachedCriteria aDetachedCriteria) {
return aDetachedCriteria.getExecutableCriteria(getSession()).list();
}
* search criteria
* @return a list of DTO objects filtered according to the given criteria
*/
- @SuppressWarnings(UNCHECKED)
+ @SuppressWarnings(Constants.UNCHECKED)
public <DTO> List<DTO> getFilteredDTOList(
final DetachedCriteria aDetachedCriteria) {
return aDetachedCriteria.getExecutableCriteria(getSession()).list();
* a search condition
* @return a list of objects filtered according to the given criteria
*/
- @SuppressWarnings(UNCHECKED)
+ @SuppressWarnings(Constants.UNCHECKED)
public List<T> getFilteredList(final Criterion aCondition) {
return getSession().createCriteria(getType()).add(aCondition).list();
}
* 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<T> getFilteredList(final Criterion aCondition,
final Order... anOrder) {
Criteria aCriteria = getSession().createCriteria(getType()).add(
* 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<T> getFilteredList(final String joinField,
final Criterion aCondition, final Order... anOrder) {
Criteria aCriteria = getSession().createCriteria(getType());
* @return merged persistent object
* @see Session#merge(Object)
*/
- @SuppressWarnings(UNCHECKED)
+ @SuppressWarnings(Constants.UNCHECKED)
public T merge(final T transientObject) {
return (T) getSession().merge(transientObject);
}
* the object to be removed from session cache
* @see Session#evict(Object)
*/
- @SuppressWarnings(UNCHECKED)
public void evict(final T persistentObject) {
getSession().evict(persistentObject);
}
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;
*/
private StepsConfigService _stepsConfigService;
+ /**
+ * Injected repository service.
+ */
+ private RepositoryService _repositoryService;
+
/**
* Get the projectElementService.
*
for (Scenario scen : fromStudy.getScenariiList()) {
if (scen.getIndex() == fromScenId) {
fromScen = scen;
+ break;
}
}
}
// 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<Publication, Publication> oldToNewPub = new HashMap<Publication, Publication>();
}
}
+ /**
+ * 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 <BR>
* the given step according to the given map of old publications to new publications.
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;
}
*
* @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);
}
/**
// 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());
}
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
+ 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
_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;
+ }
+
}
@Transactional
public Study selectStudy(final long index) {
Study result = getStudyDAO().get(index);
- loadWorkflow(result);
+ if (result != null) {
+ loadWorkflow(result);
+ }
return result;
}
// 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);
}
}
* 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}
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;
}
}
}
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();
}
}
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));
}
+ "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(",");
}
} // for
- JFreeChart chart = ChartFactory.createXYLineChart(
- chartTitle, // Title
+ JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // Title
axis1Name, // x-axis Label
axis2Name, // y-axis Label
dataset, // Dataset
* @see org.splat.service.StudyService#getComparableStudies()
*/
@Transactional(readOnly = true)
- public List<StudyFacadeDTO> getComparableStudies(final long userId) throws MismatchException {
- //retrieve the number of the "Analyze the results" step
+ public List<StudyFacadeDTO> getComparableStudies(final long userId)
+ throws MismatchException {
+ // retrieve the number of the "Analyze the results" step
List<Step> allSteps = _projectSettings.getAllSteps();
Step theAnalyzeStep = null;
- for(Step step : allSteps) {
- if(step.getKey().equals("postprocessing")) {
+ for (Step step : allSteps) {
+ if (step.getKey().equals("postprocessing")) {
theAnalyzeStep = step;
}
}
- if(theAnalyzeStep == null) { //TODO: throw some other exception
- throw new MismatchException("no step with key 'postprocessing' found." +
- "Probably, customization settings have been changed.");
+ if (theAnalyzeStep == null) { // TODO: throw some other exception
+ throw new MismatchException(
+ "no step with key 'postprocessing' found."
+ + "Probably, customization settings have been changed.");
}
- List<Publication> publications = _publicationDAO.getFilteredList("mydoc",
- Restrictions.eq("step", Integer.valueOf(theAnalyzeStep.getNumber())));
+ List<Publication> publications = _publicationDAO.getFilteredList(
+ "mydoc", Restrictions.eq("step", Integer.valueOf(theAnalyzeStep
+ .getNumber())));
- //split retrieved publications into groups by studies and scenarios
+ // split retrieved publications into groups by studies and scenarios
Map<Study, List<ProjectElement>> studyMap = new HashMap<Study, List<ProjectElement>>();
- Map<ProjectElement, List<Publication>> scenarioMap =
- new HashMap<ProjectElement, List<Publication>>();
-
- for(Publication publication : publications) {
- //filter out publications corresponding to a document of given step which is not a _result_ document
- if(!publication.value().getType().isResultOf(theAnalyzeStep)
+ Map<ProjectElement, List<Publication>> scenarioMap = new HashMap<ProjectElement, List<Publication>>();
+
+ for (Publication publication : publications) {
+ // filter out publications corresponding to a document of given step which is not a _result_ document
+ if (!publication.value().getType().isResultOf(theAnalyzeStep)
|| !"srd".equals(publication.getSourceFile().getFormat())) {
continue;
}
-
- //check the study visibility to the user
- if(!isStaffedBy(publication.getOwnerStudy(), _userService.selectUser(userId))
- && Visibility.PUBLIC.equals(publication.getOwnerStudy().getVisibility())) {
+
+ // check the study visibility to the user
+ if (!isStaffedBy(publication.getOwnerStudy(), _userService
+ .selectUser(userId))
+ && Visibility.PUBLIC.equals(publication.getOwnerStudy()
+ .getVisibility())) {
continue;
}
-
+
Study study = publication.getOwnerStudy();
ProjectElement scenario = publication.getOwner();
-
+
Hibernate.initialize(scenario);
- if (scenario instanceof HibernateProxy) {
- scenario = (ProjectElement) ((HibernateProxy) scenario).getHibernateLazyInitializer()
- .getImplementation();
- }
-
- if(!(scenario instanceof Scenario)) {
+ if (scenario instanceof HibernateProxy) {
+ scenario = (ProjectElement) ((HibernateProxy) scenario)
+ .getHibernateLazyInitializer().getImplementation();
+ }
+
+ if (!(scenario instanceof Scenario)) {
throw new MismatchException(
"publications from postprocessing step are supposed to have owner scenario");
}
- if(!studyMap.containsKey(study)) {
+ if (!studyMap.containsKey(study)) {
studyMap.put(study, new ArrayList<ProjectElement>());
}
-
- if(!studyMap.get(study).contains(scenario)) {
+
+ if (!studyMap.get(study).contains(scenario)) {
studyMap.get(study).add(scenario);
}
- if(!scenarioMap.containsKey(scenario)) {
+ if (!scenarioMap.containsKey(scenario)) {
scenarioMap.put(scenario, new ArrayList<Publication>());
}
scenarioMap.get(scenario).add(publication);
}
-
- //Create the result DTOs
+
+ // Create the result DTOs
List<StudyFacadeDTO> result = new ArrayList<StudyFacadeDTO>();
- for(Study study : studyMap.keySet()) {
-
+ for (Study study : studyMap.keySet()) {
+
StudyFacadeDTO studyDTO = new StudyFacadeDTO();
studyDTO.setName(study.getTitle());
studyDTO.setScenarios(new ArrayList<StudyFacadeDTO.ScenarioDTO>());
result.add(studyDTO);
-
- for(ProjectElement scenario : studyMap.get(study)) {
-
+
+ for (ProjectElement scenario : studyMap.get(study)) {
+
StudyFacadeDTO.ScenarioDTO scenarioDTO = new StudyFacadeDTO.ScenarioDTO();
scenarioDTO.setName(scenario.getTitle());
scenarioDTO.setDocs(new ArrayList<DocumentDTO>());
studyDTO.getScenarios().add(scenarioDTO);
- for(Publication publication : scenarioMap.get(scenario)) {
+ for (Publication publication : scenarioMap.get(scenario)) {
DocumentDTO documentDTO = new DocumentDTO();
documentDTO.setId(publication.getIndex());
documentDTO.setTitle(publication.value().getTitle());
-
+
scenarioDTO.getDocs().add(documentDTO);
}
}
- }
+ }
return result;
}
-
+
/**
* Get the publicationDAO.
*
FileInputStream inputStream = new FileInputStream(src);
try {
+ // Create target directory if necessary
+ if (!target.getParentFile().exists()) {
+ target.getParentFile().mkdirs();
+ }
FileOutputStream outputStream = new FileOutputStream(target);
try {
ref="projectElementService" />
<property name="projectSettings" ref="projectSettings" />
<property name="publicationService" ref="publicationService" />
- <property name="stepService" ref="stepService" />
+ <property name="stepService" ref="stepService" />
+ <property name="stepsConfigService" ref="stepsConfigService" />
<property name="studyService" ref="studyService" />
<property name="knowledgeElementDAO" ref="knowledgeElementDAO" />
<property name="scenarioDAO" ref="scenarioDAO" />
<property name="validationCycleDAO" ref="validationCycleDAO" />
<property name="knowledgeElementTypeService"
ref="knowledgeElementTypeService" />
+ <property name="repositoryService" ref="repositoryService" />
<property name="userService" ref="userService" />
<property name="userDAO" ref="userDAO" />
<property name="roleDAO" ref="roleDAO" />
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;
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;
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;
@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.<BR>
* <B>Description :</B> <BR>
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.
*
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);
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 {
} 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()");
}
* <i>Create a study.</i><BR>
* <B>Action : </B><BR>
* <i>1. call the method for a not existing source study.</i><BR>
- * <i>1. call the method for a not existing source scenario.</i><BR>
- * <i>1. call the method for a not existing source study.</i><BR>
- * <i>2. call the method for an existing username and an existing product.</i><BR>
- * <i>3. call the method for a not existing username expecting an exception.</i><BR>
+ * <i>2. call the method for a not existing source scenario with not evolving step.</i><BR>
+ * <i>3. call the method for a not existing source scenario with evolving step.</i><BR>
+ * <i>4. call the method for an existing source scenario with evolving step.</i><BR>
* <B>Test data : </B><BR>
* <i>no input parameters</i><BR>
*
* <B>Outcome results:</B><BR>
* <i>
* <ul>
- * <li>1: The new study must be created. The new product simulation context must be created.</li>
- * <li>2: The new study must be created.</li>
- * <li>3: The new study must not be created. Exception must be thrown.</li>
+ * <li>1: Exception must be thrown.</li>
+ * <li>2: The study content must be copied.</li>
+ * <li>3: Exception must be thrown.</li>
+ * <li>4: The study content must be copied.</li>
* </ul>
* </i>
*
_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<Integer, org.splat.som.Step> 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<Integer, org.splat.som.Step> 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.<BR>
* <B>Description :</B> <BR>
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);
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.</i><BR>
try {
} catch (InvalidPropertyException ipe) {
LOG.debug("Expected exception: " + ipe.getMessage());
}
-
+
// 2. call the method for not existing context type and context value.</i><BR>
_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.</i><BR>
_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.</i><BR>
_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.</i><BR>
try {
_scenarioService.assignStudyContext(studyId1, "",
} catch (InvalidPropertyException ipe) {
LOG.debug("Expected exception: " + ipe.getMessage());
}
-
+
rollbackNestedTransaction();
LOG.debug(">>>>> END testAssignStudyContextFromPython()");
}
* 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();
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);
long id23 = _scenarioDAO.create(scen);
ht.flush();
ht.clear();
-
+
// //////// START OF TESTS
// 1. call the method for not existing study id.
List<ScenarioDTO> 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);
-<%@ 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"%>
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<script language="JavaScript">
+ function initialize() {
+ create.elements[0].focus();
+ }
- <script language="JavaScript">
+ function setValue() {
+ var select = create.projectContextId.value; // contextValue select input
+ if (select == "0") { // Creation of a new context type
+ tds = document.getElementById("select");
+ tde = document.getElementById("enter");
+ tds.style.display = "none"; // Hides the select input
+ tde.style.display = "block"; // Displays the text input
+ }
+ create.projectContext.focus();
+ }
- function initialize () {
-// ----------------------
- create.elements[0].focus();
- }
-
- function setValue () {
-// -------------------
- var select = create.elements[1].value; // contextValue select input
- if (select == "0") { // Creation of a new context type
- tds = document.getElementById("select");
- tde = document.getElementById("enter");
- tds.style.display = "none"; // Hides the select input
- tde.style.display = "block"; // Displays the text input
- }
- create.elements[2].focus();
- }
- </script>
+ function selectSourceStudy() {
+ $("#create").submit();
+ }
+
+ $(document).ready(function () {
+ create.projectContextId.value = <s:property value="projectContextId"/>;
+ setValue();
+ });
+</script>
<!-- New study dialog
- =============================================================================================================================
+ ===========================================================================
-->
- <div id=article-box>
- <div id=section><s:text name="title.newstudy"/></div>
- <div id=top-spacer></div>
- <form name="create" action="valid-new" method="post">
- <table class="text">
+<div id="article-box">
+ <div id="section">
+ <s:text name="title.newstudy" />
+ </div>
+ <div id="top-spacer"></div>
+ <form id="create" name="create" action="new-copy" method="post">
+ <table class="text">
- <tr class="error">
- <td colspan=3><s:text name="%{error}"/></td>
- </tr>
+ <tr class="error">
+ <td colspan="3"><s:text name="%{error}" /></td>
+ </tr>
- <tr>
- <td>
- <s:text name="field.studytitle"/>*:
- </td>
- <td colspan=2>
- <input type=text size="60" name=title value="<s:property value="title"/>">
- </td>
- </tr>
+ <tr>
+ <td> <s:text name="field.studytitle" />*:
+ </td>
+ <td><s:textfield theme="simple" size="60" name="title" /></td>
+ </tr>
- <tr>
- <td>
- <s:text name="field.product"/>*:
- </td>
- <s:if test="projectContextValues.size > 0">
- <td id=select>
- <select name="projectContext" style="width:214px" onChange="setValue()">
- <option value="-1"><s:text name="menu.select"/></option>
- <option value="0"> <s:text name="menu.newproduct"/></option>
- <optgroup label=" <s:text name="label.products"/>">
- <s:iterator value="projectContextValues">
- <option value="<s:property value="index"/>"> <s:property value="value"/></option>
- </s:iterator>
- </optgroup>
- </select>
- </td>
- <td id=enter style="display: none">
- <input type=text size="30" name=projectContext>
- </td>
- </s:if>
- <s:else>
- <td>
- <input type=hidden name=projectContext value="0">
- <input type=text size="30" name=projectContext>
- </td>
- </s:else>
- <td align=right>
- <input type="submit" value="<s:text name="button.newstudy"/>"/>
- </td>
- </tr>
+ <tr>
+ <td> <s:text name="field.product" />*:
+ </td>
+ <s:if test="projectContextValues.size > 0">
+ <td id="select"><select name="projectContextId"
+ style="width: 214px" onChange="setValue()">
+ <option value="-1">
+ <s:text name="menu.select" />
+ </option>
+ <option value="0">
+
+ <s:text name="menu.newproduct" />
+ </option>
+ <optgroup label=" <s:text name="label.products"/>">
+ <s:iterator value="projectContextValues">
+ <option value="<s:property value="index"/>">
+
+ <s:property value="value" />
+ </option>
+ </s:iterator>
+ </optgroup>
+ </select></td>
+ <td id="enter" style="display: none"><s:textfield
+ theme="simple" size="30" name="projectContext" /></td>
+ </s:if>
+ <s:else>
+ <td><s:hidden name="projectContextId" value="0" /> <s:textfield
+ size="30" name="projectContext" /></td>
+ </s:else>
+ </tr>
+ <tr>
+ <td> <s:text name="field.fromStudy" />*:
+ </td>
+ <td><s:select theme="simple" list="studies" name="fromStudyId"
+ onchange="selectSourceStudy()" /></td>
+ </tr>
+ <tr>
+ <td> <s:text name="field.finalStep" />*:
+ </td>
+ <td><s:select theme="simple" list="steps" name="finalStep" /></td>
+ </tr>
+ <tr>
+ <td> <s:text name="field.fromScenario" />*:
+ </td>
+ <td><s:select theme="simple" list="scenarios"
+ name="fromScenarioId" /></td>
+ </tr>
+ <tr>
+ <td align="right" colspan="2"><s:submit action="valid-copy"
+ theme="simple" type="button" key="button.newstudy" /></td>
+ </tr>
- </table>
- </form>
- <div id=top-spacer></div>
- </div>
+ </table>
+ </form>
+ <div id="top-spacer"></div>
+</div>
<!-- Reserved
-->
- <div id=right-pane></div>
- <div id=bottom-spacer></div>
+<div id="right-pane"></div>
+<div id="bottom-spacer"></div>
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
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
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;
* 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.
*/
/**
* {@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;
}
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<Proxy> 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<ScenarioDTO> scens = getScenarioService().getStudyScenarios(_fromStudyId);
- for (ScenarioDTO scen: scens) {
+ List<ScenarioDTO> 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()));
}
}
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;
+ }
}
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;
*/
private transient List<SimulationContext> _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.
*/
_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);
* 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");
// 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
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);
}
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());
}
}
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