--- /dev/null
+<upgrade-log>
+ <entry time="2012-10-08 05:14:16 UTC">
+ <upgrade-participant pluginId="com.bea.workshop.common.wtp.core" pluginVersion="1.2.1.20080808135653" class="com.bea.workshop.common.wtp.core.upgrade.internal.WtpComponentFileUpgradeParticipant"/>
+ </entry>
+</upgrade-log>
--- /dev/null
+Manifest-Version: 1.0
+Class-Path:
+
<classpathentry exported="true" kind="lib" path="lib/org.springframework.instrument-3.1.2.RELEASE.jar"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.jdbc-3.1.2.RELEASE.jar"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.jms-3.1.2.RELEASE.jar"/>
- <classpathentry exported="true" kind="lib" path="lib/org.springframework.orm-3.1.2.RELEASE.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/org.springframework.orm-3.1.2.RELEASE.jar" sourcepath="/3dparty_src/hibernate/hibernate-distribution-3.5.3-Final-dist.zip"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.oxm-3.1.2.RELEASE.jar"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.test-3.1.2.RELEASE.jar"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.transaction-3.1.2.RELEASE.jar"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.web.struts-3.1.2.RELEASE.jar"/>
<classpathentry exported="true" kind="lib" path="lib/org.springframework.web-3.1.2.RELEASE.jar"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
+ <classpathentry exported="true" kind="lib" path="lib/p6spy.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/aopalliance.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
</configExtensions>
<configs>
<config>src/spring/globalContext.xml</config>
+ <config>src/spring/businessServiceContext.xml</config>
+ <config>src/spring/daoServiceContext.xml</config>
+ <config>src/spring/technicalServiceContext.xml</config>
</configs>
<configSets>
+ <configSet>
+ <name><![CDATA[Siman beans]]></name>
+ <allowBeanDefinitionOverriding>true</allowBeanDefinitionOverriding>
+ <incomplete>false</incomplete>
+ <configs>
+ <config>src/spring/globalContext.xml</config>
+ <config>src/spring/businessServiceContext.xml</config>
+ <config>src/spring/daoServiceContext.xml</config>
+ <config>src/spring/technicalServiceContext.xml</config>
+ </configs>
+ </configSet>
</configSets>
</beansProjectDescription>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the root abstract class supporting dynamic attributes.
+ - All objects instance of a subclass of Any are uniquely identified by the rid primary key through the IDGenerator identifier generator class.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <!-- <class name="org.splat.dal.bo.kernel.Any" abstract="true"> -->
+ <union-subclass name="org.splat.dal.bo.kernel.Any" extends="org.splat.dal.bo.kernel.Persistent" abstract="true" table="any">
+ <!-- int rid -->
+<!-- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
+ <generator class="org.splat.dal.bo.kernel.IDGenerator"/>
+ </id> -->
+
+<!-- <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id>-->
+
+ <!-- Set<Attribute> attributes -->
+ <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Attribute" />
+ </set>
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+/**
+ * Abstract root class of persistent objects supporting dynamic attributes.<br/>
+ * Dynamic attributes are instances of concrete subclasses of Attribute that are assigned to Any objects at run time.
+ * The attributes of a given Any object must all be of different types.
+ *
+ * @see Attribute
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.hibernate.Session;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.ObjectProperties;
+
+
+public abstract class Any extends Persistent {
+
+ private Set<Attribute> attributes;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor.
+ protected Any () {
+ }
+// Initialization constructors
+ protected Any (ObjectProperties oprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// --------------------------------------
+ super(oprop);
+ attributes = new HashSet<Attribute>();
+ }
+ protected Any (Attribute... field) {
+// ----------------------------------
+ attributes = new HashSet<Attribute>();
+ for (int i=0; i<field.length; i++) {
+ if (field[i] == null) continue; // Happen when newing an Any object without property
+ if (field[i].getFrom().equals(this)) attributes.add(field[i]);
+ }
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Attribute getAttribute (Class<? extends Attribute> type) {
+// ---------------------------------------------------------------
+ for (Iterator<Attribute> i=attributes.iterator(); i.hasNext(); ) {
+ Attribute field = i.next();
+ if (field.getClass().equals(type)) return field;
+ }
+ return null;
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ protected boolean removeAttribute (Attribute field) {
+// ---------------------------------------------------
+ for (Iterator<Attribute> i=attributes.iterator(); i.hasNext(); ) {
+ if (!i.next().equals(field)) continue;
+ i.remove();
+ if (this.isSaved()) Database.getSession().update(this);
+ return true;
+ }
+ return false;
+ }
+
+ public boolean setAttribute (Attribute field) {
+// ------------------------------------------------
+ Class<?> type = field.getClass();
+ Session session = Database.getSession();
+
+ if (!field.getFrom().equals(this)) return false;
+ for (Iterator<Attribute> i=attributes.iterator(); i.hasNext(); ) {
+ if (!i.next().getClass().equals(type)) continue;
+ i.remove();
+ break;
+ }
+ attributes.add(field);
+ if (this.isSaved()) {
+ if (!field.isSaved()) session.save(field);
+ session.update(this);
+ } // Else, when saving this, Hibernate will propagate the operation
+ return true;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the Attribute class hierarchy.
+ - The attribute hierarchy is mapped to a single table using a String discriminator.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <class name="org.splat.dal.bo.kernel.Attribute" abstract="true" table="attribute">
+
+ <!-- int rid -->
+ <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id>
+ <discriminator column="type" type="string"/>
+
+ <!-- Any owner -->
+ <many-to-one name="owner" column="owner" access="field" not-null="true" />
+
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+/**
+ *
+ * @see Any
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+
+public abstract class Attribute extends Persistent {
+
+ protected Any owner;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor.
+ protected Attribute () {
+ }
+// Initialization constructor
+ protected Attribute (Any from) {
+// ------------------------------
+ this.owner = from;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Persistent getFrom () {
+// ----------------------------
+ return owner;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the root abstract class supporting relations.
+ -
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- <class name="org.splat.dal.bo.kernel.Entity" abstract="true"> -->
+ <union-subclass name="org.splat.dal.bo.kernel.Entity" abstract="true" extends="org.splat.dal.bo.kernel.Any" table="entity">
+
+ <!-- int rid -->
+<!-- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
+ <generator class="org.splat.dal.bo.kernel.IDGenerator"/>
+ </id>-->
+
+ <!-- Set<Attribute> attributes -->
+<!-- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Attribute" />
+ </set> -->
+
+ <!-- Set<Relation> relations -->
+ <set name="relations" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Relation" />
+ </set>
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+/**
+ * Abstract root class of persistent objects supporting relations to other persistent objects.<br/>
+ * Relations are instances of concrete subclasses of Relation that are assigned to Entity objects at run time.<br/>
+ * <br/>
+ * Entity objects also support dynamic attributes provided by the Any class.
+ *
+ * @see Relation
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+
+import org.hibernate.Session;
+import org.splat.dal.dao.kernel.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.ObjectProperties;
+
+
+public abstract class Entity extends Any {
+
+ private Set<Relation> relations;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected Entity () {
+ }
+// Initialization constructor
+ protected Entity (ObjectProperties prop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// ----------------------------------------
+ super(prop);
+ relations = new HashSet<Relation>();
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Relation getFirstRelation (Class<? extends Relation> type) {
+// -----------------------------------------------------------------
+ for (Iterator<Relation> i=relations.iterator(); i.hasNext();) {
+ Relation link = i.next();
+ if (link.getClass().equals(type)) return link;
+ }
+ return null;
+ }
+
+ public List<Relation> getRelations (Class<? extends Relation> type) {
+// -------------------------------------------------------------------
+ List<Relation> result = new Vector<Relation>();
+
+ for (Iterator<Relation> i=relations.iterator(); i.hasNext();) {
+ Relation link = i.next();
+ if (link.getClass().equals(type)) result.add(link);
+ }
+ return result;
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ protected Set<Relation> getAllRelations () {
+// ------------------------------------------
+ return relations;
+ }
+
+ protected Relation addRelation (Relation link) {
+// ----------------------------------------------
+ Session session = Database.getSession();
+
+ session.save(link);
+ relations.add(link);
+ session.update(this);
+
+ if (link.isBidirectional()) {
+ Entity to = (Entity)link.getTo(); // Bidirectional relation are necessarily between entities
+
+ link = link.getReverse();
+ session.save(link);
+// if (to.relations == null) to.relations = new HashSet<Relation>();
+ to.relations.add(link);
+ session.update(to);
+ }
+ return link;
+ }
+
+ protected void removeRelation (Class<? extends Relation> type, Persistent to) {
+// -----------------------------------------------------------------------------
+ for (Iterator<Relation> i=relations.iterator(); i.hasNext();) {
+ Relation link = i.next();
+ if (!link.getClass().equals(type)) continue;
+ if (!link.getTo().equals(to)) continue;
+ i.remove();
+ if (this.isSaved()) Database.getSession().update(this);
+ return;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+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;
+
+
+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();
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the primary key common to all Persistent objects.
+ -
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <class name="org.splat.dal.bo.kernel.Persistent" abstract="true">
+
+
+<!-- <id name="rid" column="rid" access="field">
+ <generator class="sequence"/>
+ </id> -->
+ <id name="rid" column="rid" access="field">
+ <generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
+ <param name="sequence_name">persistent_id</param>
+ <param name="initial_value">1000</param>
+ </generator>
+ </id>
+
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.ObjectProperties;
+
+/**
+ * Base implementation of the API Design Pattern of objects which persistence is based on Hibernate.<br/>
+ * This Design Pattern supports the following features:
+ * <ul>
+ * <li>Flexible API for constructing objects from many variable arguments</li>
+ * <li>Impossible to leave persistent objects in inconsistent state, even temporarily, during their construction</li>
+ * <li>Same Object Oriented API for constructing and selecting objects from the database</li>
+ * <li>Centralized validity check of arguments</li>
+ * </ul>
+ * The API is based on intermediate properties objects used for collecting arguments and checking their validity.
+ * These properties objects are passed to persistent object constructors and database select functions for execution.
+ * For example, as based on this Design Pattern, a User object could be created that way:
+ * <pre>
+ * User.Properties args = new User.Properties();
+ * User user = new User( args.setUsername("mypseudo").setMailAddress("me@provider.domain") );
+ * </pre>
+ * Classes implementing this Design Pattern must inherit from Persistent and implement their Properties class as a nested
+ * subclass of Persistent.Properties.<br/>
+ * <br/>
+ * Naturally, as usual with Hibernate, any class can be persistent (you don't need to inherit from Persistent for being
+ * persistent). Inheriting from Persistent is only a matter of enabling the API supported by the above Design Pattern.
+ *
+ * @see ObjectProperties
+ * @see Persistent.Properties
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+
+public abstract class Persistent {
+
+ private int rid; // Primary key of persistent objects
+
+ protected abstract static class Properties implements ObjectProperties {
+// ----------------------------------------------------------------------
+ private boolean tobechecked = true; // Property validity check flag
+
+ public void disableCheck () {
+ tobechecked = false;
+ }
+ public boolean mustBeChecked () {
+ return tobechecked;
+ }
+ public void clear () {
+ tobechecked = true;
+ }
+ }
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+/**
+ * Database fetch constructor.
+ */
+ protected Persistent () {
+// -----------------------
+ rid = 0; // Set when loading the object
+ }
+
+/**
+ * Checks the mutual compatibility of arguments previously set in the given properties object, if the validity check is enabled.
+ * As this validity depends on concrete classes, the check is delegated to subclasses of the given Persistent.Properties.
+ */
+ protected Persistent (ObjectProperties oprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// ---------------------------------------------
+ if (oprop.mustBeChecked()) oprop.checkValidity(); // Throws one of the above exception if not valid
+ rid = 0; // Set when saving the object
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean equals(Object entity) {
+// ------------------------------------
+ if (entity == null) return false;
+ if (entity.getClass().equals(this.getClass())) {
+ Persistent object = (Persistent)entity;
+ int he = object.getIndex(); // getIndex() is supposed fetching the index if not yet done
+ int me = this.getIndex(); // getIndex() is supposed fetching the index if not yet done
+ if (me*he != 0) return (he == me);
+ if (me+he == 0) return (this == object);
+ }
+ return false;
+ }
+
+/**
+ * Returns the Persistent ID of this object. The PID is set when saving this object. It is unique in the scope of the class
+ * of this object only.
+ *
+ * @return the PID of this, or 0 if this is not saved.
+ * @see isSaved()
+ */
+ public int getIndex () {
+// ----------------------
+ return rid;
+ }
+
+ public int hashCode () {
+// ----------------------
+ return toString().hashCode();
+ }
+
+/**
+ * Returns true if this object is saved.
+ *
+ * @return true if this is saved.
+ * @see getIndex()
+ */
+ public boolean isSaved () {
+// -------------------------
+ return (getIndex() != 0); // getIndex() is supposed fetching the index if not yet done
+ }
+
+/**
+ * Return a string representing uniquely this object.
+ *
+ * @return the unique string representation of this object.
+ */
+ public String toString () {
+// -------------------------
+ int oid = getIndex(); // getIndex() is supposed fetching the index if not yet done
+ if (oid == 0) oid = super.hashCode(); //WARNING: Must not call super.toString() as it goes back here (this.toString())
+ return new StringBuffer("object ").append(getClass().getName()).append("@").append(oid).toString();
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the Relation class hierarchy.
+ - The entire hierarchy is mapped to one single table using a String discriminator.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- <class name="org.splat.dal.bo.kernel.Relation" abstract="true" table="relation"> -->
+ <class name="org.splat.dal.bo.kernel.Relation" abstract="true">
+
+ <!-- int rid -->
+<!-- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
+ <generator class="org.splat.dal.bo.kernel.IDGenerator"/>
+ </id>-->
+ <id name="rid" column="rid" access="field">
+ <generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
+ <param name="sequence_name">relation_id</param>
+ </generator>
+ </id>
+ <!-- <discriminator column="name" type="string"/>-->
+
+ <!-- Set<Attribute> attributes -->
+ <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Attribute" />
+ </set>
+
+ <!-- Entity owner -->
+ <many-to-one name="owner" column="owner" access="field" not-null="true" />
+
+ <!-- <property name="to" column="refer" access="property" not-null="true" />-->
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+/**
+ * Base implementation of relations between entities.<br/>
+ * A relation makes a typed link from an entity to any kind persistent object. The relations are typed by subclasses of this
+ * abstract class which define the actual object referenced by the relation.<br/>
+ * This Relation base class implements unidirectional relations. The bidirectionality must be implemented in concrete subclasses
+ * by:
+ * <ul>
+ * <li>overriding the isBidirectional() and getReverseClass() methods,</li>
+ * <li>creating the reverse relation in constructors.</li>
+ * </ul>
+ * Relation objects also support dynamic attributes provided by the Any class.
+ *
+ * @see Entity
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Iterator;
+
+import org.hibernate.Session;
+import org.splat.dal.dao.kernel.Database;
+
+
+public abstract class Relation extends Any {
+
+// Persistent fields
+ protected Entity owner; // Study or Document
+
+// Transient field
+ protected Relation reverse;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected Relation () {
+// ---------------------
+ reverse = null;
+ }
+// Initialization constructor
+ protected Relation (Entity from) {
+// --------------------------------
+ super((Attribute)null); // For building the collection of attributes
+ this.owner = from;
+ this.reverse = null; // Initialized by subclasses
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Entity getFrom () {
+// ------------------------
+ return owner;
+ }
+
+ public Relation getReverse () {
+// -----------------------------
+ if (!this.isBidirectional() || reverse != null) return reverse;
+
+ Class<? extends Relation> type = this.getReverseClass();
+ Entity to = (Entity)this.getTo(); // Bidirectional relations are necessarily between Entities
+
+ for (Iterator<Relation> i=to.getAllRelations().iterator(); i.hasNext(); ) {
+ Relation asked = i.next();
+ if (!asked.getClass().equals(type)) continue;
+ if (!asked.getTo().equals(owner)) continue;
+ reverse = asked;
+ reverse.reverse = this; // For benefiting from this execution
+ return reverse;
+ }
+ return null;
+ }
+
+ public Class<? extends Relation> getReverseClass () {
+// ---------------------------------------------------
+ return null;
+ }
+
+ public boolean isBidirectional () {
+// ---------------------------------
+ return false;
+ }
+
+/**
+ * Moves this relation from its current owner entity to the given one.
+ *
+ * @param nowner the document to which this relation is moved
+ * */
+ public void moveTo (Entity nowner) {
+// ----------------------------------
+ Session session = Database.getSession();
+
+ this.owner = nowner;
+ nowner.getAllRelations().add(this);
+// myold.getAllRelations().remove(this); Harmful as it leads to remove this relation from the database (!?)
+ session.update(this);
+ session.update(nowner);
+
+ if (this.isBidirectional()) {
+ Relation link = this.getReverse();
+ link.setTo(nowner);
+ session.update(link);
+ }
+ }
+
+// ==============================================================================================================================
+// Abstract functions
+// ==============================================================================================================================
+
+ public abstract Persistent getTo ();
+ protected abstract void setTo (Persistent to); // For the need of the moveTo() method
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+/**
+ * Class of objects representing the role of users.
+ * A role is named by an application-dependent string (reason why role names are not defined by an enumeration).
+ * A user may have several roles, user roles being stored into the database as a list of role names separated by a comma.
+ *
+ * @see User
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Vector;
+
+
+public class Role {
+
+ private String username;
+ private String role;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected Role () {
+ }
+// Initialization constructor
+ protected Role (String username, String role) {
+// ---------------------------------------------
+ this.username = username;
+ this.role = role;
+ }
+
+// ==============================================================================================================================
+// Protected member functions
+// ==============================================================================================================================
+
+ protected void addRole (String role) {
+// ------------------------------------
+ this.role = this.role + "," + role;
+ }
+
+ protected Role[] toArray () {
+// ---------------------------
+ String[] name = role.split(",");
+ Vector<Role> role = new Vector<Role>();
+
+ for (int i=0; i<name.length; i++) role.add(new Role(username, name[i]));
+ return role.toArray(new Role[name.length]);
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+// In functions bellow, the role is supposed having previously been extracted as an array.
+
+ public String getName () {
+// ------------------------
+ return role;
+ }
+
+ public boolean is (String name) {
+// -------------------------------
+ return this.role.equals(name);
+ }
+
+ public boolean isSame (Role other) {
+// ----------------------------------
+ return this.role.equals(other.role);
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+ <joined-subclass name="org.splat.dal.bo.kernel.TextAttribute" extends="org.splat.dal.bo.kernel.Attribute" table="text_attr">
+ <key column="rid"/>
+ <property name="mytext" column="value" type="text" access="field" not-null="true"/>
+ </joined-subclass>
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+
+import org.splat.dal.dao.kernel.Database;
+
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+
+public abstract class TextAttribute extends Attribute {
+
+ //private Text mytext;
+ private String mytext;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor.
+ protected TextAttribute () {
+ }
+
+// Initialization constructor
+ protected TextAttribute (Any from, String value) {
+// ----------------------------------------------
+ super(from);
+ mytext = value;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public String getValue () {
+// -------------------------
+ return mytext;
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ protected void setValue (String value) {
+// --------------------------------------
+ mytext = value;
+ if (this.isSaved()) Database.getSession().update(this);
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the User class and its corresponding Role definition.
+ - User and Role are associated by a one-to-one association on the username User foreign key.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- Class User
+ -->
+ <union-subclass name="org.splat.dal.bo.kernel.User" extends="org.splat.dal.bo.kernel.Persistent" table="user" lazy="false">
+<!-- <natural-id>-->
+ <property name="username" column="username" access="field" />
+ <many-to-one name="role" column="username" insert="false" update="false" unique="true" cascade="save-update" access="field" />
+ <property name="email" column="email" access="field" />
+<!-- </natural-id>-->
+ <property name="password" column="password" access="field" />
+ <property name="first" column="first" access="field" not-null="true" />
+ <property name="last" column="last" access="field" not-null="true" />
+ <property name="display" column="display" access="field" />
+ <property name="organid" column="organid" access="field" />
+ </union-subclass>
+
+<!-- Class Role
+ -->
+ <class name="org.splat.dal.bo.kernel.Role" table="role" lazy="false">
+ <id name="username" column="username" access="field">
+ <generator class="assigned"/>
+ </id>
+ <property name="role" column="role" access="field" not-null="true" />
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.kernel;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.security.Principal;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.Name;
+
+
+public class User extends Persistent implements Principal, Name {
+
+// Persistent fields
+ @SuppressWarnings("unused")
+ private String password; // Property without getter function
+
+ private String username; // Unique in the user directory
+ private String first;
+ private String last;
+ private String display; // Optional
+ private Role role; // Roles as list (as stored into the database)
+ private String email;
+ private String organid;
+
+// Fields initialization class
+ public static class Properties extends Persistent.Properties {
+// ------------------------------------------------------------
+ private String username = null;
+ private String password = null;;
+ private String first = null;
+ private String last = null;
+ private String display = null;
+ private Role role = null;
+ private String email = null;
+ private String organid = null;
+
+// - Public services
+
+ public void clear () {
+ super.clear();
+ username = null;
+ password = null;;
+ first = null;
+ last = null;
+ display = null;
+ role = null;
+ email = null;
+ organid = null;
+ }
+ public String getOrganizationName () {
+ return organid;
+ }
+ public String getPassword () {
+ return password;
+ }
+ public String getUsername () {
+ return username;
+ }
+// - Property setters
+
+ public Properties addRole (String role) throws InvalidPropertyException
+ {
+ if (role.length() == 0) throw new InvalidPropertyException("role");
+ if (this.role == null) {
+ this.role = new Role(username, role);
+ } else {
+ Role[] curole = this.role.toArray();
+ for (int i=0; i<curole.length; i++) if (curole[i].is(role)) return this;
+ this.role.addRole(role);
+ }
+ return this;
+ }
+ public Properties setDisplayName (String display) throws InvalidPropertyException
+ {
+ if (display.length() == 0) throw new InvalidPropertyException("displayname");
+ this.display = display;
+ return this;
+ }
+ public Properties setFirstName (String first) throws InvalidPropertyException
+ {
+ if (first.length() == 0) throw new InvalidPropertyException("firstname");
+ this.first = first;
+ return this;
+ }
+ public Properties setMailAddress (String address) throws InvalidPropertyException
+ {
+ String[] term = address.split("@"); // Must be of the form x@y
+ if (term.length != 2) throw new InvalidPropertyException("address");
+ term = term[1].split("\\x2E"); // Must be of the form x@y.z
+ if (term.length != 2) throw new InvalidPropertyException("address");
+ this.email = address;
+ return this;
+ }
+ public Properties setName (String last) throws InvalidPropertyException
+ {
+ if (last.length() == 0) throw new InvalidPropertyException("lastname");
+ this.last = last;
+ return this;
+ }
+ public Properties setOrganizationName (String organization) throws InvalidPropertyException
+ {
+ if (organization.length() == 0) throw new InvalidPropertyException("organization");
+ this.organid = organization;
+ return this;
+ }
+ public Properties setPassword (String password) throws InvalidPropertyException
+ {
+ if (password != null) {
+ if (password.length() < 1) throw new InvalidPropertyException("password");
+ this.password = String.valueOf(password.hashCode());
+ }
+ return this;
+ }
+ public Properties setUsername (String username) throws InvalidPropertyException
+ {
+ if (username.length() == 0) throw new InvalidPropertyException("username");
+ this.username = username;
+ return this;
+ }
+// - Global validity check
+
+ public void checkValidity () throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
+ {
+ if (username == null) throw new MissedPropertyException("username");
+ if (first == null) throw new MissedPropertyException("firstname");
+ if (last == null) throw new MissedPropertyException("lastname");
+ if (role == null) throw new MissedPropertyException("role");
+ if (email == null) throw new MissedPropertyException("email");
+//TODO: Check if username exists
+ }
+ }
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected User () {
+// --------------
+ }
+// Anonymous user supposed not to be saved
+ public User (String name) {
+// -------------------------
+ username = null;
+ password = null;
+ first = null;
+ last = null;
+ display = name;
+ role = null;
+ email = null;
+ organid = null;
+ }
+// New user
+ public User (Properties uprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// ------------------------------
+ super(uprop); // Throws one of the above exception if not valid
+ this.username = uprop.username;
+ this.password = uprop.password;
+ this.first = uprop.first;
+ this.last = uprop.last;
+ this.display = uprop.display;
+ this.role = uprop.role;
+ this.email = uprop.email;
+ this.organid = uprop.organid;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean equals (Object item) {
+// -----------------------------------
+ if (item == null) return false;
+ if (item instanceof String) {
+ return this.username.equals((String)item); // Usernames are unique
+ }
+ else if (item instanceof User) {
+ User given = (User)item;
+ if (isSaved()) return (this.getIndex() == given.getIndex());
+ else return (this.username.equals(given.username)); // Usernames are unique
+ } else {
+ return false;
+ }
+ }
+
+ public String getDisplayName () {
+// -------------------------------
+ if (display == null) return last + " " + first;
+ else return display;
+ }
+
+ public String getFirstName () {
+// -----------------------------
+ return first;
+ }
+
+ public String getMailAddress () {
+// -------------------------------
+ return email;
+ }
+
+ public String getName () {
+// ------------------------
+ return last;
+ }
+
+ public String getOrganizationName () {
+// ------------------------------------
+ return organid;
+ }
+
+ public String getRoleNames () {
+// -----------------------------
+ return role.getName();
+ }
+
+ public Role[] getRoles () {
+// -------------------------
+ return role.toArray();
+ }
+
+ public String getUsername () {
+// ----------------------------
+ return username;
+ }
+
+ public String toString () {
+// -------------------------
+ return last + " " + first;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ * Base implementation of actor relations such as Contributor, Reviewer and Approver.
+ * ActorRelation objects are attached to Documents for defining those who HAVE CONTRIBUTED to these documents,
+ * while instances of subclasses of ActorRelation are attached to Studies for setting those who CAN CONTRIBUTE to given document types.</br>
+ * </br>
+ * Depending on the actual relation object, the value of the actor relation has different meaning:
+ * <ul>
+ * <li>The description of ActorRelation objects defines the type of contributions (Contributor, Reviewer, Approver...)</li>
+ * <li>The description of instances of subclasses of ActorRelation defines the type of acting documents</li>
+ * </ul>
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+
+
+public abstract class ActorRelation extends Relation {
+
+ private User refer;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected ActorRelation () {
+ }
+// ActorRelation subclasses constructor
+ protected ActorRelation (Study from, User to) {
+// ---------------------------------------------
+ super(from);
+ this.refer = to;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ @Override
+ public User getTo () {
+// --------------------
+ return refer;
+ }
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (User)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the Attribute concrete subclasses.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- Description attribute
+ -->
+ <subclass name="org.splat.dal.bo.som.DescriptionAttribute" extends="org.splat.dal.bo.kernel.TextAttribute" discriminator-value="description">
+ </subclass>
+
+<!-- Comment attribute
+ -->
+ <subclass name="org.splat.dal.bo.som.CommentAttribute" extends="org.splat.dal.bo.kernel.TextAttribute" discriminator-value="comment">
+ </subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ * Attribute class of type Comment.<br/>
+ * A comment is made of any text up to 65 thousand characters.
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.TextAttribute;
+
+
+public class CommentAttribute extends TextAttribute {
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor.
+ protected CommentAttribute () {
+ }
+/**
+ * Constructs a comment attached to a time stamp.
+ *
+ * @param from the time stamp to which this comment is attached.
+ * @param value the text of this comment
+ */
+ protected CommentAttribute (Timestamp from, String value) {
+// ---------------------------------------------------------
+ super(from, value);
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.User;
+
+
+public class ContributorRelation extends ActorRelation {
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected ContributorRelation () {
+ }
+// Initialization constructor
+ public ContributorRelation (Study from, User to) {
+// --------------------------------------------------
+ super(from, to);
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+
+
+public class ConvertsRelation extends Relation {
+
+// Persistent field
+ private File refer;
+
+// Transient fields
+ private boolean got; // For optimizing getDescription()
+ private String description; // Null if this is not described
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected ConvertsRelation () {
+// -----------------------------
+ got = false;
+ description = null;
+ }
+// Initialization constructors
+ protected ConvertsRelation (Document from, File to) {
+// ---------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.got = true;
+ this.description = null; // Conversion not described
+ }
+ protected ConvertsRelation (Document from, File to, String description) {
+// -----------------------------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.got = true;
+ this.description = description; // May be null
+ if (description != null) this.setAttribute( new DescriptionAttribute(this, description) );
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public String getDescription () {
+// -------------------------------
+ if (!got) {
+ DescriptionAttribute field = (DescriptionAttribute)this.getAttribute(DescriptionAttribute.class);
+ if (field != null) description = field.getValue();
+ got = true; // Don't need to be modified later as set and remove attribute functions are private to this class
+ }
+ return description; // May be null
+ }
+
+ public File getTo () {
+// --------------------
+ return refer;
+ }
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (File)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ * Attribute class of type Description.<br/>
+ * A description is made of any text up to 65 thousand characters.
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.TextAttribute;
+
+
+public class DescriptionAttribute extends TextAttribute {
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor.
+ protected DescriptionAttribute () {
+ }
+/**
+ * Constructs the description of a study or a scenario.
+ *
+ * @param from the study or the scenario to which this description is attached.
+ * @param value the text of this description
+ */
+ public DescriptionAttribute (ProjectElement from, String value) {
+// ------------------------------------------------------------------
+ super(from, value);
+ }
+/**
+ * Constructs the description attached to a version relation.
+ *
+ * @param from the version relation to which this description is attached.
+ * @param value the text of this description
+ */
+ protected DescriptionAttribute (VersionsRelation from, String value) {
+// --------------------------------------------------------------------
+ super(from, value);
+ }
+ /**
+ * Constructs the description attached to a conversion relation.
+ *
+ * @param from the conversion relation to which this description is attached.
+ * @param value the text of this description
+ */
+ protected DescriptionAttribute (ConvertsRelation from, String value) {
+// --------------------------------------------------------------------
+ super(from, value);
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the Document class and its type information implemented by the DocumentType class.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- <class name="org.splat.dal.bo.som.Document" table="document" lazy="false"> -->
+ <union-subclass name="org.splat.dal.bo.som.Document" extends="org.splat.dal.bo.kernel.Entity" table="document" lazy="false">
+<!-- Properties inherited from Entity
+ -->
+ <!-- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
+ <generator class="org.splat.dal.bo.kernel.IDGenerator"/>
+ </id>
+
+ <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Attribute" />
+ </set>
+ <set name="relations" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Relation" />
+ </set>-->
+
+<!-- Document properties
+ -
+ - String did -->
+ <property name="did" column="did" access="field" not-null="true" />
+
+ <!-- DocumentType type -->
+ <many-to-one name="type" column="type" access="field" not-null="true" />
+
+ <!-- File myfile -->
+ <many-to-one name="myfile" column="myfile" unique="true" cascade="all-delete-orphan" access="field" not-null="true" />
+
+ <!-- String name -->
+ <property name="name" column="name" access="field" not-null="true" />
+
+ <!-- ProgressState state -->
+ <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
+
+ <!-- int step -->
+ <property name="step" column="step" access="field" not-null="true" />
+
+ <!-- String version -->
+ <property name="version" column="version" access="field" />
+
+ <!-- int countag -->
+ <property name="countag" column="countag" access="field" not-null="true" />
+
+ <!-- int history -->
+ <property name="history" column="history" access="field" not-null="true" />
+
+ <!-- User author -->
+ <many-to-one name="author" column="author" access="field" not-null="true" />
+
+ <!-- Date lasdate -->
+ <property name="lasdate" column="lasdate" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- Class DocumentType
+ -->
+ <class name="org.splat.dal.bo.som.DocumentType" table="doctype" lazy="false">
+ <id name="rid" column="rid" access="field">
+ <generator class="increment"/>
+ </id>
+ <property name="name" column="name" access="field" not-null="true" />
+ <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
+ <property name="step" column="step" access="field" not-null="true" />
+ <property name="result" column="result" access="field" />
+ <set name="uses" table="docuse" lazy="false" access="field">
+ <key column="owner" />
+ <many-to-many column="rid" class="org.splat.dal.bo.som.DocumentType" />
+ </set>
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.Timestamp.ComparatorByDate;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.NotApplicableException;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.manox.Reader;
+import org.splat.manox.Toolbox;
+import org.splat.service.StudyService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
+import org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming;
+import org.splat.som.Revision;
+import org.splat.som.Step;
+
+public class Document extends Entity {
+
+ // Persistent fields
+ private DocumentType type; // User expendable types
+ private File myfile;
+ private String did;
+ private int step;
+ private ProgressState state;
+ private String name;
+ private String version;
+ private int countag;
+ private int history;
+ private User author;
+ private Date lasdate;
+ private ProjectSettingsService _projectSettingsService;
+ private StudyService _studyService;
+
+ // Transient fields
+ public static String suformat = "00"; // Format of the suffix number of document did and file name
+
+ // ==============================================================================================================================
+ // Construction
+ // ==============================================================================================================================
+
+ // 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
+ private ProjectSettingsService.Step step = null;
+ private ProgressState state = null;
+ private String name = null;
+ protected String format = null;
+ private String version = null;
+ private User author = null;
+ protected Date date = null;
+ private String summary = null; // Only for versioning a document
+ private String path = null; // Only for searching from a given path
+
+ // - Public services
+
+ public void clear() {
+ super.clear();
+ type = null;
+ did = null;
+ owner = null;
+ step = null;
+ state = null;
+ name = null;
+ format = null;
+ version = null;
+ author = null;
+ date = null;
+ summary = null;
+ path = null;
+ }
+
+ public Properties copy() {
+ Properties copy = new Properties();
+ copy.type = this.type;
+ copy.did = this.did;
+ copy.owner = this.owner;
+ copy.step = this.step;
+ copy.state = this.state;
+ copy.name = this.name;
+ copy.format = this.format;
+ copy.version = this.version;
+ copy.author = this.author;
+ copy.date = this.date;
+ copy.summary = this.summary;
+ copy.path = this.path;
+ return copy;
+ }
+
+ // - Protected services
+
+ public User getAuthor() {
+ return author;
+ }
+
+ public String getDescription() {
+ return summary;
+ }
+
+ public String getLocalPath() {
+ return path;
+ }
+
+ public String getReference() {
+ return did;
+ }
+
+ public ProjectSettingsService.Step getStep() {
+ return step;
+ }
+
+ public DocumentType getType() {
+ return type;
+ }
+
+ // - Property setters
+
+ public Properties setAuthor(User user) {
+ this.author = user;
+ return this;
+ }
+
+ public Properties setDate(Date date) {
+ this.date = date;
+ return this;
+ }
+
+ public Properties setDescription(String summary)
+ throws InvalidPropertyException {
+ if (summary.length() == 0)
+ throw new InvalidPropertyException("description");
+ this.summary = summary;
+ return this;
+ }
+
+ public Properties setDocument(Document base) {
+ type = base.type;
+ step = ProjectSettingsServiceImpl.getStep(base.step);
+ name = base.name;
+ format = base.getFormat();
+ state = ProgressState.inWORK; // For incrementing the version number at save time
+ version = base.version;
+ return this;
+ }
+
+ public Properties setExternReference(String ref)
+ throws InvalidPropertyException {
+ if (ref.length() == 0)
+ throw new InvalidPropertyException("reference");
+ if (ref.equals(new Revision().toString()))
+ throw new InvalidPropertyException("reference"); // Internal version number
+ this.version = ref;
+ return this;
+ }
+
+ public Properties setFormat(String format)
+ throws InvalidPropertyException {
+ if (format.length() == 0)
+ throw new InvalidPropertyException("format");
+ this.format = format;
+ return this;
+ }
+
+ // Required only for passing search arguments
+ public Properties setLocalPath(String path)
+ throws InvalidPropertyException {
+ if (path.length() == 0)
+ throw new InvalidPropertyException("path");
+ this.path = path;
+ return this;
+ }
+
+ public Properties setName(String name) throws InvalidPropertyException {
+ if (name.length() == 0)
+ throw new InvalidPropertyException("name");
+ this.name = name;
+ return this;
+ }
+
+ public Properties setOwner(ProjectElement owner) {
+ this.owner = owner;
+ return this;
+ }
+
+ // Required only for passing search arguments
+ public Properties setReference(String did)
+ throws InvalidPropertyException {
+ if (did.length() == 0)
+ throw new InvalidPropertyException("reference");
+ this.did = did;
+ return this;
+ }
+
+ public Properties setState(ProgressState state)
+ throws InvalidPropertyException {
+ if (state == ProgressState.inPROGRESS
+ || state == ProgressState.TEMPLATE)
+ throw new InvalidPropertyException("state"); // Non document states
+ this.state = state;
+ return this;
+ }
+
+ public Properties setStep(ProjectSettingsService.Step step) {
+ this.step = step;
+ return this;
+ }
+
+ public Properties setType(DocumentType type) {
+ this.type = type;
+ return this;
+ }
+
+ // - Global validity check
+
+ public void checkValidity() throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException {
+ if (type == null)
+ throw new MissedPropertyException("type");
+ if (owner == null)
+ throw new MissedPropertyException("owner");
+ if (step == null)
+ throw new MissedPropertyException("step");
+ if (author == null)
+ throw new MissedPropertyException("author");
+ if (format == null)
+ throw new MissedPropertyException("format");
+ if (owner instanceof Study && !step.appliesTo(Study.class))
+ throw new InvalidPropertyException("step");
+ if (!type.isContentInto(step))
+ throw new InvalidPropertyException("step");
+ if (state != null && state != ProgressState.EXTERN) {
+ // inDRAFT, inCHECK or APPROVED + version = imposed version (future use)
+ // inWORK + version = base version incremented at save time (used for versioning)
+ if (version == null)
+ throw new InvalidPropertyException("state");
+ }
+ if (version != null) {
+ if (state == null)
+ state = ProgressState.EXTERN;
+ }
+ }
+ }
+
+ // Database fetch constructor
+ protected Document() {
+ }
+
+ // Internal constructor
+ public Document(Properties dprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException {
+ // -------------------------------------
+ super(dprop); // Throws one of the above exception if not valid
+ myfile = new File(null, dprop.format, dprop.date); // The path is initialized below
+ type = dprop.type;
+ step = dprop.step.getNumber();
+ name = dprop.name;
+ version = dprop.version;
+ author = dprop.author;
+ countag = 0;
+ history = 0;
+ lasdate = myfile.getDate(); // Today if not defined in the properties
+
+ state = dprop.state;
+ if (state == null) {
+ state = ProgressState.inWORK; // Promoted when saving this document
+ version = new Revision().toString();
+ }
+ Study owner = null;
+ if (dprop.owner instanceof Study)
+ owner = (Study) dprop.owner;
+ else
+ owner = ((Scenario) dprop.owner).getOwnerStudy();
+
+ ProjectSettingsService.Step step = ProjectSettingsServiceImpl
+ .getStep(this.step);
+ SimpleDateFormat tostring = new SimpleDateFormat("yyyy");
+ String year = tostring.format(owner.getDate());
+ if (name == null) { // Newed document
+ this.name = "%n"; // Named later at publication
+ this.history = -1; // Marks the document as undefined for future assignment
+ }
+ String filename = generateEncodedName(owner);
+ String path;
+
+ path = owner.getReference();
+ did = new StringBuffer(path).append(".%").append(suformat).toString(); // Document reference
+ path = new StringBuffer(year).append("/").append(path).append("/")
+ .append(step.getPath()) // File path relative to the repository vault
+ .append(filename).append(".").append(myfile.getFormat()) // File name and extension
+ .toString();
+ myfile.changePath(path);
+ }
+
+ // ==============================================================================================================================
+ // Public member functions
+ // ==============================================================================================================================
+
+ public File getAttachedFile(String format) {
+ // -------------------------------------------
+ List<Relation> exports = getRelations(ConvertsRelation.class);
+
+ for (Iterator<Relation> i = exports.iterator(); i.hasNext();) {
+ File export = (File) i.next().getTo();
+ if (export.getFormat().equals(format))
+ return export;
+ }
+ return null;
+ }
+
+ public User getAuthor() {
+ // ------------------------
+ return author;
+ }
+
+ public Date getCreationDate() {
+ // ------------------------------
+ return myfile.getDate();
+ }
+
+ public Date getLastModificationDate() {
+ // --------------------------------------
+ return lasdate;
+ }
+
+ public String getFormat() {
+ // --------------------------
+ return myfile.getFormat();
+ }
+
+ public Document getPreviousVersion() {
+ // -------------------------------------
+ Relation previous = getFirstRelation(VersionsRelation.class);
+ if (previous != null)
+ return (Document) previous.getTo();
+ else
+ return null;
+ }
+
+ public ProgressState getProgressState() {
+ // ----------------------------------------
+ return state;
+ }
+
+ /**
+ * Returns the path where all physical files attached to this document are saved. This path is relative to the vault of the repository
+ * and include the file name, without extension, common to all physical files attached to this document.
+ *
+ * @return the path of the document
+ */
+ public String getRelativePath() {
+ // --------------------------------
+ String[] table = myfile.getRelativePath().split("\\x2E");
+ StringBuffer path = new StringBuffer(table[0]);
+ for (int i = 1; i < table.length - 1; i++)
+ path.append('.').append(table[i]);
+ return path.toString();
+ }
+
+ /**
+ * Returns the global unique reference of this document lineage. The document reference is common to all versions of the document
+ * (versioning a document does not change its reference). It is made of the owner study reference suffixed by a document identifier
+ * unique in the scope of the study.
+ *
+ * @return the document reference
+ */
+ public String getReference() {
+ // -----------------------------
+ return did;
+ }
+
+ public java.io.File getSaveDirectory() {
+ // ---------------------------------------
+ String mypath = Database.getRepositoryVaultPath()
+ + myfile.getRelativePath();
+ String[] table = mypath.split("/");
+
+ // Cutting the filename
+ StringBuffer path = new StringBuffer(table[0]);
+ for (int i = 1; i < table.length - 1; i++)
+ path = path.append("/").append(table[i]);
+ return new java.io.File(path.append("/").toString());
+ }
+
+ public File getSourceFile() {
+ // ----------------------------
+ return myfile;
+ }
+
+ /**
+ * Returns the stamps such as review and approval attached to this document, if exist. If several stamps exist, they are returned in
+ * ascending order of dates.
+ *
+ * @return the stamps of the document in ascending order of dates, or an empty array if no stamp exist.
+ */
+ public Timestamp[] getStamps() {
+ // -------------------------------
+ Vector<Timestamp> stamps = new Vector<Timestamp>();
+
+ for (Iterator<Relation> i = this.getAllRelations().iterator(); i
+ .hasNext();) {
+ Relation link = i.next();
+ if (link instanceof StampRelation)
+ stamps.add(((StampRelation) link).getTo());
+ }
+ Timestamp[] result = stamps.toArray(new Timestamp[stamps.size()]);
+ ComparatorByDate bydate = new Timestamp.ComparatorByDate();
+
+ Arrays.sort(result, bydate);
+ return result;
+ }
+
+ /**
+ * Returns the title of this document.
+ *
+ * @return the document title, or an empty string is this document is undefined.
+ * @see #isUndefined()
+ */
+ public String getTitle() {
+ // -------------------------
+ if (this.isUndefined())
+ return "";
+ else
+ return name;
+ }
+
+ public DocumentType getType() {
+ // ------------------------------
+ return type;
+ }
+
+ /**
+ * Returns the version number of this document. The version number, when exists, is either of the internal form (m.n.s) usable for
+ * building a Revision object, or any string in case of external document (document with EXTERN state).<br/>
+ * <br/>
+ * Note: document slots have a version number equal to "0.0.0".
+ *
+ * @return the version number of this document, or null if this is EXTERN.
+ * @see #isUndefined()
+ */
+ public String getVersion() {
+ // ---------------------------
+ return version;
+ }
+
+ /**
+ * Returns true if this document is undefined. An undefined document is a meta-document created for reserving the persistent reference
+ * of a new document before saving (or importing) this later into the repository. The working copy of a such document may include this
+ * reference.
+ *
+ * @see #getTitle()
+ * @see #getVersion()
+ * @see #initialize(Properties)
+ */
+ public boolean isUndefined() {
+ // -----------------------------
+ return (history == -1);
+ }
+
+ public boolean isInto(Step container) {
+ // --------------------------------------
+ return (step == container.getNumber());
+ }
+
+ public boolean isPublished() {
+ // -----------------------------
+ return (countag > 0);
+ }
+
+ public boolean isShared() {
+ // --------------------------
+ return (countag + history > 1);
+ }
+
+ public boolean isVersioned() {
+ // -----------------------------
+ return (history > 0);
+ }
+
+ // ==============================================================================================================================
+ // Public services
+ // ==============================================================================================================================
+
+ public static DocumentType createType(DocumentType.Properties tprop)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, RuntimeException {
+ // ---------------------------------------------------------------------
+ // TODO: Check for duplicate definition
+ DocumentType type = new DocumentType(tprop);
+ Session session = Database.getSession();
+ session.save(type);
+
+ return type;
+ }
+
+ public static Properties extractProperties(java.io.File file) {
+ // --------------------------------------------------------------
+ Properties fprop = new Properties();
+ Reader tool = Toolbox.getReader(file);
+ String value;
+ if (tool != null)
+ try {
+ value = tool.extractProperty("title");
+ if (value != null)
+ fprop.setName(value);
+
+ value = tool.extractProperty("reference");
+ if (value != null)
+ fprop.setReference(value);
+ } catch (Exception e) {
+ }
+ return fprop;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<DocumentType> selectAllTypes() {
+ // --------------------------------------------------
+ String query = "from DocumentType";
+
+ List<DocumentType> types = Database.getSession().createQuery(query)
+ .list();
+ for (Iterator<DocumentType> i = types.iterator(); i.hasNext();) {
+ Hibernate.initialize(i.next()); // Supposed fetching document types
+ }
+ return types;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<DocumentType> selectResultTypes() {
+ // -----------------------------------------------------
+ String query = "from DocumentType where result is not null order by result asc";
+
+ return Database.getSession().createQuery(query).list();
+ }
+
+ public static DocumentType selectType(String name) {
+ // ---------------------------------------------------
+ String query = new StringBuffer("from DocumentType where name='")
+ .append(name).append("'").toString();
+
+ return (DocumentType) Database.getSession().createQuery(query)
+ .uniqueResult();
+ }
+
+ public static DocumentType selectType(int index) {
+ // -------------------------------------------------
+ String query = new StringBuffer("from DocumentType where rid='")
+ .append(index).append("'").toString();
+
+ return (DocumentType) Database.getSession().createQuery(query)
+ .uniqueResult();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<DocumentType> selectTypesOf(
+ ProjectSettingsService.Step step) {
+ // --------------------------------------------------------------------------
+ Integer number = step.getNumber();
+ String query = new StringBuffer("from DocumentType")
+ .append(" where step like '%-").append(number).append("-%'")
+ .toString();
+
+ List<DocumentType> types = Database.getSession().createQuery(query)
+ .list();
+ for (Iterator<DocumentType> i = types.iterator(); i.hasNext();) {
+ Hibernate.initialize(i.next()); // For fetching document types
+ }
+ return types;
+ }
+
+ // ==============================================================================================================================
+ // Protected services
+ // ==============================================================================================================================
+
+ protected ConvertsRelation attach(String format) {
+ // -------------------------------------------------
+ return attach(format, null);
+ }
+
+ protected ConvertsRelation attach(String format, String description) {
+ // ---------------------------------------------------------------------
+ String path = this.getRelativePath();
+ File export = new File(path + "." + format);
+ ConvertsRelation attach = new ConvertsRelation(this, export,
+ description);
+ Session session = Database.getSession();
+
+ session.save(export);
+ session.save(attach);
+
+ this.addRelation(attach); // Updates this
+
+ return attach;
+ }
+
+ public boolean buildReferenceFrom(ProjectElement scope, Document lineage) {
+ // -----------------------------------------------------------------------------
+ if (state != ProgressState.inWORK)
+ return false;
+ Study owner = null;
+ Scenario context = null;
+ if (scope instanceof Study)
+ owner = (Study) scope;
+ else {
+ context = ((Scenario) scope);
+ owner = context.getOwnerStudy();
+ }
+ did = lineage.did;
+ if (context != null && (lineage.isVersioned() || owner.shares(lineage))) {
+ version = new Revision(version).setBranch(context.getReference())
+ .toString();
+ }
+ return true;
+ }
+
+ public boolean buildReferenceFrom(Study scope) {
+ // --------------------------------------------------
+ if (state != ProgressState.inWORK && state != ProgressState.EXTERN)
+ return false;
+ DecimalFormat tostring = new DecimalFormat(suformat);
+
+ did = did.replace("%" + suformat,
+ tostring.format(scope.getLastLocalIndex()));
+ return true;
+ }
+
+ public boolean demote() {
+ // ---------------------------
+ ValidationStep torem;
+
+ if (state == ProgressState.inCHECK) {
+ state = ProgressState.inDRAFT;
+ torem = ValidationStep.REVIEW;
+ // This operation must not change the version number of documents.
+ // Consequently, inDRAFT documents may have a minor version number equal to zero.
+ } else if (state == ProgressState.inDRAFT) {
+ state = ProgressState.inWORK;
+ torem = ValidationStep.PROMOTION;
+ } else {
+ return false;
+ }
+ for (Iterator<Relation> i = this.getAllRelations().iterator(); i
+ .hasNext();) {
+ Relation link = i.next();
+ if (!(link instanceof StampRelation))
+ continue;
+ if (((StampRelation) link).getStampType() != torem)
+ continue;
+ i.remove();
+ break;
+ }
+ Database.getSession().update(this);
+ return true;
+ }
+
+ /**
+ * Increments the reference count of this document following its publication into a Study step.
+ *
+ * @see #release()
+ */
+ public void hold() {
+ // ----------------------
+ countag += 1;
+ if (this.isSaved())
+ Database.getSession().update(this);
+ }
+
+ /**
+ * Defines this document.
+ *
+ * @param dprop
+ * the properties of the document
+ *
+ * @see Step#createDocument(Properties)
+ * @see #isUndefined()
+ */
+ public void initialize(Properties dprop) throws MissedPropertyException,
+ InvalidPropertyException, NotApplicableException {
+ // --------------------------------------------
+ if (!this.isUndefined())
+ throw new NotApplicableException(
+ "Cannot initialize an existing Document");
+ if (dprop.name == null)
+ throw new MissedPropertyException("name");
+ if (dprop.name.length() == 0)
+ throw new InvalidPropertyException("name");
+ if (dprop.owner == null)
+ throw new MissedPropertyException("owner");
+ // if (dprop.owner instanceof Study && !ProjectSettings.getStep(step).appliesTo(Study.class)) {
+ // throw new InvalidPropertyException("step");
+ // }
+ name = dprop.name;
+ myfile.changePath(myfile.getRelativePath().replace("%n",
+ getEncodedRootName((Study) dprop.owner)));
+ if (history == -1)
+ history = 0;
+ if (dprop.date == null) {
+ Calendar current = Calendar.getInstance();
+ lasdate = current.getTime(); // Today
+ } else {
+ lasdate = dprop.date;
+ }
+ Database.getSession().update(this);
+ }
+
+ public boolean promote(Timestamp stamp) {
+ // -------------------------------------------
+ ProgressState newstate = null;
+
+ if (state == ProgressState.inWORK) {
+ newstate = ProgressState.inDRAFT; // Promotion to being reviewed
+ } else if (state == ProgressState.inDRAFT) {
+ newstate = ProgressState.inCHECK; // Promotion to approval
+ Revision myvers = new Revision(version);
+ if (myvers.isMinor()) {
+ version = myvers.incrementAs(newstate).toString();
+ // TODO: If my physical file is programatically editable, update its (property) version number
+ // ISSUE: What about attached files such as PDF if exist, should we remove them ?
+ }
+ } else if (state == ProgressState.inCHECK) {
+ newstate = ProgressState.APPROVED;
+ }
+ this.state = newstate;
+ if (stamp != null)
+ this.addRelation(stamp.getContext());
+ Database.getSession().update(this);
+ return true;
+ }
+
+ /**
+ * Decrements the reference count of this document following the removal of a Publication from a Study step.
+ *
+ * @see #hold()
+ */
+ public void release() {
+ // -------------------------
+ countag -= 1;
+ if (this.isSaved())
+ Database.getSession().update(this);
+ }
+
+ protected void rename(String title) throws InvalidPropertyException {
+ // ------------------------------------
+ if (title.length() == 0)
+ throw new InvalidPropertyException("name");
+
+ Calendar current = Calendar.getInstance();
+ this.name = title;
+ this.lasdate = current.getTime(); // Today
+ Database.getSession().update(this);
+ }
+
+ public void updateAs(Revision newvers) {
+ // ------------------------------------------
+ version = newvers.setBranch(version).toString(); // Branch names are propagated by the versionning
+ ProgressState newstate = ProgressState.inCHECK;
+ if (newvers.isMinor())
+ newstate = ProgressState.inWORK;
+ state = null; // Just to tell updateAs(sate) to not increment the version number
+ updateAs(newstate);
+ }
+
+ public void updateAs(ProgressState state) {
+ // ---------------------------------------------
+ Document previous = null;
+
+ // Set of version number
+ if (state == ProgressState.EXTERN) {
+ if (this.state != ProgressState.EXTERN)
+ this.version = null; // Strange use-case...
+ } else {
+ Revision myvers = new Revision(version);
+ if (!myvers.isNull()) { // Versionning context
+ for (Iterator<Relation> i = getAllRelations().iterator(); i
+ .hasNext();) {
+ Relation link = i.next();
+ if (!link.getClass().equals(VersionsRelation.class))
+ continue;
+ previous = (Document) link.getTo(); // Versioned document
+ break;
+ }
+ }
+ if (this.state != null)
+ myvers.incrementAs(state); // Incrementation if the reversion number is not imposed
+ this.version = myvers.toString();
+ }
+ // Update this document and the previous version, if exit
+ Session session = Database.getSession();
+ if (previous != null) {
+ previous.history += 1;
+ session.update(previous);
+ }
+ this.state = state;
+ session.update(this);
+ }
+
+ // protected void upgrade () {
+ // -------------------------
+ // if (this.state != ProgressState.inWORK) return;
+ //
+ // Calendar current = Calendar.getInstance();
+ // for (Iterator<Relation> i=getAllRelations().iterator(); i.hasNext();) {
+ // Relation link = i.next();
+ // if (!link.getClass().equals(UsesRelation.class)) continue;
+ //
+ // Document used = (Document)link.getTo();
+ // if (!used.isVersioned()) continue;
+ // TODO: Update the uses relation
+ // }
+ // this.promote();
+ // this.lasdate = current.getTime(); // Today
+ // Database.getSession().update(this);
+ //
+ // TODO: Promote documents using this one
+ // }
+
+ // ==============================================================================================================================
+ // Private services
+ // ==============================================================================================================================
+
+ private String generateEncodedName(Study scope) {
+ // ------------------------------------------------
+ StringBuffer encoding = new StringBuffer();
+ FileNaming scheme = getProjectSettingsService().getFileNamingScheme();
+ DecimalFormat tostring = new DecimalFormat(suformat);
+
+ int number = getStudyService().generateLocalIndex(scope);
+
+ if (scheme == FileNaming.encoded) {
+ encoding.append(scope.getReference()).append(".")
+ .append(tostring.format(number));
+ } else { // title and (temporarily) asis
+ encoding.append(name).append(".").append(tostring.format(number));
+ }
+ return encoding.toString();
+ }
+
+ private String getEncodedRootName(Study scope) {
+ // -----------------------------------------------
+ FileNaming scheme = getProjectSettingsService().getFileNamingScheme();
+
+ if (scheme == FileNaming.encoded)
+ return scope.getReference();
+ else
+ return name;
+ }
+
+ /**
+ * @return
+ */
+ private ProjectSettingsService getProjectSettingsService() {
+ return _projectSettingsService;
+ }
+
+ public void setProjectSettingsService(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+ /**
+ * @return
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
+
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.List;
+import java.util.Set;
+import java.util.HashSet;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.ProjectSettingsService.Step;
+
+
+public class DocumentType extends Persistent {
+
+// Persistent fields
+ private String name;
+ private ProgressState state;
+ private String step; // List of (dash separated) steps (numbers) containing this type
+ private String result; // Step (number ) having this type as result
+ private Set<DocumentType> uses;
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Fields initialization class
+ public static class Properties extends Persistent.Properties {
+// ------------------------------------------------------------
+ private String name = null;
+ private String step = null;
+ private String result = null;
+ private DocumentType[] uses = null;
+
+// - Public services
+
+ public void clear () {
+ super.clear();
+ name = null;
+ step = null;
+ result = null;
+ uses = null;
+ }
+// - Setters of DocumentType properties
+
+ public Properties setName (String name) throws InvalidPropertyException
+ {
+ if (name.length() == 0) throw new InvalidPropertyException("name");
+ this.name = name;
+ return this;
+ }
+ public Properties setResult (ProjectSettingsService.Step step)
+ {
+ this.result = String.valueOf(step.getNumber());
+ return this;
+ }
+ public Properties setStep (ProjectSettingsService.Step... step)
+ {
+ this.step = "-";
+ for (int i=0; i<step.length; i++) this.step = this.step + String.valueOf(step[i].getNumber()) + "-";
+ return this;
+ }
+ public Properties setUses (DocumentType... type)
+ {
+ this.uses = type;
+ return this;
+ }
+// - Global validity check
+
+ public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
+ {
+ if (name == null) throw new MissedPropertyException("name");
+ if (step == null) throw new MissedPropertyException("path");
+ }
+ }
+// Database fetch constructor
+ protected DocumentType () {
+// -------------------------
+ }
+// Initialization constructor
+ protected DocumentType (Properties dprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// -----------------------------------------
+ super(dprop); // Throws one of the above exception if not valid
+ name = dprop.name;
+ state = ProgressState.inCHECK;
+ step = dprop.step;
+ result = dprop.result; // May be null
+ uses = new HashSet<DocumentType>();
+ if (dprop.uses != null) for (int i=0; i<dprop.uses.length; i++) uses.add(dprop.uses[i]);
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean approve () {
+// -------------------------
+ if (state != ProgressState.inCHECK) return false;
+ this.state = ProgressState.APPROVED; // The type name is supposed being localized
+ Database.getSession().update(this);
+ return true;
+ }
+
+ public boolean equals(Object entity) {
+// ------------------------------------
+ if (entity == null) return false;
+ if (entity instanceof String) {
+ return this.name.equals((String)entity); // Names are unique
+ } else
+ if (entity instanceof DocumentType) {
+ DocumentType object = (DocumentType)entity;
+ int he = object.getIndex();
+ int me = this.getIndex();
+ if (me*he != 0) return (he == me);
+ else return this.getName().equals(object.getName());
+ } else {
+ return false;
+ }
+ }
+
+ public String getName () {
+// ------------------------
+ return name;
+ }
+
+ public Set<DocumentType> getDefaultUses () {
+// -------------------------------------------
+ return uses;
+ }
+
+ public boolean isApproved () {
+// ----------------------------
+ return (state == ProgressState.APPROVED);
+ }
+
+/**
+ * Checks if documents of this type are attached to the given study step, either as result or content.
+ *
+ * @param step the involved study step
+ * @return true if documents of this type are attached to the given step.
+ * @see #isResultOf(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
+ */
+ public boolean isContentInto (ProjectSettingsService.Step step) {
+// --------------------------------------------------------
+ String[] path = this.step.split("-");
+ for (int i=0; i<path.length; i++) {
+ String value = path[i];
+ if (value.length() == 0) continue;
+ if (Integer.valueOf(value) == step.getNumber()) return true;
+ }
+ return false;
+ }
+
+/**
+ * Checks if documents of this type are result of any study step.
+ *
+ * @return true if documents of this type are result of a step.
+ * @see #isStudyResult()
+ * @see #isResultOf(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
+ */
+ public boolean isStepResult () {
+// ------------------------------
+ return (result != null);
+ }
+
+/**
+ * Checks if documents of this type are result of the given study step.
+ *
+ * @param step the involved study step
+ * @return true if documents of this type are result of the given step.
+ * @see #isContentInto(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
+ * @see #isStepResult()
+ * @see #isStudyResult()
+ */
+ public boolean isResultOf (ProjectSettingsService.Step step) {
+// -----------------------------------------------------
+ if (result == null) return false;
+ return (Integer.valueOf(result) == step.getNumber());
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ * Class whose only purpose is to represent the kernel's Entity class for propagating to this package the visibility of relations
+ * and attributes editing functions.
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Set;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.kernel.ObjectProperties;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+
+
+public abstract class Entity extends org.splat.dal.bo.kernel.Entity {
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected Entity () {
+ }
+// Initialization constructor
+ protected Entity (ObjectProperties prop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// ----------------------------------------
+ super(prop);
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ public Relation addRelation (Relation link) {
+// ----------------------------------------------
+ return super.addRelation(link);
+ }
+
+ public Set<Relation> getAllRelations () {
+// ------------------------------------------
+ return super.getAllRelations();
+ }
+
+ public void removeRelation (Class<? extends Relation> type, Persistent to) {
+// -----------------------------------------------------------------------------
+ super.removeRelation(type, to);
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <union-subclass name="org.splat.dal.bo.som.File" extends="org.splat.dal.bo.kernel.Persistent" table="file" lazy="false">
+
+<!-- Properties inherited Persistent
+ -->
+<!-- <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id>-->
+
+<!-- File properties
+ -->
+ <!-- String format -->
+ <property name="format" column="format" access="field" not-null="true" />
+
+ <!-- String path -->
+ <property name="path" column="path" access="field" not-null="true" />
+
+ <!-- String date -->
+ <property name="date" column="date" access="field" not-null="true" />
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ * Class of meta files representing physical files under the control of Study Manager.
+ * Typically, the files represented by this class are source files of Documents and exports in different formats.
+ * The path of such files is relative to the vault of the repository of Study Manager.
+ * When creating a Document, as the source file is produced by the caller which creates the Document, the corresponding
+ * physical file may not exist at instantiation time.
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Calendar;
+import java.util.Date;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.dao.som.Database;
+
+
+public class File extends Persistent {
+
+// Persistent fields
+ protected String format;
+ protected String path;
+ protected Date date;
+
+// Transient fields
+ private java.io.File myfile; // For optimization
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected File () {
+// -----------------
+ this.myfile = null;
+ }
+// Internal constructors
+ protected File (String path) {
+// ----------------------------
+ Calendar current = Calendar.getInstance();
+ String[] table = path.split("\\x2E");
+
+ this.format = table[table.length-1];
+ this.path = path; // The corresponding physical file may not exist yet
+ this.date = current.getTime(); // Today
+ this.myfile = null;
+ }
+ protected File (String path, String format, Date date) {
+// ------------------------------------------------------
+ this.path = path; // The corresponding physical file may not exist yet
+ this.format = format; // The format name may be different from the physical file extension
+ this.date = date;
+ if (date == null) {
+ Calendar current = Calendar.getInstance();
+ this.date = current.getTime(); // Today
+ }
+ this.myfile = null;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+/**
+ * Returns the data file associated to this meta file.
+ *
+ * @return the associated data file. If this meta data is an empty document, the returned file does not exist.
+ */
+ public java.io.File asFile () {
+// -----------------------------
+ if (myfile == null) myfile = new java.io.File(Database.getRepositoryVaultPath() + path);
+ return myfile;
+ }
+
+ public Date getDate () {
+// ----------------------
+ return date;
+ }
+
+ public String getFormat () {
+// --------------------------
+ return format;
+ }
+
+ public String getName () {
+// ------------------------
+ return this.asFile().getName();
+ }
+
+ public String getRelativePath () {
+// --------------------------------
+ return path;
+ }
+
+ public boolean exists () { // Shortcut
+// ------------------------
+ return (this.asFile().exists());
+ }
+
+// ==============================================================================================================================
+// Protected service
+// ==============================================================================================================================
+
+ protected void changePath (String path) {
+// ---------------------------------------
+ this.path = path;
+ this.myfile = null;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <class name="org.splat.dal.bo.som.IDBuilder" table="refid">
+
+ <!-- Integer cycle -->
+ <id name="cycle" column="cycle" access="field">
+ <generator class="assigned"/>
+ </id>
+
+ <!-- Integer base -->
+ <property name="base" column="base" access="field" />
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.splat.dal.dao.som.Database;
+
+
+public class IDBuilder {
+
+ @SuppressWarnings("unused")
+ private int cycle;
+ private int base; // Number of studies created in this cycle
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+ protected IDBuilder () {
+ }
+ public IDBuilder (Date date) {
+// -------------------------------
+ SimpleDateFormat get = new SimpleDateFormat("yyyy");
+ String year = get.format(date);
+ cycle = Integer.valueOf(year);
+ base = 0;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public String buildReference (String pattern, Study study) {
+// -------------------------------------------------------------
+ char[] format = pattern.toCharArray();
+ char[] ref = new char[80]; // Better evaluate the length of the generated string
+ int next = base + 1;
+
+ int count = 0;
+ for (int i=0; i<format.length; i++) {
+
+// Insertion of attribute values
+ if (format[i] == '%') {
+ i += 1;
+
+ if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
+ int n = i;
+ while (format[i] == 'y') {
+ i += 1;
+ if (i == format.length) break;
+ }
+ SimpleDateFormat tostring = new SimpleDateFormat("yyyy");
+ String year = tostring.format(study.getDate());
+ year = year.substring(4-(i-n), 4); // 4-(i-n) must be equal to either 0 or 2
+ for (int j=0; j<year.length(); j++) {
+ ref[count] = year.charAt(j);
+ count += 1;
+ }
+ i -= 1; // Back to the last 'y' character
+ } else
+ if (format[i] == '0') { // Insertion of the index
+ int n = i;
+ while (format[i] == '0') {
+ i += 1;
+ if (i == format.length) break;
+ }
+ DecimalFormat tostring = new DecimalFormat(pattern.substring(n, i));
+ String number = tostring.format(next);
+ for (int j=0; j<number.length(); j++) {
+ ref[count] = number.charAt(j);
+ count += 1;
+ }
+ i -= 1; // Back to the last '0' character
+ }
+// Keep the character
+ } else {
+ ref[count] = format[i];
+ count += 1;
+ }
+ }
+// Incrementation of the number of study
+ base = next;
+ Database.getSession().update(this);
+ return String.copyValueOf(ref, 0, count);
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <union-subclass name="org.splat.dal.bo.som.KnowledgeElement" extends="org.splat.dal.bo.kernel.Persistent" table="knowelm" lazy="false">
+
+<!-- Properties inherited Persistent
+ -->
+<!-- <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id> -->
+
+<!-- KnowledgeElement properties
+ -->
+ <!-- KnowledgeElementType type -->
+ <many-to-one name="type" column="type" access="field" not-null="true" />
+
+ <!-- String title -->
+ <property name="title" column="title" access="field" not-null="true" />
+
+ <!-- String value -->
+ <property name="value" type="text" column="value" access="field" not-null="true" />
+
+ <!-- Scenario owner -->
+ <many-to-one name="owner" column="owner" access="field" not-null="true" />
+
+ <!-- ProgressState state -->
+ <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
+
+ <!-- User author -->
+ <many-to-one name="author" column="author" access="field" not-null="true" />
+
+ <!-- Date date -->
+ <property name="date" column="date" access="field" not-null="true" />
+
+ </union-subclass>
+
+<!-- Class KnowledgeElementType
+ -->
+ <union-subclass name="org.splat.dal.bo.som.KnowledgeElementType" extends="org.splat.dal.bo.kernel.Persistent" table="knowtype" lazy="false">
+<!-- <id name="rid" column="rid" access="field">
+ <generator class="increment"/>
+ </id>-->
+ <property name="name" column="name" access="field" not-null="true" />
+ <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.text.DecimalFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Vector;
+
+import org.hibernate.Session;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+
+
+public class KnowledgeElement extends Persistent {
+
+ private KnowledgeElementType type; // User extendable types
+ private Scenario owner;
+ private ProgressState state;
+ private String title;
+ private String value;
+ private User author;
+ private Date date;
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Fields initialization class
+ public static class Properties extends Persistent.Properties {
+// ------------------------------------------------------------
+ private String kid = null; // Search criterion only
+ private KnowledgeElementType type = null;
+ private Scenario owner = null;
+ private Visibility visibility = null; // Search criterion only
+ private ProgressState state = null;
+ private String title = null;
+ private String value = null;
+ private User author = null;
+ private User actor = null; // Search criterion only
+ private Date date = null;
+ private List<SimulationContext> context = new Vector<SimulationContext>(); // Search criterion only
+
+// - Public services
+
+ public void clear () {
+ super.clear();
+ kid = null;
+ type = null;
+ owner = null;
+ visibility = null;
+ state = null;
+ title = null;
+ value = null;
+ author = null;
+ actor = null;
+ date = null;
+ context = new Vector<SimulationContext>(); // as clear() may generate side effects
+ }
+ public Properties copy () {
+ Properties copy = new Properties();
+ copy.kid = this.kid;
+ copy.type = this.type;
+ copy.owner = this.owner;
+ copy.visibility = this.visibility;
+ copy.state = this.state;
+ copy.title = this.title;
+ copy.value = this.value;
+ copy.author = this.author;
+ copy.actor = this.actor;
+ copy.date = this.date;
+ copy.context = this.context;
+ return copy;
+ }
+// - Protected services
+
+ public User getActor () {
+ return actor;
+ }
+ public User getAuthor () {
+ return author;
+ }
+ public ProgressState getProgressState () {
+ return state;
+ }
+ public String getReference () {
+ return kid;
+ }
+ public List<SimulationContext> getSimulationContexts () {
+ return context;
+ }
+ public String getTitle () {
+ return title;
+ }
+ public KnowledgeElementType getType () {
+ return type;
+ }
+ public Visibility getVisibility () {
+ return visibility;
+ }
+// - Property setters
+
+// For building a search query
+ public Properties setActor (User actor)
+ {
+ this.actor = actor;
+ return this;
+ }
+ public Properties setAuthor (User user)
+ {
+ this.author = user;
+ return this;
+ }
+ public Properties setDate (Date date)
+ {
+ this.date = date;
+ return this;
+ }
+ public Properties setOwnerScenario (Scenario owner)
+ {
+ this.owner = owner;
+ return this;
+ }
+// For building a search query
+ public Properties setReference (String kid) throws InvalidPropertyException
+ {
+ if (kid.length() == 0) throw new InvalidPropertyException("reference");
+ this.kid = kid;
+ return this;
+ }
+// For building a search query
+ public Properties setSimulationContexts (List<SimulationContext> context) {
+ this.context = context;
+ return this;
+ }
+ public Properties setState (ProgressState state) throws InvalidPropertyException
+ {
+ if (state != ProgressState.inWORK && state != ProgressState.inDRAFT && state != ProgressState.inCHECK && state != ProgressState.APPROVED) {
+ throw new InvalidPropertyException("state");
+ }
+ this.state = state;
+ return this;
+ }
+ public Properties setTitle (String title) throws InvalidPropertyException
+ {
+ if (title.length() == 0) throw new InvalidPropertyException("title");
+ this.title = title;
+ return this;
+ }
+ public Properties setType (KnowledgeElementType type)
+ {
+ this.type = type;
+ return this;
+ }
+ public Properties setValue (String value) throws InvalidPropertyException
+ {
+ if (value.length() == 0) throw new InvalidPropertyException("value");
+ this.value = value;
+ return this;
+ }
+// For building a search query
+ public Properties setVisibility (Visibility area)
+ {
+ this.visibility = area;
+ return this;
+ }
+// - Global validity check
+
+ public void checkValidity () throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
+ {
+ if (type == null) throw new MissedPropertyException("type");
+ if (owner == null) throw new MissedPropertyException("owner");
+ if (title == null) throw new MissedPropertyException("title");
+ if (value == null) throw new MissedPropertyException("value");
+ if (author == null) throw new MissedPropertyException("author");
+ }
+ }
+// Database fetch constructor
+ protected KnowledgeElement () {
+ }
+// Internal constructor
+ public KnowledgeElement (Properties kprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+ super(kprop); // Throws one of the above exception if not valid
+ type = kprop.type;
+ owner = kprop.owner;
+ title = kprop.title;
+ author = kprop.author;
+
+ date = kprop.date;
+ if (date == null) {
+ Calendar current = Calendar.getInstance();
+ date = current.getTime(); // Today
+ }
+ state = kprop.state;
+ if (state == null) {
+ if (type.isReserved()) state = ProgressState.inWORK;
+ else state = ProgressState.inDRAFT;
+ }
+ value = kprop.value.trim();
+ if (!value.startsWith("<p>")) {
+ StringBuffer text = new StringBuffer("<p>");
+ int index = value.indexOf("<p>");
+ if (index > 0) {
+ value = text.append(value.substring(0, index)).append("</p>").append(value.substring(index)).toString();
+ } else {
+ value = text.append(value).append("</p>").toString();
+ }
+ }
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean equals (KnowledgeElement given) {
+// ----------------------------------------------
+ if (isSaved()) return (this.getIndex() == given.getIndex());
+ if (!this.getType().getName().equals(given.getType().getName())) return false;
+ if (this.getValue().equals(given.getValue())) return true;
+ return false;
+ }
+
+ public User getAuthor () {
+// ------------------------
+ return author;
+ }
+
+ public Date getDate () {
+// ----------------------
+ return date;
+ }
+
+ public Scenario getOwnerScenario () {
+// -----------------------------------
+ return owner;
+ }
+
+ public ProgressState getProgressState () {
+// ----------------------------------------
+ return state;
+ }
+
+ public String getTitle () {
+// -------------------------
+ return title;
+ }
+
+ public String getReference () {
+// -----------------------------
+ DecimalFormat toString = new DecimalFormat("00000"); // Supports 99 999 knowledge elements
+ return "KE" + toString.format(this.getIndex());
+ }
+
+ public KnowledgeElementType getType () {
+// --------------------------------------
+ return type;
+ }
+
+ public String getValue () {
+// -------------------------
+ return value;
+ }
+
+ public Visibility getVisibility () {
+// ----------------------------------
+ return getOwnerScenario().getOwnerStudy().getVisibility();
+ }
+
+ public void update (String description) {
+// ---------------------------------------
+ value = description.trim();
+ if (!value.startsWith("<p>")) {
+ StringBuffer text = new StringBuffer("<p>");
+ int index = value.indexOf("<p>");
+ if (index > 0) {
+ value = text.append(value.substring(0, index)).append("</p>").append(value.substring(index)).toString();
+ } else {
+ value = text.append(value).append("</p>").toString();
+ }
+ }
+ Database.getSession().update(this); // No need to update the Lucene index
+ }
+
+// ==============================================================================================================================
+// Public services
+// ==============================================================================================================================
+
+ public static KnowledgeElementType createType (String name) throws RuntimeException {
+// -----------------------------------------------------------
+//TODO: Check for duplicate definition
+ KnowledgeElementType kelt = new KnowledgeElementType(name);
+ Session session = Database.getSession();
+ session.save(kelt);
+
+ return kelt;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<KnowledgeElementType> selectAllTypes () {
+// ----------------------------------------------------------
+ StringBuffer query = new StringBuffer("from KnowledgeElementType");
+ query = query.append(" order by rid asc");
+ return Database.getSession().createQuery(query.toString()).list();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<KnowledgeElementType> selectTypesWhere (ProgressState state) {
+// -------------------------------------------------------------------------------
+ StringBuffer query = new StringBuffer("from KnowledgeElementType where state='").append(state).append("'");
+ query = query.append(" order by rid asc");
+ return Database.getSession().createQuery(query.toString()).list();
+ }
+
+ public static KnowledgeElementType selectType (String name) {
+// -----------------------------------------------------------
+ StringBuffer query = new StringBuffer("from KnowledgeElementType where name='").append(name).append("'");
+ return (KnowledgeElementType)Database.getSession().createQuery(query.toString()).uniqueResult();
+ }
+
+ public static KnowledgeElementType selectType (int index) {
+// ---------------------------------------------------------
+ StringBuffer query = new StringBuffer("from KnowledgeElementType where rid='").append(index).append("'");
+ return (KnowledgeElementType)Database.getSession().createQuery(query.toString()).uniqueResult();
+ }
+
+ /**
+ * @param aState knowledge element progress state to set
+ */
+ public void setProgressState(ProgressState aState) {
+ state = aState;
+ }
+ /**
+ * @param aTitle a title to set
+ */
+ public void setTitle(String aTitle) {
+ title = aTitle;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.dao.som.Database;
+
+
+public class KnowledgeElementType extends Persistent {
+
+ private String name;
+ private ProgressState state;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected KnowledgeElementType () {
+ }
+// Initialization constructor
+ protected KnowledgeElementType (String name) {
+// --------------------------------------------
+ super();
+ this.name = name;
+ this.state = ProgressState.inCHECK;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean approve () {
+// -------------------------
+ if (state != ProgressState.inCHECK) return false;
+ this.state = ProgressState.APPROVED; // The type name is supposed being localized
+ if (this.isSaved()) Database.getSession().update(this);
+ return true;
+ }
+
+ public boolean equals(Object entity) {
+// ------------------------------------
+ if (entity == null) return false;
+ if (entity instanceof String) {
+ return this.name.equals((String)entity); // Names are unique
+ } else
+ if (entity instanceof KnowledgeElementType) {
+ KnowledgeElementType object = (KnowledgeElementType)entity;
+ int he = object.getIndex();
+ int me = this.getIndex();
+ if (me*he != 0) return (he == me);
+ else return this.getName().equals(object.getName());
+ } else {
+ return false;
+ }
+ }
+
+ public String getName () {
+// ------------------------
+ return name;
+ }
+
+ public boolean isApproved () {
+// ----------------------------
+ return (state == ProgressState.APPROVED);
+ }
+
+ public boolean isReserved () {
+// ----------------------------
+ return (state == ProgressState.inWORK);
+ }
+
+// ==============================================================================================================================
+// Protected service
+// ==============================================================================================================================
+/**
+ * Reserves this type for the management of simulation contexts.
+ * For being able to get the studies in which simulation contexts are used, all study scenarios are indexed through this
+ * knowledge element type, whether they include knowledge elements or not.
+ */
+ public boolean reserve () {
+// ----------------------------
+ if (state != ProgressState.inCHECK) return false;
+ this.state = ProgressState.inWORK;
+ if (this.isSaved()) Database.getSession().update(this);
+ return true;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+public enum ProgressState {
+ inPROGRESS, // Represents inWORK, inDRAFT and inCHECK states for search purpose
+ inWORK, inDRAFT, inCHECK, APPROVED,
+ EXTERN, // Document-specific state representing documents produced outside studies
+ TEMPLATE // Study-specific state qualifying typical reference studies
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of properties common to Study and Scenario
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- <class name="org.splat.dal.bo.som.ProjectElement" abstract="true"> -->
+ <union-subclass name="org.splat.dal.bo.som.ProjectElement" extends="org.splat.dal.bo.kernel.Entity" abstract="true">
+
+<!-- Properties inherited from Entity
+ -->
+ <!-- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
+ <generator class="org.splat.dal.bo.kernel.IDGenerator"/>
+ </id>
+ <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Attribute" />
+ </set>
+ <set name="relations" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Relation" />
+ </set> -->
+
+<!-- ProjectElement properties common to Study and Scenario
+ -->
+ <property name="title" column="title" access="field" not-null="true" />
+ <property name="credate" column="credate" access="field" not-null="true" />
+ <property name="lasdate" column="lasdate" access="field" not-null="true" />
+ <many-to-one name="manager" column="manager" access="field" not-null="true" />
+ <list name="contex" table="projext" lazy="false" access="field">
+ <key column="owner" />
+ <list-index column="ordex" />
+ <many-to-many column="rid" class="org.splat.dal.bo.som.SimulationContext" />
+ </list>
+ <set name="docums" inverse="true" lazy="false" order-by="`rid` desc" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.som.Publication" />
+ </set>
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+
+import org.apache.log4j.Logger;
+
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.ObjectProperties;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.som.Step;
+
+
+public abstract class ProjectElement extends Entity {
+
+// Persistent fields
+ protected String title;
+ protected User manager;
+ protected Date credate; // Object creation date
+ protected Date lasdate; // Object Last modification date
+ private List<SimulationContext> contex; // Structured by the Step transient class
+ private Set<Publication> docums; // Structured by the Step transient class
+
+// Transient field
+ private Step[] folders;
+
+ /**
+ * Set the folders.
+ * @param folders the folders to set
+ */
+ public void setFolders(Step[] folders) {
+ this.folders = folders;
+ }
+ /**
+ * Get the folders.
+ * @return the folders
+ */
+ public Step[] getFolders() {
+ return folders;
+ }
+
+ protected final static Logger logger = Logger.getLogger(ProjectElement.class);
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected ProjectElement () {
+// ---------------------------
+ folders = null;
+ }
+// Initialization constructor
+ protected ProjectElement (ObjectProperties oprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// -------------------------------------------------
+ super(oprop); // Throws one of the above exception if not valid
+ title = null; // Initialized by subclasses
+ credate = null; // Initialized by subclasses
+ lasdate = null; // Initialized by subclasses
+ docums = new LinkedHashSet<Publication>();
+ contex = new Vector<SimulationContext>();
+
+ folders = null;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public User getAuthor () {
+// ------------------------
+ return manager;
+ }
+
+/**
+ * Returns the creation date of this Project Element.
+ */
+ public Date getDate () {
+// ----------------------
+ return credate;
+ }
+
+ public String getDescription () {
+// -------------------------------
+ String summary = null;
+ DescriptionAttribute field = (DescriptionAttribute)this.getAttribute(DescriptionAttribute.class);
+ if (field != null) summary = field.getValue();
+ return summary; // May be null
+ }
+
+ public Date getLastModificationDate () {
+ return lasdate;
+ }
+
+ public void setLastModificationDate (Date aDate) {
+ lasdate = aDate;
+ }
+
+ /**
+ * Returns the publication into this Project Element of the given document version, if exists.
+ * If exists, a document publication id unique in a given ProjectElement.
+ *
+ * @param doc a document version published into this Project Element
+ * @return the publication of the document version, or null if the given document version is not published into this Project Element
+ */
+ public Publication getPublication (Document doc) {
+// ------------------------------------------------
+ int index = doc.getIndex();
+ for (Iterator<Publication> i=docums.iterator(); i.hasNext(); ) {
+ Publication found = i.next();
+ if (found.value().getIndex() == index) return found; // A document publication is unique in a given ProjectElement
+ }
+ return null;
+ }
+
+ public String getTitle () {
+// -------------------------
+ return title;
+ }
+
+ public void setTitle (String aTitle) {
+ title = aTitle;
+ }
+
+ public boolean publishes (Document doc) {
+// ---------------------------------------
+ int index = doc.getIndex();
+ for (Iterator<Publication> i=docums.iterator(); i.hasNext(); ) {
+ Document found = i.next().value();
+ if (found.getIndex() == index) return true;
+ }
+ return false;
+ }
+
+ public Iterator<Publication> PublicationIterator () {
+// ---------------------------------------------------
+ return Collections.unmodifiableSet(docums).iterator();
+ }
+
+ public Iterator<SimulationContext> SimulationContextIterator () {
+// ---------------------------------------------------------------
+ return Collections.unmodifiableList(contex).iterator();
+ }
+
+// ==============================================================================================================================
+// Protected member functions
+// ==============================================================================================================================
+
+ public boolean add (Publication newdoc) {
+// ------------------------------------------
+ return docums.add(newdoc);
+ }
+
+ public boolean add (SimulationContext newdoc) {
+// ------------------------------------------------
+ return contex.add(newdoc);
+ }
+
+ public boolean remove (Publication oldoc) {
+// --------------------------------------------
+ return docums.remove(oldoc); // The removed tag becoming orphan, it is supposed automatically deleted from the data store
+ }
+
+ public boolean remove (SimulationContext oldoc) {
+// --------------------------------------------------
+ return contex.remove(oldoc);
+ }
+
+/**
+ * Refreshes the internal data potentially out-of-date.
+ * This function needs to be called when Publication objects are added to this Project Element before being saved. The reason is,
+ * as saving a persistent object changes its hashcode, hashed data need to be rebuilt after saving for making functions based
+ * on this hashcode such as remove(), working.
+ */
+ public void refresh () {
+// -------------------------
+ Publication[] curdoc = docums.toArray(new Publication[docums.size()]);
+
+ folders = null; // Just in case
+ docums.clear();
+ for (int i=0; i<curdoc.length; i++) docums.add(curdoc[i]);
+// No need to rebuild the list of SimulationContext as it does not use hashcodes
+ Database.getSession().update(this);
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <union-subclass name="org.splat.dal.bo.som.Publication" extends="org.splat.dal.bo.kernel.Persistent" table="doctag" lazy="false">
+
+<!-- Properties inherited Persistent
+ -->
+<!-- <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id>-->
+
+<!-- Publication properties
+ -->
+ <!-- Document mydoc -->
+ <many-to-one name="mydoc" column="doc" access="field" not-null="true" />
+
+ <!-- ProjectElement owner -->
+ <many-to-one name="owner" column="owner" access="field" not-null="true" />
+
+ <!-- char isnew -->
+ <property name="isnew" column="isnew" access="field" not-null="true" />
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ * Publication objects are the way to reference document versions from a Project Element.
+ * As such, a Document version is added (or published) to a Project Element through a Publication object.
+ * This publication is done by saving the Publication object produced when creating and versioning a Document from a given
+ * Project Element Step (call of the saveAs() function).<br/>
+ * <br/>
+ * A Publication object is homogeneous to a reference to a Document version and belongs to one Project Element, this latter
+ * being either a Study Scenario or a Study itself, depending on the Study Step to which the document is published.<br/>
+ * <br/>
+ * The document version referenced by a Publication object is the Value of the publication.
+ *
+ * @see Document
+ * @see ProjectElement
+ * @see Step
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.NotApplicableException;
+import org.splat.manox.Reader;
+import org.splat.manox.Toolbox;
+import org.splat.som.DocumentRights;
+import org.splat.som.Revision;
+import org.splat.som.Step;
+
+
+public class Publication extends Persistent {
+
+// Persistent fields
+ private Document mydoc;
+ private ProjectElement owner; // Either Study or Scenario, depending on the step involved by the publication
+ private char isnew; // True if this references a document version new for the owner project element
+
+// Transient fields
+ private Step mystep;
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+/**
+ * Get the mystep.
+ * @return the mystep
+ */
+ public Step getStep() {
+ return mystep;
+ }
+ /**
+ * Set the mystep.
+ * @param aStep the mystep to set
+ */
+ public void setStep(Step aStep) {
+ this.mystep = aStep;
+ }
+ // Database fetch constructor
+ public Publication () {
+// ------------------------
+ mystep = null;
+ }
+// Internal constructors
+ public Publication (Document doc, ProjectElement publisher) {
+// --------------------------------------------------------------
+ mydoc = doc;
+ mystep = null;
+ owner = publisher;
+ isnew = 'Y';
+ }
+// ==============================================================================================================================
+// Member functions
+// ==============================================================================================================================
+
+ public Relation addDependency (Publication to) {
+// ----------------------------------------------
+ return this.addDependency(to.value());
+ }
+
+ public Relation addDependency (Document to) {
+// -------------------------------------------
+ if (to == null) return null;
+ else return mydoc.addRelation( new UsesRelation(mydoc, to) );
+ }
+
+/**
+ * Undo the out-date operation.
+ *
+ * @return true if the acceptance succeeds
+ * @see #outdate()
+ * @see DocumentRights#canAccept()
+ */
+ public boolean actualize () {
+// ---------------------------
+ if (!this.isOutdated()) return false;
+ isnew = 'Y';
+ Database.getSession().update(this);
+ return true;
+ }
+
+ public ConvertsRelation attach (String format) {
+// ----------------------------------------------
+ return mydoc.attach(format);
+ }
+
+ public ConvertsRelation attach (String format, String description) {
+// ------------------------------------------------------------------
+ return mydoc.attach(format, description);
+ }
+
+/**
+ * Returns either the Study Scenario or the Study itself to which this publication belongs, depending on the Study Step into
+ * which the referenced document has been published.<br/>
+ * If this publication belongs to a Study, the Project Element returned is the Study returned by getOwnerStudy().
+ *
+ * @return the Study Scenario or the Study to which this publication belongs to
+ * @see #getOwnerStudy()
+ */
+ public ProjectElement getOwner () {
+// ---------------------------------
+ return owner;
+ }
+
+ /**
+ * Set the owner.
+ * @param owner the owner to set
+ */
+ public void setOwner(ProjectElement owner) {
+ this.owner = owner;
+ }
+
+ public Study getOwnerStudy () {
+// -----------------------------
+ if (owner instanceof Study) return (Study)owner;
+ else return ((Scenario)owner).getOwnerStudy();
+ }
+
+/**
+ * Returns the state of this published document.
+ * It is the same than the state of the referenced document, unless this publication is out-of-date, in which case it is
+ * In-Work state.
+ *
+ * @see #outdate()
+ * @see #isOutdated()
+ */
+ public ProgressState getProgressState () {
+// ----------------------------------------
+ if (this.isOutdated()) return ProgressState.inWORK; // Overrides the document state
+ else return mydoc.getProgressState();
+ }
+
+ public List<Publication> getRelations (Class<? extends Relation> type) {
+// ----------------------------------------------------------------------
+ if (type == null) return null;
+
+ List<Publication> result = new ArrayList<Publication>();
+ List<Relation> relist = mydoc.getRelations(type);
+ for (Iterator<Relation> i=relist.iterator(); i.hasNext();) {
+ Relation relation = i.next();
+ Document relatedoc = (Document)relation.getTo();
+ Publication related = owner.getPublication(relatedoc);
+ if (related != null) {
+ result.add(related);
+ } else
+ if (owner instanceof Scenario) { // The relation may cross steps belonging to a scenario and its owner study
+ related = ((Scenario)owner).getOwnerStudy().getPublication(relatedoc);
+ if (related != null) result.add(related);
+ }
+ }
+ return result;
+ }
+
+ public File getSourceFile () {
+// ----------------------------
+ return mydoc.getSourceFile();
+ }
+
+ public boolean isNewForOwner () {
+// -------------------------------
+ return (isnew == 'Y');
+ }
+
+ public boolean isOutdated () {
+// ----------------------------
+ return (isnew == 'O');
+ }
+
+ /**
+ * Get the isnew.
+ * @return the isnew
+ */
+ public char getIsnew() {
+ return isnew;
+ }
+ /**
+ * Set the isnew.
+ * @param isnew the isnew to set
+ */
+ public void setIsnew(char isnew) {
+ this.isnew = isnew;
+ }
+ public void rename (String title) throws InvalidPropertyException {
+// ---------------------------------
+ mydoc.rename(title);
+ }
+
+/**
+ * Out-dates this publication and recursively all publications using this one.
+ * Typically, a publication is out-dated when modifying a document to which it depends.
+ *
+ * @see #isOutdated()
+ * @see #getProgressState()
+ * @see #actualize()
+ */
+ public void outdate () {
+// ----------------------
+ if (this.isOutdated()) return;
+
+ List<Publication> relist = this.getRelations(UsedByRelation.class);
+ for (Iterator<Publication> i = relist.iterator(); i.hasNext(); ) {
+ i.next().outdate();
+ }
+ isnew = 'O';
+ Database.getSession().update(this);
+ }
+
+/**
+ * Returns the document version referenced by this Publication.
+ */
+ public Document value () {
+// ------------------------
+ return mydoc;
+ }
+ /**
+ * Set the mydoc.
+ * @param mydoc the mydoc to set
+ */
+ public void setValue (Document aDoc) {
+ this.mydoc = aDoc;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ - Mapping of the Relation class hierarchy.
+ - The entire hierarchy is mapped to one single table using a String discriminator.
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+<!-- Uses relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.UsesRelation" extends="org.splat.dal.bo.kernel.Relation" table="uses_rel">
+ <many-to-one name="refer" column="refer" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- UsedBy relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.UsedByRelation" extends="org.splat.dal.bo.kernel.Relation" table="usedby_rel">
+ <many-to-one name="refer" column="refer" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- Versions relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.VersionsRelation" extends="org.splat.dal.bo.kernel.Relation" table="versions_rel">
+ <many-to-one name="refer" column="refer" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- Converts relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.ConvertsRelation" extends="org.splat.dal.bo.kernel.Relation" table="converts_rel">
+ <many-to-one name="refer" column="refer" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- Contributor actor relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.ContributorRelation" extends="org.splat.dal.bo.kernel.Relation" table="contributor_rel">
+ <many-to-one name="refer" column="refer" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- ValidationCycle relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.ValidationCycleRelation" extends="org.splat.dal.bo.kernel.Relation" table="cycle_rel">
+<!-- <many-to-one name="refer" column="refer" unique="true" cascade="all-delete-orphan" access="field" not-null="true" />-->
+ <many-to-one name="refer" column="refer" unique="true" access="field" not-null="true" />
+ </union-subclass>
+
+<!-- Stamp relation
+ -->
+ <union-subclass name="org.splat.dal.bo.som.StampRelation" extends="org.splat.dal.bo.kernel.Relation" table="stamp_rel">
+<!-- <many-to-one name="refer" column="refer" unique="true" cascade="all-delete-orphan" access="field" not-null="true" />-->
+ <many-to-one name="refer" column="refer" unique="true" access="field" not-null="true" />
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <union-subclass name="org.splat.dal.bo.som.Scenario" extends="org.splat.dal.bo.som.ProjectElement" table="scenario" lazy="false">
+
+ <!-- Study owner -->
+ <many-to-one name="owner" column="owner" insert="false" update="false" access="field" not-null="true" />
+
+ <!-- int sid -->
+ <property name="sid" column="sid" access="field" not-null="true" />
+
+ <!-- User cuser -->
+ <many-to-one name="cuser" column="cuser" access="field" />
+
+ <!-- Set<KnowledgeElement> kelms -->
+ <set name="kelms" inverse="true" lazy="false" order-by="`type`,`date` asc" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.som.KnowledgeElement" />
+ </set>
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.io.IOException;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Vector;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.service.StepService;
+import org.splat.service.technical.IndexService;
+import org.splat.som.Step;
+
+
+public class Scenario extends ProjectElement {
+
+// Persistent fields
+ private Study owner;
+ private int sid; // Identifier unique in the scope of owner study
+ private User cuser; // User having checked-out the scenario, if done
+ private Set<KnowledgeElement> kelms;
+
+// Transient fields
+ private HashMap<Integer, List<KnowledgeElement>> known;
+ private List<KnowledgeElement> knowl; // Copy of kelms excluding the internal Knowledge Element (ucase below)
+ private KnowledgeElement ucase; // Internal Knowledge Element for accessing to all used simulation contexts
+
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Fields initialization class
+ public static class Properties extends Persistent.Properties {
+// ------------------------------------------------------------
+ private Study owner = null;
+ private Scenario previous = null;
+ private Step base = null;
+ private String title = null;
+ private String summary = null;
+ private User manager = null;
+ private Date date = null;
+
+// - Public services
+
+ public void clear () {
+ super.clear();
+ owner = null;
+ previous = null;
+ base = null;
+ title = null;
+ summary = null;
+ manager = null;
+ date = null;
+ }
+// - Protected services
+
+ public Step getBaseStep () {
+ return base; // May be null
+ }
+ public Scenario getInsertAfter () {
+ return previous; // May be null
+ }
+ public User getManager () {
+ return manager;
+ }
+ public Properties setOwnerStudy (Study owner)
+ {
+ this.owner = owner;
+ return this;
+ }
+// - Setters of Scenario properties
+
+ public Properties setBaseStep (Step base) throws InvalidPropertyException
+ {
+ if (!(base.getOwner() instanceof Scenario)) throw new InvalidPropertyException("step");
+ this.base = base;
+ return this;
+ }
+ public Properties setDate (Date date)
+ {
+ this.date = date;
+ return this;
+ }
+ public Properties setDescription (String summary)
+ {
+ if (summary.length() > 0) this.summary = summary;
+ return this;
+ }
+ public Properties setInsertAfter (Scenario previous)
+ {
+ this.previous = previous;
+ return this;
+ }
+ public Properties setManager (User user)
+ {
+ this.manager = user;
+ return this;
+ }
+ public Properties setTitle (String title) throws InvalidPropertyException
+ {
+ if (title.length() == 0) throw new InvalidPropertyException("title");
+ this.title = title;
+ return this;
+ }
+// - Global validity check
+
+ public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
+ {
+ if (owner == null) throw new MissedPropertyException("owner");
+ if (title == null) throw new MissedPropertyException("title");
+ if (manager == null) throw new MissedPropertyException("manager");
+ }
+ }
+// Database fetch constructor
+ protected Scenario () {
+// ---------------------
+ known = null;
+ knowl = null;
+ ucase = null;
+ }
+// Internal constructor
+ public Scenario (Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// -------------------------------------
+ super(sprop); // Throws one of the above exception if not valid
+ owner = sprop.owner;
+ sid = 0;
+ cuser = null;
+ title = sprop.title; // Inherited attribute
+ known = null;
+ knowl = null; // Initialized when getting all Knowledge Elements
+ ucase = null;
+ kelms = new HashSet<KnowledgeElement>();
+
+ manager = sprop.manager;
+ if (!owner.isStaffedBy(manager)) throw new InvalidPropertyException("manager");
+
+ credate = sprop.date; // Inherited attribute
+ if (credate == null) {
+ Calendar current = Calendar.getInstance();
+ credate = current.getTime(); // Today
+ }
+ lasdate = credate; // Inherited attribute
+
+ if (sprop.summary != null) this.setAttribute( new DescriptionAttribute(this, sprop.summary) );
+
+ Scenario[] scene = owner.getScenarii();
+ for (int i=0; i<scene.length; i++) if (scene[i].sid > this.sid) this.sid = scene[i].sid;
+ sid += 1;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public List<KnowledgeElement> getAllKnowledgeElements () {
+// --------------------------------------------------------
+ if (knowl == null) {
+ knowl = new Vector<KnowledgeElement>(kelms.size());
+ for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext(); ) {
+ KnowledgeElement kelm = i.next();
+ if (kelm.getType().equals("usecase")) ucase = kelm;
+ else knowl.add(kelm);
+ }
+ }
+ return Collections.unmodifiableList(knowl);
+ }
+
+ public KnowledgeElement getKnowledgeElement (int index) {
+// -------------------------------------------------------
+ for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext();) {
+ KnowledgeElement mykelm = i.next();
+ if (mykelm.getIndex() == index) return mykelm;
+ }
+ return null;
+ }
+
+ public List<KnowledgeElement> getKnowledgeElementsOf (KnowledgeElementType type) {
+// --------------------------------------------------------------------------------
+ if (kelms.isEmpty()) return new Vector<KnowledgeElement>(); // Smarter than returning null
+ if (known == null) known = new HashMap<Integer, List<KnowledgeElement>>();
+
+ int numtype = type.getIndex();
+ List<KnowledgeElement> listype = known.get(numtype);
+ if (listype == null) {
+ listype = new Vector<KnowledgeElement>();
+ for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext();) {
+ KnowledgeElement kelm = i.next();
+ if (kelm.getType().getIndex() == numtype) listype.add(kelm);
+ }
+ known.put(numtype, listype);
+ }
+ return listype; // No protection against this object corruption as it would not corrupt the database
+ }
+
+ public Study getOwnerStudy () {
+// -----------------------------
+ return owner;
+ }
+/**
+ * Returns the local reference of this scenario. This reference is unique in the scope of the owner study.
+ */
+ public String getReference () {
+// -----------------------------
+ return String.valueOf(sid);
+ }
+
+ public User getUser () {
+ return cuser; // Null if the scenario has not been checked-out
+ }
+
+ public void setUser (User aUser) {
+ cuser = aUser; // Null if the scenario has not been checked-out
+ }
+
+ public boolean removeKnowledgeElement (KnowledgeElement kelm) {
+// -------------------------------------------------------------
+ KnowledgeElement torem = getKnowledgeElement(kelm.getIndex());
+ if (torem == null) return false;
+ boolean done = kelms.remove(torem);
+ if (done) {
+// Update of my transient data
+ List<KnowledgeElement> kelms = known.get(kelm.getType().getIndex());
+ kelms.remove(torem);
+ if (knowl != null) knowl.remove(torem);
+ Database.getSession().update(this);
+//TODO: If the owner study is not private, remove the knowledge from the Lucene index
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isCheckedout () {
+// ------------------------------
+ return (cuser != null);
+ }
+
+
+
+// ==============================================================================================================================
+// Protected member function
+// ==============================================================================================================================
+
+ public void updateMyIndex (IndexService lucin) throws IOException {
+// ------------------------------------------
+ if (ucase == null) for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext(); ) {
+ KnowledgeElement kelm = i.next();
+ if (!kelm.getType().equals("usecase")) continue;
+ ucase = kelm;
+ break;
+ }
+ lucin.update(ucase);
+ }
+
+// ==============================================================================================================================
+// Private services
+// ==============================================================================================================================
+ /**
+ * @return
+ */
+ public Set<KnowledgeElement> getKnowledgeElements() {
+ return kelms;
+ }
+ /**
+ * @param kelm
+ */
+ public void setUcase(KnowledgeElement kelm) {
+ ucase = kelm;
+ }
+ /**
+ * @return
+ */
+ public List<KnowledgeElement> getKnowledgeElementsList() {
+ return knowl;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <class name="org.splat.dal.bo.som.SimulationContext" table="contelm">
+
+<!-- Properties inherited Persistent
+ -->
+ <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id>
+
+<!-- SimulationContext properties
+ -->
+ <!-- SimulationContextType type -->
+ <many-to-one name="type" column="type" access="field" not-null="true" />
+
+ <!-- int step -->
+ <property name="step" column="step" access="field" not-null="true" />
+
+ <!-- ProgressState state -->
+ <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
+
+ <!-- String value -->
+ <property name="value" column="value" type="text" access="field" not-null="true" />
+
+ <!-- int counter -->
+ <property name="counter" column="counter" access="field" not-null="true" />
+ </class>
+
+<!-- Class SimulationContextType
+ -->
+ <class name="org.splat.dal.bo.som.SimulationContextType" table="contype" lazy="false">
+ <id name="rid" column="rid" access="field">
+ <generator class="increment"/>
+ </id>
+ <property name="name" column="name" access="field" not-null="true" />
+ <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
+ <property name="step" column="step" access="field" not-null="true" />
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.hibernate.Session;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.som.Step;
+
+
+public class SimulationContext extends Persistent implements Serializable {
+
+ private SimulationContextType type; // User extendable types
+ private int step;
+ private ProgressState state;
+ private String value;
+ private int counter;
+
+ private static final long serialVersionUID = 422889133378471949L;
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Fields initialization class
+ public static class Properties extends Persistent.Properties {
+// ------------------------------------------------------------
+ private SimulationContextType type = null;
+ private ProjectSettingsService.Step step = null;
+ private ProgressState state = null;
+ private String value = null;
+
+// - Public services
+
+ public void clear () {
+ super.clear();
+ type = null;
+ step = null;
+ state = null;
+ value = null;
+ }
+ public ProgressState getProgressState () {
+ return state;
+ }
+ public SimulationContextType getType () {
+ return type;
+ }
+ public String getValue () {
+ return value;
+ }
+
+// - Setters of SimulationContext properties
+
+ public Properties setState (ProgressState state) throws InvalidPropertyException
+ {
+ if (state != ProgressState.inCHECK && state != ProgressState.APPROVED) {
+ throw new InvalidPropertyException("state");
+ }
+ this.state = state;
+ return this;
+ }
+ public Properties setStep (ProjectSettingsService.Step step) throws InvalidPropertyException
+ {
+ this.step = step;
+ return this;
+ }
+ public Properties setValue (String value) throws InvalidPropertyException
+ {
+ if (value.length() == 0) throw new InvalidPropertyException("value");
+ this.value = value;
+ return this;
+ }
+ public Properties setType (SimulationContextType type)
+ {
+ this.type = type;
+ return this;
+ }
+// - Global validity check
+
+ public void checkValidity () throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
+ {
+ if (type == null) throw new MissedPropertyException("type");
+ if (step == null) throw new MissedPropertyException("step");
+ if (value == null) throw new MissedPropertyException("value");
+ if (!type.isAttachedTo(step)) throw new InvalidPropertyException("step");
+ }
+ }
+// Database fetch constructor
+ protected SimulationContext () {
+ }
+// Internal constructor
+ public SimulationContext (Properties kprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+ super(kprop); // Throws one of the above exception if not valid
+ type = kprop.type;
+ step = kprop.step.getNumber();
+ value = kprop.value;
+ counter = 0;
+ state = kprop.state;
+ if (state == null) state = ProgressState.inCHECK;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean approve () {
+// -------------------------
+ if (state != ProgressState.inCHECK) return false;
+ this.state = ProgressState.APPROVED; // The type name is supposed being localized
+ Database.getSession().update(this);
+ return true;
+ }
+
+ public boolean equals (SimulationContext given) {
+// -----------------------------------------------
+ if (isSaved()) return (this.getIndex() == given.getIndex());
+ if (!this.getType().getName().equals(given.getType().getName())) return false;
+ if (this.getValue().equals(given.getValue())) return true;
+ return false;
+ }
+
+ public String getValue () {
+// -------------------------
+ return value;
+ }
+
+ public ProgressState getProgressState () {
+// ----------------------------------------
+ return state;
+ }
+
+ public SimulationContextType getType () {
+// ---------------------------------------
+ return type;
+ }
+
+ public boolean isInto (Step container) {
+// --------------------------------------
+ return (step == container.getNumber());
+ }
+
+ public boolean isShared () {
+// --------------------------
+ return (counter > 1);
+ }
+
+// ==============================================================================================================================
+// Public services
+// ==============================================================================================================================
+
+ public static SimulationContextType createType (String name, ProjectSettingsService.Step step) throws InvalidPropertyException, RuntimeException {
+// ---------------------------------------------------------------------------------------
+//TODO: Check for duplicate definition
+ SimulationContextType type = new SimulationContextType(name, step);
+ Session session = Database.getSession();
+ session.save(type);
+
+ return type;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<SimulationContextType> selectAllTypes () {
+// -----------------------------------------------------------
+ StringBuffer query = new StringBuffer("from SimulationContextType"); // Useless to order by names as the result mixes localized and non localized types
+ query = query.append(" order by step asc");
+ return Database.getSession().createQuery(query.toString()).list();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<SimulationContextType> selectTypesOf (ProjectSettingsService.Step... step) {
+// --------------------------------------------------------------------------------------
+ StringBuffer query = new StringBuffer("from SimulationContextType where step='").append(step[0].getNumber()).append("'");
+ for (int i=1; i<step.length; i++) { // Useless to order as the result mixes localized and non localized types
+ query = query.append(" or step='").append(step[i].getNumber()).append("'");
+ }
+ query = query.append(" order by step asc");
+ return Database.getSession().createQuery(query.toString()).list();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<SimulationContextType> selectTypesWhere (SimulationContextType.Properties sprop) {
+// ---------------------------------------------------------------------------------------------------
+ StringBuffer query = new StringBuffer("from SimulationContextType");
+ String separator = " where";
+ ProjectSettingsService.Step step = sprop.getStep();
+ ProgressState state = sprop.getProgressState();
+ String order = " order by step asc";
+
+ if (step != null) {
+ query = query.append(separator).append(" step='").append(step.getNumber()).append("'");
+ separator = " and";
+ order = " order by state desc"; // APPROVED (upper case A) is grater than inCHECK (lower case i)
+ }
+ if (state != null) {
+ query = query.append(separator).append(" state='").append(state.toString()).append("'");
+// separator = " and";
+ if (step != null) {
+ if (state != ProgressState.APPROVED) order = " order by name asc";
+ else order = ""; // Approved types are localized
+ }
+ }
+ query = query.append(order);
+ return Database.getSession().createQuery(query.toString()).list();
+ }
+
+ public static SimulationContextType selectType (String name) {
+// ------------------------------------------------------------
+ StringBuffer query = new StringBuffer("from SimulationContextType where name='").append(name).append("'");
+ return (SimulationContextType)Database.getSession().createQuery(query.toString()).uniqueResult();
+ }
+
+ public static SimulationContextType selectType (int index) {
+// ----------------------------------------------------------
+ StringBuffer query = new StringBuffer("from SimulationContextType where rid='").append(index).append("'");
+ return (SimulationContextType)Database.getSession().createQuery(query.toString()).uniqueResult();
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ public void hold () {
+// ----------------------
+ counter += 1;
+ if (this.isSaved()) Database.getSession().update(this);
+ }
+
+ public void release () {
+// -------------------------
+ counter -= 1;
+ if (this.isSaved()) Database.getSession().update(this);
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.io.Serializable;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.ProjectSettingsService.Step;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
+
+
+public class SimulationContextType extends Persistent implements Serializable {
+
+// Persistent fields
+ private String name;
+ private ProgressState state;
+ private int step;
+
+// Required by the serialization
+ private static final long serialVersionUID = 4819425038576161242L;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Search properties class
+ public static class Properties {
+// ------------------------------
+ private ProgressState state = null;
+ private ProjectSettingsService.Step step = null;
+
+ protected ProgressState getProgressState () {
+ return state;
+ }
+ protected ProjectSettingsService.Step getStep () {
+ return step;
+ }
+ public Properties setState (ProgressState state) {
+ this.state = state;
+ return this;
+ }
+ public Properties setStep (ProjectSettingsService.Step step) {
+ this.step = step;
+ return this;
+ }
+ }
+// Database fetch constructor
+ protected SimulationContextType () {
+ }
+// Initialization constructor
+ protected SimulationContextType (String name, ProjectSettingsService.Step step) throws InvalidPropertyException {
+// ------------------------------------------------------------------------
+ super();
+ this.name = name;
+ this.state = ProgressState.inCHECK;
+ this.step = step.getNumber();
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public boolean approve () {
+// -------------------------
+ if (state != ProgressState.inCHECK) return false;
+ this.state = ProgressState.APPROVED; // The type name is supposed being localized
+ Database.getSession().update(this);
+ return true;
+ }
+
+ public boolean equals(Object entity) {
+// ------------------------------------
+ if (entity == null) return false;
+ if (entity instanceof String) {
+ return this.name.equals((String)entity); // Names are unique
+ } else
+ if (entity instanceof SimulationContextType) {
+ SimulationContextType object = (SimulationContextType)entity;
+ int he = object.getIndex();
+ int me = this.getIndex();
+ if (me*he != 0) return (he == me);
+ else return this.getName().equals(object.getName());
+ } else {
+ return false;
+ }
+ }
+
+ public ProjectSettingsService.Step getAttachedStep () {
+// ----------------------------------------------
+ return ProjectSettingsServiceImpl.getStep(step);
+ }
+
+ public String getName () {
+// ------------------------
+ return name;
+ }
+
+ public boolean isAttachedTo (ProjectSettingsService.Step step) {
+// -------------------------------------------------------
+ if (this.step == step.getNumber()) return true;
+ return false;
+ }
+
+ public boolean isApproved () {
+// ----------------------------
+ return (state == ProgressState.APPROVED);
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+
+
+public class StampRelation extends Relation {
+
+ private Timestamp refer;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected StampRelation () {
+ }
+// Internal constructor
+ protected StampRelation (Document from, Timestamp to) {
+// -----------------------------------------------------
+ super(from);
+ this.refer = to;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Timestamp getTo () {
+// -------------------------
+ return refer;
+ }
+
+ public ValidationStep getStampType () {
+// -------------------------------------
+ return refer.getType();
+ }
+
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (Timestamp)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <typedef name="ProgressState" class="org.splat.dal.bo.kernel.GenericEnumType">
+ <param name="enumClassName">org.splat.dal.bo.som.ProgressState</param>
+ </typedef>
+
+ <typedef name="Visibility" class="org.splat.dal.bo.kernel.GenericEnumType">
+ <param name="enumClassName">org.splat.dal.bo.som.Visibility</param>
+ </typedef>
+
+ <union-subclass name="org.splat.dal.bo.som.Study" extends="org.splat.dal.bo.som.ProjectElement" table="study" lazy="false">
+
+ <!-- String sid -->
+ <property name="sid" column="sid" access="field" not-null="true" />
+
+ <!-- int docount -->
+ <property name="docount" column="docount" access="field" not-null="true" />
+
+ <!-- ProgressState state -->
+ <property name="state" type="ProgressState" column="state" access="field" not-null="true" />
+
+ <!-- Visibility visibility -->
+ <property name="visibility" type="Visibility" column="area" access="field" not-null="true" />
+
+ <!-- List<Scenario> scenarii -->
+ <list name="scenarii" lazy="false" cascade="delete-orphan" access="field">
+ <key column="owner" not-null="true" />
+ <list-index column="scendex"/>
+ <one-to-many class="org.splat.dal.bo.som.Scenario" />
+ </list>
+
+ <!-- String version -->
+ <property name="version" column="version" access="field" not-null="true" />
+
+ <!-- int history -->
+ <property name="history" column="history" access="field" not-null="true" />
+
+ </union-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Set;
+import java.util.Vector;
+
+import org.hibernate.Session;
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.UserDirectory;
+import org.splat.service.StepService;
+import org.splat.service.technical.IndexServiceImpl;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
+import org.splat.service.technical.ProjectSettingsServiceImpl.ProjectSettingsValidationCycle;
+import org.splat.som.Revision;
+
+
+public class Study extends ProjectElement {
+
+// Persistent fields
+ private String sid; // External unique reference in a format conform to the configuration pattern
+ private int docount; // Total number of documents of this study, including versions
+ private ProgressState state;
+ private Visibility visibility;
+ private List<Scenario> scenarii;
+ private String version;
+ private int history; // Number of studies versioning this one, if any
+
+// Transient fields
+ private List<User> contributor; // Shortcut to contributors
+ private HashMap<String,ValidationCycle> validactor; // Shortcut to validation cycles
+ private Set<User> actor; // Summary of above actors
+ private StepService _stepService;
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Fields initialization class
+ public static class Properties extends Persistent.Properties {
+// ------------------------------------------------------------
+ private String sid = null; // Search criterion only
+ private String title = null;
+ private String summary = null;
+ private User manager = null;
+ private User actor = null; // Search criterion only
+ private Visibility visibility = null; // Search criterion only
+ private ProgressState state = null; // Search criterion only
+ private Date date = null;
+ private List<SimulationContext> context = new Vector<SimulationContext>(); // Search criterion only
+
+// - Public services
+
+ public void clear () {
+ super.clear();
+ sid = null;
+ title = null;
+ summary = null;
+ manager = null;
+ actor = null;
+ visibility = null;
+ state = null;
+ date = null;
+ context = new Vector<SimulationContext>(); // as clear() may generate side effects
+ }
+ public Properties copy () {
+ Properties copy = new Properties();
+ copy.sid = this.sid;
+ copy.title = this.title;
+ copy.summary = this.summary;
+ copy.manager = this.manager;
+ copy.actor = this.actor;
+ copy.visibility = this.visibility;
+ copy.state = this.state;
+ copy.date = this.date;
+ copy.context = this.context;
+ return copy;
+ }
+// - Protected services
+
+ public User getActor () {
+ return actor;
+ }
+ public User getManager () {
+ return manager;
+ }
+ public ProgressState getProgressState () {
+ return state;
+ }
+ public String getReference () {
+ return sid;
+ }
+ public List<SimulationContext> getSimulationContexts () {
+ return context;
+ }
+ public String getTitle () {
+ return title;
+ }
+ public String getSummary () {
+ return summary;
+ }
+ public Visibility getVisibility () {
+ return visibility;
+ }
+// - Property setters
+
+// For building a search query
+ public Properties setActor (User actor)
+ {
+ this.actor = actor;
+ return this;
+ }
+ public Properties setDate (Date date)
+ {
+ this.date = date;
+ return this;
+ }
+ public Properties setDescription (String summary)
+ {
+ if (summary.length() > 0) this.summary = summary;
+ return this;
+ }
+ public Properties setManager (User user)
+ {
+ this.manager = user;
+ return this;
+ }
+// For building a search query
+ public Properties setReference (String sid) throws InvalidPropertyException
+ {
+ if (sid.length() == 0) throw new InvalidPropertyException("reference");
+ this.sid = sid;
+ return this;
+ }
+// For building a search query
+ public Properties setSimulationContexts (List<SimulationContext> context) {
+ this.context = context;
+ return this;
+ }
+// For building a search query
+ public Properties setState (ProgressState state)
+ {
+ this.state = state;
+ return this;
+ }
+ public Properties setTitle (String title) throws InvalidPropertyException
+ {
+ if (title.length() == 0) throw new InvalidPropertyException("title");
+ this.title = title;
+ return this;
+ }
+// For building a search query
+ public Properties setVisibility (Visibility area)
+ {
+ this.visibility = area;
+ return this;
+ }
+// - Global validity check
+
+ public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
+ {
+ if (title == null) throw new MissedPropertyException("title");
+ if (manager == null) throw new MissedPropertyException("manager");
+ }
+ }
+// Database fetch constructor
+ protected Study () {
+// ------------------
+ contributor = null;
+ validactor = null;
+ actor = null;
+ }
+// Internal constructor
+ public Study (Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
+// ----------------------------------
+ super(sprop); // Throws one of the above exception if not valid
+ sid = sprop.sid; // Reset after save
+ title = sprop.title; // Inherited attribute
+ manager = sprop.manager;
+ docount = 0;
+ history = 0;
+ scenarii = new LinkedList<Scenario>();
+ visibility = Visibility.PRIVATE;
+ state = ProgressState.inWORK;
+
+ credate = sprop.date; // Inherited attribute
+ if (credate == null) {
+ Calendar current = Calendar.getInstance();
+ credate = current.getTime(); // Today
+ }
+ lasdate = credate; // Inherited attribute
+ version = new Revision().incrementAs(state).toString();
+
+ if (sprop.summary != null) this.setAttribute( new DescriptionAttribute(this, sprop.summary) );
+
+ contributor = null;
+ validactor = null;
+ actor = null;
+ }
+
+ /**
+ * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
+ *
+ * @return the actors of this study
+ * @see #hasActor(User)
+ */
+ public Set<User> getActors () {
+ // -----------------------------
+ if (actor == null) setShortCuts();
+ return Collections.unmodifiableSet(actor);
+ }
+
+ /**
+ * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
+ *
+ * @return the actors of this study
+ * @see #hasActor(User)
+ */
+ public Set<User> getModifiableActors () {
+ // -----------------------------
+ if (actor == null) setShortCuts();
+ return actor;
+ }
+
+ public List<User> getContributors () {
+ // ------------------------------------
+ if (contributor == null) setShortCuts();
+ return Collections.unmodifiableList(contributor); // May be empty
+ }
+
+ public List<User> getModifiableContributors () {
+ if (contributor == null) setShortCuts();
+ return contributor; // May be empty
+ }
+
+ public ProgressState getProgressState () {
+// ----------------------------------------
+ return state;
+ }
+
+/**
+ * Returns the global unique reference of this study.
+ * The study reference is common to all versions of the study (versioning a study does not change its reference).
+ * The form of this study reference is defined in the configuration of the application server - see the SOM XML customization
+ * file.
+ */
+ public String getReference () {
+ return sid;
+ }
+
+ public void setReference (String aReference) {
+ sid = aReference;
+ }
+
+ public Scenario[] getScenarii () {
+// --------------------------------
+ return scenarii.toArray(new Scenario[scenarii.size()]);
+ }
+
+ public List<Scenario> getScenariiList () {
+// --------------------------------
+ return scenarii;
+ }
+
+/**
+ * Returns the validation cycle of the given document type.
+ *
+ * @param doc the document type being subject of validation
+ * @return the validation cycle of the document, or null if not defined.
+ */
+ public ValidationCycle getValidationCycleOf (DocumentType type) {
+// ---------------------------------------------------------------
+ if (validactor == null) setShortCuts();
+ ValidationCycle result = validactor.get(type.getName());
+ if (result == null) {
+ if (type.isStepResult()) result = validactor.get("default"); // "default" validation cycle defined in the configuration, if exist
+ if (result == null) result = validactor.get("built-in");
+ }
+ return result;
+ }
+
+ public String getVersion () {
+// ---------------------------
+ return version;
+ }
+
+ public Visibility getVisibility () {
+// ----------------------------------
+ return visibility;
+ }
+
+/**
+ * Checks if the given user is actor of this study.
+ * Actors include contributors, reviewers and approvers.
+ *
+ * @return true if the given user is actor of this study.
+ * @see #getActors()
+ */
+ public boolean hasActor (User user) {
+// -----------------------------------
+ if (user == null) return false;
+ for (Iterator<User> i=this.getActors().iterator(); i.hasNext(); ) {
+ User involved = i.next();
+ if (involved.equals(user)) return true;
+ }
+ return false;
+ }
+
+/**
+ * Checks whether this study is in the Public or the Reference area of the repository.
+ *
+ * @return true if the study is public.
+ * @see #moveToPublic()
+ * @see #moveToReference()
+ */
+ public boolean isPublic () {
+// --------------------------
+ return (visibility != Visibility.PRIVATE);
+ }
+/**
+ * Checks if the given user participates to this study.
+ * The Study staff includes the author and contributors.
+ *
+ * @return true if the given user is actor of this study.
+ * @see #getContributors()
+ */
+ public boolean isStaffedBy (User user) {
+// --------------------------------------
+ if (user == null) return false;
+ if (manager.equals(user)) return true;
+ for (Iterator<User> i=getContributors().iterator(); i.hasNext();) {
+ if (i.next().equals(user)) return true;
+ }
+ return false;
+ }
+
+ public boolean isVersioned () {
+// -----------------------------
+ return (history > 0);
+ }
+
+ public boolean shares (Document doc) {
+// ------------------------------------
+ Scenario[] scene = this.getScenarii(); // If shared from within the study, the document is shared by the scenarios
+ int counter = 0;
+
+ for (int i=0; i<scene.length; i++) {
+ if (!scene[i].publishes(doc)) continue;
+ if (counter == 1) return true;
+ counter += 1;
+ }
+ return false;
+ }
+
+ public int getLastLocalIndex () {
+// ----------------------------------
+ return docount;
+ }
+
+ public void loadWorkflow () {
+// ------------------------------
+ setShortCuts();
+ }
+
+ public void setShortCuts () {
+// ----------------------------
+ contributor = new Vector<User>();
+ validactor = new HashMap<String,ValidationCycle>();
+ actor = new HashSet<User>();
+
+// Get the contributors
+ for (Iterator<Relation> i=getRelations(ContributorRelation.class).iterator(); i.hasNext(); ) {
+ ContributorRelation link = (ContributorRelation)i.next();
+ contributor.add(link.getTo());
+ }
+// Get the validation cycles specific to this study
+ for (Iterator<Relation> i=getRelations(ValidationCycleRelation.class).iterator(); i.hasNext(); ) {
+ ValidationCycleRelation link = (ValidationCycleRelation)i.next();
+ validactor.put(link.getDocumentType().getName(), link.getTo()); // The associated document type is necessarily not null in this context
+ }
+// Get the validation cycles coming from the configured workflow and not overridden in this study
+ for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i=ProjectSettingsServiceImpl.getAllValidationCycles().iterator(); i.hasNext(); ) {
+ ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i.next();
+ String type = cycle.getName();
+ if (!validactor.containsKey(type)) validactor.put(type, new ValidationCycle(this, cycle));
+ }
+// Get all corresponding actors
+ for (Iterator<ValidationCycle> i=validactor.values().iterator(); i.hasNext(); ) {
+ ValidationCycle cycle = i.next();
+ User[] user = cycle.getAllActors();
+ for (int j=0; j<user.length; j++) actor.add(user[j]);
+ }
+// Get all other actors
+ for (Iterator<Relation> i=this.getAllRelations().iterator(); i.hasNext(); ) {
+ Relation link = i.next();
+ Class<?> kindof = link.getClass().getSuperclass();
+ if (!kindof.equals(ActorRelation.class)) continue;
+ actor.add( ((ActorRelation)link).getTo() );
+ }
+ }
+ /**
+ * @param aVisibility a study visibility to set
+ */
+ public void setVisibility(Visibility aVisibility) {
+ visibility = aVisibility;
+ }
+ /**
+ * @param aState a study progress state to set
+ */
+ public void setProgressState(ProgressState aState) {
+ state = aState;
+ }
+ /**
+ * @param string
+ */
+ public void setVersion(String aVersion) {
+ version = aVersion;
+ }
+ /**
+ * @param i
+ */
+ public void setLastLocalIndex(int anIndex) {
+ docount = anIndex;
+ }
+ /**
+ * @return
+ */
+ public HashMap<String, ValidationCycle> getValidationCycles() {
+ return validactor;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <typedef name="StampType" class="org.splat.dal.bo.kernel.GenericEnumType">
+ <param name="enumClassName">org.splat.dal.bo.som.ValidationStep</param>
+ </typedef>
+
+<!-- <class name="org.splat.dal.bo.som.Timestamp" table="stamp" lazy="false"> -->
+ <union-subclass name="org.splat.dal.bo.som.Timestamp" extends="org.splat.dal.bo.kernel.Any" table="stamp" lazy="false">
+
+<!-- Properties inherited from Any
+ -->
+ <!-- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
+ <generator class="org.splat.dal.bo.kernel.IDGenerator"/>
+ </id>
+ <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
+ <key column="owner" />
+ <one-to-many class="org.splat.dal.bo.kernel.Attribute" />
+ </set> -->
+
+<!-- Timestamp properties
+ -->
+ <!-- StampRelation context -->
+ <one-to-one name="context" property-ref="refer" access="field"/>
+
+ <!-- ValidationCycle.Step mytype -->
+ <property type="StampType" name="mytype" column="type" access="field" not-null="true" />
+
+ <!-- User author -->
+ <many-to-one name="author" column="author" access="field" not-null="true" />
+
+ <!-- Date sdate, including the time section -->
+ <property type="timestamp" name="sdate" column="date" access="field" not-null="true" />
+
+ </union-subclass>
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.Comparator;
+import java.util.Date;
+
+import org.splat.dal.bo.kernel.Any;
+import org.splat.dal.bo.kernel.Attribute;
+import org.splat.dal.bo.kernel.User;
+
+
+public class Timestamp extends Any {
+
+ private StampRelation context;
+ private ValidationStep mytype;
+ private User author;
+ private Date sdate;
+
+ public static class ComparatorByDate implements Comparator<Timestamp> {
+// ---------------------------------------------------------------------
+ public int compare(Timestamp t1, Timestamp t2)
+ {
+ return t1.getDate().compareTo(t2.getDate());
+ }
+ }
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected Timestamp () {
+ }
+// Internal constructors
+ public Timestamp (ValidationStep type, Document from, User to, Date sdate) {
+// -----------------------------------------------------------------------------
+ super((Attribute)null); // For building the collection of attributes
+ this.mytype = type;
+ this.author = to;
+ this.sdate = sdate;
+ this.context = new StampRelation(from, this);
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public User getAuthor () {
+// ------------------------
+ return author;
+ }
+
+ public String getComment () {
+// ---------------------------
+ CommentAttribute field = (CommentAttribute)this.getAttribute(CommentAttribute.class);
+ String result = null;
+ if (field != null) result = field.getValue();
+ return result;
+ }
+
+ public Date getDate () {
+// ----------------------
+ return sdate;
+ }
+
+ public ValidationStep getType () {
+// --------------------------------
+ return mytype;
+ }
+
+ public void setComment (String comment) {
+// ---------------------------------------
+ if (comment != null) this.setAttribute( new CommentAttribute(this, comment) );
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ protected StampRelation getContext () {
+// -------------------------------------
+ return context;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+
+
+public class UsedByRelation extends Relation {
+
+ private Document refer;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected UsedByRelation () {
+ }
+// Initialization constructors
+ protected UsedByRelation (Document from, Document to) {
+// -----------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.reverse = new UsesRelation(this, to, from);
+ }
+// Internal constructor
+ protected UsedByRelation (Relation back, Document from, Document to) {
+// --------------------------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.reverse = back;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Class<? extends Relation> getReverseClass () {
+// ---------------------------------------------------
+ return UsesRelation.class;
+ }
+ public Document getTo () {
+// -------------------------
+ return refer;
+ }
+ public boolean isBidirectional () {
+// ---------------------------------
+ return true;
+ }
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (Document)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+
+
+public class UsesRelation extends Relation {
+
+ private Document refer;
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected UsesRelation () {
+ }
+// Initialization constructors
+ public UsesRelation (Document from, Document to) {
+// ---------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.reverse = new UsedByRelation(this, to, from);
+ }
+// Internal constructor
+ protected UsesRelation (Relation back, Document from, Document to) {
+// ------------------------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.reverse = back;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public Class<? extends Relation> getReverseClass () {
+// ---------------------------------------------------
+ return UsedByRelation.class;
+ }
+
+ public Document getTo () {
+// -------------------------
+ return refer;
+ }
+ public boolean isBidirectional () {
+// ---------------------------------
+ return true;
+ }
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (Document)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
+<!--
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+ -->
+
+<hibernate-mapping>
+
+ <union-subclass name="org.splat.dal.bo.som.ValidationCycle" extends="org.splat.dal.bo.kernel.Persistent" table="cycle" lazy="false">
+
+<!-- Properties inherited Persistent
+ -->
+ <!-- <id name="rid" column="rid" access="field">
+ <generator class="native"/>
+ </id>-->
+
+<!-- ValidationCycle properties
+ -->
+ <!-- ValidationCycleRelation context -->
+ <one-to-one name="context" property-ref="refer" access="field" />
+
+ <!-- DocumentType mytype -->
+ <many-to-one name="mytype" column="type" access="field" not-null="true" />
+
+ <!-- User publisher -->
+ <many-to-one name="publisher" column="publisher" access="field" />
+
+ <!-- User reviewer -->
+ <many-to-one name="reviewer" column="reviewer" access="field" />
+
+ <!-- User approver -->
+ <many-to-one name="approver" column="approver" access="field" />
+
+ <!-- User signatory -->
+ <many-to-one name="signatory" column="signatory" access="field" />
+
+ </union-subclass>
+</hibernate-mapping>
\ No newline at end of file
--- /dev/null
+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
+ * involved in such validations. Once past, each validation step is written down by a time-stamp attached to the validated
+ * document.<br/>
+ * <br/>
+ * The possible validation steps are Promotion, Review, Approval and Acceptance (or Refusal), all being optional,
+ * except Promotion.<br/>
+ * When enabled, Review and Approval involve one given user while Promotion and Acceptance have default actors defined by
+ * the application. The default actors are:
+ * <ul>
+ * <li>Promotion by either the author of the document or the responsible of study</li>
+ * <li>Acceptance by the customer, possibly represented by an internal user</li>
+ * </ul>
+ * Explicit Promotion and Acceptance actors can be defined, for example to force some documents to be published by the
+ * responsible of study only.<br/>
+ * <br/>
+ * Default validation cycles are defined in the configuration workflow, the responsible of studies overriding them when necessary.
+ * They are attached to studies at a given document type.<br/>
+ *
+ * @see Study#addValidationCycle(DocumentType,Properties)
+ * @see Study#getValidationCycleOf(DocumentType)
+ * @see Timestamp
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.util.List;
+import java.util.Vector;
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.UserDirectory;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
+
+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
+
+ public void clear () {
+ super.clear();
+ doctype = null;
+ publisher = null;
+ reviewer = null;
+ approver = null;
+ signatory = null;
+ }
+// - Protected services
+
+ public Properties setDocumentType (DocumentType type)
+ {
+ doctype = type;
+ return this;
+ }
+// - Properties setter
+
+ public Properties setActor (ValidationStep step, 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");
+ }
+ }
+// Database fetch constructor
+ protected ValidationCycle () {
+ }
+// Internal constructors
+ protected ValidationCycle (Study from, ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
+// -----------------------------------------------------------------------------
+ Actor[] actype = cycle.getActorTypes();
+ User.Properties uprop = new User.Properties();
+
+ mytype = Document.selectType(cycle.getName()); // Null in case of default validation cycle
+// context = new ValidationCycleRelation(from, this);
+ context = null; // Validation cycle defined in the workflow
+ for (int i=0; i<actype.length; i++) {
+ User actor = null;
+ if (actype[i] != null)
+ try {
+ if (actype[i] == Actor.manager) {
+ actor = from.getAuthor();
+ } else
+ if (actype[i] == Actor.Nx1) {
+ List<User> manager = UserDirectory.selectUsersWhere(uprop.setOrganizationName("Nx1"));
+ if (manager.size() == 1) actor = manager.get(0);
+ } else
+ if (actype[i] == Actor.Nx2) {
+ List<User> manager = UserDirectory.selectUsersWhere(uprop.setOrganizationName("Nx2"));
+ if (manager.size() == 1) actor = manager.get(0);
+ } else { /* Actor.customer */
+ actor = from.getAuthor();
+//TODO: Get the customer of the study, if exists
+ }
+ } catch (Exception e) { // Should not happen
+ actor = null;
+ }
+ if (i == 0) reviewer = actor;
+ else if (i == 1) approver = actor;
+ else if (i == 2) signatory = actor;
+ }
+ }
+ public ValidationCycle (Study from, 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);
+ }
+
+// ==============================================================================================================================
+// 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 (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);
+ 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 (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 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);
+ if (signatory != null) result.add(signatory);
+ 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
+ }
+
+/**
+ * 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);
+ }
+
+/**
+ * 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()
+ * @see ProjectSettingsServiceImpl#getNewValidationCycle()
+ */
+ public boolean isDefault () {
+// ---------------------------
+ return (mytype == null);
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ public ValidationCycleRelation getContext () {
+// -----------------------------------------------
+ return context;
+ }
+
+ protected void remove (ValidationStep step) {
+// ------------------------------------------
+ if (step == ValidationStep.REVIEW) reviewer = null;
+ else if (step == ValidationStep.APPROVAL) approver = null;
+ else if (step == ValidationStep.ACCEPTANCE || step == ValidationStep.REFUSAL) signatory = null;
+ if (this.isSaved()) Database.getSession().update(this);
+ }
+
+ public void resetActors (Properties vprop) {
+// ---------------------------------------------
+ publisher = vprop.publisher; // May be null
+ reviewer = vprop.reviewer; // May be null
+ approver = vprop.approver; // May be null
+ signatory = vprop.signatory; // May be null
+ if (this.isSaved()) Database.getSession().update(this);
+ }
+
+ protected void setActor (ValidationStep step, 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;
+ if (this.isSaved()) Database.getSession().update(this);
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+
+
+public class ValidationCycleRelation extends Relation {
+
+ private ValidationCycle refer;
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected ValidationCycleRelation () {
+ }
+// Internal constructor
+ protected ValidationCycleRelation (Study from, ValidationCycle to) {
+// ------------------------------------------------------------------
+ super(from);
+ this.refer = to;
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+/**
+ * Returns the document type to which the validation cycle referenced by this relation applies. If the referenced validation cycle
+ * is a default one, the associated document type is not defined.
+ *
+ * @return the document type involved by the referenced validation cycle, or null if this latter is a default one.
+ */
+ public DocumentType getDocumentType () {
+// --------------------------------------
+ return refer.getDocumentType();
+ }
+
+ public ValidationCycle getTo () {
+// -------------------------------
+ return refer;
+ }
+
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (ValidationCycle)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+public enum ValidationStep {
+ PROMOTION, REVIEW, APPROVAL, ACCEPTANCE, // Validation steps subject of time stamp
+ DISTRIBUTION, REFUSAL // Additional Time stamps
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import org.splat.dal.bo.kernel.Persistent;
+import org.splat.dal.bo.kernel.Relation;
+
+
+public class VersionsRelation extends Relation {
+
+// Persistent field
+ private Document refer;
+
+// Transient fields
+ private boolean got; // For optimizing getDescription()
+ private String description; // Null if this is not described
+
+// ==============================================================================================================================
+// Constructors
+// ==============================================================================================================================
+
+// Database fetch constructor
+ protected VersionsRelation () {
+// -----------------------------
+ got = false;
+ description = null;
+ }
+// Initialization constructors
+ public VersionsRelation (Document from, Document to) {
+// -------------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.got = true;
+ this.description = null; // Conversion not described
+ }
+ public VersionsRelation (Document from, Document to, String description) {
+// ---------------------------------------------------------------------------
+ super(from);
+ this.refer = to;
+ this.got = true;
+ this.description = description; // May be null
+ if (description != null) this.setAttribute( new DescriptionAttribute(this, description) );
+ }
+
+// ==============================================================================================================================
+// Public member functions
+// ==============================================================================================================================
+
+ public String getDescription () {
+// -------------------------------
+ if (!got) {
+ DescriptionAttribute field = (DescriptionAttribute)this.getAttribute(DescriptionAttribute.class);
+ if (field != null) description = field.getValue();
+ got = true; // Don't need to be modified later as set and remove attribute functions are private to this class
+ }
+ return description; // May be null
+ }
+
+ public Document getTo () {
+// -------------------------
+ return refer;
+ }
+ protected void setTo (Persistent to) {
+// ------------------------------------
+ refer = (Document)to;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.bo.som;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+public enum Visibility {
+ PRIVATE, // Qualifies studies stored into the private area
+ PUBLIC, // Qualifies studies stored into the public area
+ REFERENCE // Qualifies studies stored into the reference area
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.dao.kernel;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.jdbc.Work;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.apache.log4j.Logger;
+
+
+public abstract class Database implements ApplicationContextAware {
+
+ /**
+ * The ApplicationContext.
+ */
+ private static ApplicationContext _context = null;
+
+ /**
+ * Spring will call this method for initialize the applicationContext.
+ * @param ctx the application context
+ * @throws BeansException the BeanException
+ */
+ public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
+ _context = ctx;
+ }
+
+ /**
+ * Static for getting the context.
+ * @return ApplicationContext the application context
+ */
+ public static ApplicationContext getContext() {
+ return _context;
+ }
+
+// private static String CONFIG_FILE = "/hibernate.cfg.xml";
+ private static SessionFactory mySessionFactory = null;
+
+ protected class CreateTables implements Work {
+// -----------------------------------------------
+ protected Statement request;
+
+ public void execute(Connection connex) throws SQLException
+ {
+ request = connex.createStatement();
+
+// Last identifier of Any objects
+ String create = "CREATE TABLE `any` (" +
+ "`rid` int(10) UNSIGNED NOT NULL," +
+ "`version` tinytext NOT NULL," +
+ "PRIMARY KEY (`rid`)" +
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+// Relation from entities
+ create = "CREATE TABLE `relation` (" +
+ "`rid` int(10) UNSIGNED NOT NULL," +
+ "`name` tinytext NOT NULL," +
+ "`owner` int(10) NOT NULL," +
+ "`refer` int(10) NOT NULL," +
+ "PRIMARY KEY (`rid`)" +
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+// Attribute objects
+ create = "CREATE TABLE `attribute` (" +
+ "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
+ "`type` tinytext NOT NULL," +
+ "`owner` int(10) NOT NULL," +
+ "`value` int(10) NOT NULL," +
+ "PRIMARY KEY (`rid`)" +
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+// Java String objects
+ create = "CREATE TABLE `text` (" +
+ "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
+ "`value` longtext NOT NULL," +
+ "PRIMARY KEY (`rid`)" +
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+// User and role objects
+ create = "CREATE TABLE `user` (" +
+ "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
+ "`username` varchar(32) NOT NULL," +
+ "`password` varchar(32)," +
+ "`first` tinytext NOT NULL," +
+ "`last` tinytext NOT NULL," +
+ "`display` tinytext," +
+ "`email` tinytext," +
+ "`organid` tinytext," +
+ "PRIMARY KEY (`rid`)" +
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ create = "CREATE TABLE `role` (" +
+ "`username` varchar(32) NOT NULL," +
+ "`role` varchar(32) NOT NULL," +
+ "PRIMARY KEY (`username`)" +
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ }
+ }
+
+ protected final static Logger logger = Logger.getLogger(Database.class);
+
+// ==============================================================================================================================
+// Public services
+// ==============================================================================================================================
+
+ public static Session getSession () {
+// -----------------------------------
+ return getInstance().getCurrentSession();
+ }
+
+// ==============================================================================================================================
+// Protected services
+// ==============================================================================================================================
+
+ protected String getSchemaVersion () {
+// ------------------------------------
+ return null;//TODO: Get schema version into specific object/table: getIDPool().getSchemaVersion();
+ }
+
+ protected void setSchemaVersion (String version) {
+// ------------------------------------------------
+//TODO: Set schema version into specific object/table: myIDpool = new IDPool(version);
+// getSession().save(myIDpool);
+ }
+
+// ==============================================================================================================================
+// Private services
+// ==============================================================================================================================
+
+ private static SessionFactory getInstance () {
+// --------------------------------------------
+ if (mySessionFactory == null) {
+// org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration();
+ try {
+ mySessionFactory = getContext().getBean(SessionFactory.class);
+// cfg.configure(); // The configuration file (hibernate.cfg.xml)) is supposed to be on the classpath
+// mySessionFactory = cfg.buildSessionFactory();
+ }
+ catch (Exception error) {
+ logger.fatal("Could not initialize the Hibernate configuration, reason:", error);
+ }
+ }
+ return mySessionFactory;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 08.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.dal.dao.kernel;
+
+import java.io.Serializable;
+
+/**
+ * @author rkv
+ *
+ */
+public interface GenericDAO<T, PK extends Serializable> {
+
+ /** Persist the newInstance object into database */
+ PK create(T newInstance);
+
+ /**
+ * Retrieve an object that was previously persisted to the database using the indicated id as primary key
+ */
+ T read(PK id);
+
+ /** Save changes made to a persistent object. */
+ void update(T transientObject);
+
+ /** Remove an object from persistent storage in the database */
+ void delete(T persistentObject);
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 08.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.dal.dao.kernel;
+
+import java.io.Serializable;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+
+/**
+ * @author rkv
+ *
+ */
+public abstract class GenericDAOImpl<T, PK extends Serializable> implements
+ GenericDAO<T, PK> {
+ private SessionFactory _sessionFactory;
+
+ public PK create(T o) {
+ return (PK) getSession().save(o);
+ }
+
+ public T read(PK id) {
+ return (T) getSession().get(getType(), id);
+ }
+
+ public void update(T o) {
+ getSession().update(o);
+ }
+
+ public void delete(T o) {
+ getSession().delete(o);
+ }
+
+ abstract protected Class<T> getType();
+ /**
+ * @return hibernate session
+ */
+ private Session getSession() {
+ return getSessionFactory().getCurrentSession();
+ }
+
+ /**
+ * Get the sessionFactory.
+ * @return the sessionFactory
+ */
+ public SessionFactory getSessionFactory() {
+ return _sessionFactory;
+ }
+
+ /**
+ * Set the sessionFactory.
+ * @param sessionFactory the sessionFactory to set
+ */
+ public void setSessionFactory(SessionFactory sessionFactory) {
+ _sessionFactory = sessionFactory;
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.splat.dal.dao.som;
+
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.jdbc.Work;
+import org.apache.log4j.Logger;
+
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.IDBuilder;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+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.UserDirectory;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.service.technical.IndexService;
+import org.splat.service.technical.RepositoryService;
+
+public class Database extends org.splat.dal.dao.kernel.Database {
+
+ private int uplevel = 0; // Level of database upgrade
+ private String basepath = null; // Path of the root directory of repository
+ private RepositoryService _repositoryService;
+ private IndexService _indexService;
+ private SessionFactory _sessionFactory;
+
+ private static Database my = null; // Singleton instance
+
+ protected class CreateTables extends
+ org.splat.dal.dao.kernel.Database.CreateTables {
+ // ---------------------------------------------------------------------------
+ public void execute(Connection connex) throws SQLException {
+ super.execute(connex);
+
+ // Study Entity
+ String create = "CREATE TABLE `study` ("
+ + "`rid` int(10) UNSIGNED NOT NULL,"
+ + "`sid` tinytext NOT NULL,"
+ + "`title` tinytext NOT NULL,"
+ + "`state` enum('inWORK','inDRAFT','inCHECK','APPROVED', 'TEMPLATE') NOT NULL default 'inWORK',"
+ + "`area` enum('PRIVATE','PUBLIC','REFERENCE') NOT NULL default 'PRIVATE',"
+ + "`manager` int(10) NOT NULL,"
+ + "`version` tinytext NOT NULL,"
+ + "`docount` int(10) UNSIGNED NOT NULL,"
+ + "`history` int(10) UNSIGNED NOT NULL,"
+ + "`credate` date NOT NULL,"
+ + "`lasdate` date NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // Scenario Entity
+ create = "CREATE TABLE `scenario` ("
+ + "`rid` int(10) UNSIGNED NOT NULL,"
+ + "`sid` int(10) UNSIGNED NOT NULL,"
+ + "`owner` int(10) NOT NULL,"
+ + "`scendex` int(3) NOT NULL,"
+ + "`title` tinytext NOT NULL,"
+ + "`manager` int(10) NOT NULL," + "`cuser` int(10),"
+ + "`credate` date NOT NULL,"
+ + "`lasdate` date NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // Document Entity and document tag (Publication)
+ create = "CREATE TABLE `document` ("
+ + "`rid` int(10) UNSIGNED NOT NULL,"
+ + "`did` tinytext NOT NULL,"
+ + "`type` int(10) NOT NULL,"
+ + "`step` int(10) NOT NULL,"
+ + "`state` enum('inWORK','inDRAFT','inCHECK','APPROVED','EXTERN') NOT NULL default 'inWORK',"
+ + "`name` tinytext NOT NULL,"
+ + "`author` int(10) NOT NULL," + "`version` tinytext,"
+ + "`countag` int(10) UNSIGNED NOT NULL,"
+ + "`history` int(10) NOT NULL,"
+ + "`myfile` int(10) NOT NULL,"
+ + "`lasdate` date NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ create = "CREATE TABLE `doctag` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`doc` int(10) NOT NULL,"
+ + "`owner` int(10) NOT NULL,"
+ + "`isnew` char(1) NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ // Document types
+ create = "CREATE TABLE `doctype` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`name` tinytext NOT NULL,"
+ + "`state` enum('inCHECK','APPROVED') NOT NULL default 'inCHECK',"
+ + "`step` tinytext NOT NULL," + "`result` tinytext,"
+ + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ // Document types dependencies
+ create = "CREATE TABLE `docuse` (" + "`owner` int(10) NOT NULL,"
+ + "`rid` int(10) NOT NULL"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // ValidationCycle related object
+ create = "CREATE TABLE `cycle` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`type` int(10) NOT NULL," + "`publisher` int(10),"
+ + "`reviewer` int(10)," + "`approver` int(10),"
+ + "`signatory` int(10)," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // Timestamp related object
+ create = "CREATE TABLE `stamp` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`type` enum('PROMOTION','REVIEW','APPROVAL','ACCEPTANCE','DISTRIBUTION','REFUSAL') NOT NULL,"
+ + "`author` int(10) NOT NULL,"
+ + "`date` datetime NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // KnowledgeElements objects
+ create = "CREATE TABLE `knowelm` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`type` int(10) NOT NULL,"
+ + "`owner` int(10) NOT NULL,"
+ + "`state` enum('inWORK','inDRAFT','inCHECK','APPROVED') NOT NULL default 'inDRAFT',"
+ + "`title` tinytext NOT NULL,"
+ + "`value` text NOT NULL,"
+ + "`author` int(10) NOT NULL,"
+ + "`date` date NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ // KnowledgeElement types
+ create = "CREATE TABLE `knowtype` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`name` tinytext NOT NULL,"
+ + "`state` enum('inWORK','inCHECK','APPROVED') NOT NULL default 'inCHECK',"
+ + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // SimulationContext objects
+ create = "CREATE TABLE `contelm` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`type` int(10) NOT NULL,"
+ + "`step` int(10) NOT NULL,"
+ + "`state` enum('inCHECK','APPROVED') NOT NULL default 'inCHECK',"
+ + "`value` text NOT NULL,"
+ + "`counter` int(10) UNSIGNED NOT NULL,"
+ + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ // SimulationContext types
+ create = "CREATE TABLE `contype` ("
+ + "`rid` int(10) UNSIGNED NOT NULL auto_increment,"
+ + "`name` tinytext NOT NULL,"
+ + "`state` enum('inCHECK','APPROVED') NOT NULL default 'inCHECK',"
+ + "`step` int(10) NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // Many-to-many association between ProjectElement (Study and Scenario) and SimulationContext
+ create = "CREATE TABLE `projext` (" + "`owner` int(10) NOT NULL,"
+ + "`ordex` int(10) NOT NULL," + "`rid` int(10) NOT NULL"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // File objects
+ create = "CREATE TABLE `file` ("
+ + "`rid` int(10) UNSIGNED NOT NULL,"
+ + "`format` tinytext NOT NULL,"
+ + "`path` tinytext NOT NULL,"
+ + "`date` date NOT NULL," + "PRIMARY KEY (`rid`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+
+ // Reference objects
+ create = "CREATE TABLE `refid` (" + "`cycle` int(10) NOT NULL,"
+ + "`base` int(10) NOT NULL," + "PRIMARY KEY (`cycle`)"
+ + ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
+ request.execute(create);
+ }
+ }
+
+ protected class CheckVersion implements Work {
+ // --------------------------------------------
+ public void execute(Connection connex) throws SQLException {
+ DatabaseMetaData dbmdata = connex.getMetaData();
+ String dbname = connex.getCatalog();
+ ResultSet table;
+
+ table = dbmdata.getTables(dbname, null, "study", null);
+ if (table.next())
+ return;
+ uplevel = -1; // Database not initialized
+ }
+ }
+
+ public final static Logger logger = org.splat.dal.dao.kernel.Database.logger;
+
+ // ==============================================================================================================================
+ // Construction
+ // ==============================================================================================================================
+
+ public Database getMe() {
+ // -------------------------------
+ if (my == null)
+ try {
+ my = this;
+ my.checkVersion();
+ } catch (Exception error) {
+ logger.fatal("Could not access the database, reason:", error);
+ }
+ return my;
+ }
+
+ private Database() {
+ }
+
+ private void checkVersion() {
+ getSessionFactory().getCurrentSession().doWork(new CheckVersion());
+ }
+
+ // ==============================================================================================================================
+ // Public member functions
+ // ==============================================================================================================================
+
+ public boolean isInitialized() {
+ // -------------------------------
+ return (uplevel >= 0);
+ }
+
+ public void initialize() throws IOException, SQLException {
+ // -------------------------
+ logger.info("Creation of the database.");
+
+ // Creation of the Lucene index
+ getIndexService().create(); // May throw IOException if the index repository is improperly configured
+
+ // Creation of the SIMER SQL tables
+ Session session = Database.getSession();
+ session.doWork(new CreateTables()); // May throw SQLException if the SIMER database does not exist
+ session.flush();
+
+ // Population of the database with customized data
+ this.populate();
+
+ session.flush();
+ uplevel = 0; // The database is now up-to-date
+ }
+
+ // ==============================================================================================================================
+ // Protected member functions
+ // ==============================================================================================================================
+
+ public void configure(Properties reprop) throws IOException {
+ // --------------------------------------------
+ basepath = reprop.getProperty("repository");
+ getRepositoryService().setBasepath(basepath);
+ getIndexService().configure();
+ }
+
+ protected void populate() {
+ // --------------------------
+ try {
+ // Initialization of the schema version
+ this.setSchemaVersion("D0.3"); // TODO: Get the version name from the configuration file
+
+ // Creation of the default system administrator
+ // TODO: Get the username password from the Hibernate configuration
+ User.Properties uprop = new User.Properties();
+ uprop.setUsername("simer").setPassword("admin").setName(
+ "Simulation").setFirstName("Manager").setDisplayName(
+ "label.sysadmin").addRole("sysadmin").setMailAddress(
+ "noreply@salome-platform.org");
+ uprop.disableCheck();
+ UserDirectory.createUser(uprop);
+ } catch (Exception e) {
+ // Let's continue, hoping the best...
+ }
+ }
+
+ // ==============================================================================================================================
+ // Public services
+ // ==============================================================================================================================
+
+ public static File getDownloadDirectory(User user) {
+ return my.getRepositoryService().getDownloadDirectory(user);
+ }
+
+ public static String getTemplatePath() {
+ return my.getRepositoryService().getTemplatePath();
+ }
+
+ public static String getRepositoryVaultPath() {
+ return my.getRepositoryService().getRepositoryVaultPath();
+ }
+
+ public static Document selectDocument(int index) {
+ // -------------------------------------------------
+ StringBuffer query = new StringBuffer("from Document where rid='")
+ .append(index).append("'");
+ return (Document) Database.getSession().createQuery(query.toString())
+ .uniqueResult();
+ }
+
+ public static Document selectDocument(String refid, String version) {
+ // --------------------------------------------------------------------
+ StringBuffer query = new StringBuffer("from Document where did='")
+ .append(refid).append("' and version='").append(version)
+ .append("'");
+ return (Document) Database.getSession().createQuery(query.toString())
+ .uniqueResult();
+ }
+
+ public static KnowledgeElement selectKnowledgeElement(int index) {
+ // -----------------------------------------------------------------
+ StringBuffer query = new StringBuffer(
+ "from KnowledgeElement where rid='").append(index).append("'");
+ KnowledgeElement result = (KnowledgeElement) Database.getSession()
+ .createQuery(query.toString()).uniqueResult();
+
+ result.getOwnerScenario().getOwnerStudy().loadWorkflow();
+ return result;
+ }
+
+ public static SimulationContext selectSimulationContext(int index) {
+ // -------------------------------------------------------------------
+ StringBuffer query = new StringBuffer(
+ "from SimulationContext where rid='").append(index).append("'");
+ return (SimulationContext) Database.getSession().createQuery(
+ query.toString()).uniqueResult();
+ }
+
+ public static SimulationContext selectSimulationContext(
+ SimulationContextType celt, String value) {
+ // --------------------------------------------------------------------------------------------------
+ SimulationContext result = null;
+ try {
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ List<SimulationContext> clist = selectSimulationContextsWhere(cprop
+ .setType(celt).setValue(value));
+ if (!clist.isEmpty())
+ result = clist.get(0); // Supposed being the most used one if many exist
+ } catch (InvalidPropertyException error) {
+ logger.info("Attempt to select a simulation context \""
+ + celt.getName() + "\" with an invalid value.");
+ }
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static List<SimulationContext> selectSimulationContextsWhere(
+ SimulationContext.Properties cprop) {
+ // --------------------------------------------------------------------------------------------------------
+ StringBuffer query = new StringBuffer("from SimulationContext");
+ String separator = " where";
+ SimulationContextType celt = cprop.getType();
+ String value = cprop.getValue();
+ ProgressState state = cprop.getProgressState();
+ String order = "";
+
+ if (celt != null) {
+ query = query.append(separator).append(" type='").append(
+ celt.getIndex()).append("'");
+ separator = " and";
+ order = " order by value asc";
+ }
+ if (value != null) {
+ query = query.append(separator).append(" value='").append(value)
+ .append("'");
+ separator = " and";
+ }
+ if (state != null) {
+ query = query.append(separator).append(" state='").append(state)
+ .append("'");
+ if (celt == null)
+ order = " order by type asc";
+ }
+ query.append(order);
+ return (List<SimulationContext>) Database.getSession().createQuery(
+ query.toString()).list();
+ }
+
+ public static Study selectStudy(int index) {
+ // -------------------------------------------
+ StringBuffer query = new StringBuffer("from Study where rid='").append(
+ index).append("'");
+ Study result = (Study) Database.getSession().createQuery(
+ query.toString()).uniqueResult();
+
+ result.loadWorkflow();
+ return result;
+ }
+
+ public static Study selectStudy(String refid) {
+ // ----------------------------------------------
+ StringBuffer query = new StringBuffer("from Study where sid='").append(
+ refid).append("'");
+ Study result = (Study) Database.getSession().createQuery(
+ query.toString()).uniqueResult();
+
+ result.loadWorkflow();
+ return result;
+ }
+
+ protected static IDBuilder selectIDBuilder(int cycle) {
+ // ------------------------------------------------------
+ StringBuffer buffer = new StringBuffer("from IDBuilder where cycle='")
+ .append(cycle).append("'");
+ String qstring = buffer.toString();
+ Query query = Database.getSession().createQuery(qstring);
+ IDBuilder result = (IDBuilder) query.uniqueResult();
+
+ return result;
+ }
+
+ public static IDBuilder selectIDBuilder(Date date) {
+ // ------------------------------------------------------
+ SimpleDateFormat year = new SimpleDateFormat("yyyy");
+ String cycle = year.format(date);
+ StringBuffer buffer = new StringBuffer("from IDBuilder where cycle='")
+ .append(cycle).append("'");
+ String qstring = buffer.toString();
+ Query query = Database.getSession().createQuery(qstring);
+ IDBuilder result = (IDBuilder) query.uniqueResult();
+
+ return result;
+ }
+
+ /**
+ * @return
+ */
+ public IndexService getIndexService() {
+ return _indexService;
+ }
+
+ /**
+ * @return
+ */
+ public RepositoryService getRepositoryService() {
+ return _repositoryService;
+ }
+
+ public void setRepositoryService(RepositoryService repositoryService) {
+ _repositoryService = repositoryService;
+ }
+
+ public void setIndexService(IndexService indexService) {
+ _indexService = indexService;
+ }
+
+ /**
+ * Get the sessionFactory.
+ *
+ * @return the sessionFactory
+ */
+ public SessionFactory getSessionFactory() {
+ return _sessionFactory;
+ }
+
+ /**
+ * Set the sessionFactory.
+ *
+ * @param sessionFactory
+ * the sessionFactory to set
+ */
+ public void setSessionFactory(SessionFactory sessionFactory) {
+ _sessionFactory = sessionFactory;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.dal.dao.som;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.dao.kernel.GenericDAO;
+
+/**
+ * @author RKV
+ *
+ */
+public interface KnowledgeElementDAO extends GenericDAO<KnowledgeElement, Long> {
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.dal.dao.som;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.dao.kernel.GenericDAOImpl;
+
+/**
+ * Knowledge element DAO.
+ * @author RKV
+ *
+ */
+public class KnowledgeElementDAOImpl extends
+ GenericDAOImpl<KnowledgeElement, Long> implements KnowledgeElementDAO {
+
+ /**
+ * {@inheritDoc}
+ * @see org.splat.dal.dao.kernel.GenericDAOImpl#getType()
+ */
+ @Override
+ protected Class<KnowledgeElement> getType() {
+ return KnowledgeElement.class;
+ }
+
+}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the root abstract class supporting dynamic attributes.
- - All objects instance of a subclass of Any are uniquely identified by the rid primary key through the IDGenerator identifier generator class.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.kernel.Any" abstract="true">
-
- <!-- int rid -->
- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
- <generator class="org.splat.kernel.IDGenerator"/>
- </id>
-
-
- <!-- Set<Attribute> attributes -->
- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Attribute" />
- </set>
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Abstract root class of persistent objects supporting dynamic attributes.<br/>
- * Dynamic attributes are instances of concrete subclasses of Attribute that are assigned to Any objects at run time.
- * The attributes of a given Any object must all be of different types.
- *
- * @see Attribute
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.hibernate.Session;
-import org.splat.som.Database;
-
-
-public abstract class Any extends Persistent {
-
- private Set<Attribute> attributes;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor.
- protected Any () {
- }
-// Initialization constructors
- protected Any (ObjectProperties oprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// --------------------------------------
- super(oprop);
- attributes = new HashSet<Attribute>();
- }
- protected Any (Attribute... field) {
-// ----------------------------------
- attributes = new HashSet<Attribute>();
- for (int i=0; i<field.length; i++) {
- if (field[i] == null) continue; // Happen when newing an Any object without property
- if (field[i].getFrom().equals(this)) attributes.add(field[i]);
- }
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Attribute getAttribute (Class<? extends Attribute> type) {
-// ---------------------------------------------------------------
- for (Iterator<Attribute> i=attributes.iterator(); i.hasNext(); ) {
- Attribute field = i.next();
- if (field.getClass().equals(type)) return field;
- }
- return null;
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected boolean removeAttribute (Attribute field) {
-// ---------------------------------------------------
- for (Iterator<Attribute> i=attributes.iterator(); i.hasNext(); ) {
- if (!i.next().equals(field)) continue;
- i.remove();
- if (this.isSaved()) Database.getSession().update(this);
- return true;
- }
- return false;
- }
-
- protected boolean setAttribute (Attribute field) {
-// ------------------------------------------------
- Class<?> type = field.getClass();
- Session session = Database.getSession();
-
- if (!field.getFrom().equals(this)) return false;
- for (Iterator<Attribute> i=attributes.iterator(); i.hasNext(); ) {
- if (!i.next().getClass().equals(type)) continue;
- i.remove();
- break;
- }
- attributes.add(field);
- if (this.isSaved()) {
- if (!field.isSaved()) session.save(field);
- session.update(this);
- } // Else, when saving this, Hibernate will propagate the operation
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the Attribute class hierarchy.
- - The attribute hierarchy is mapped to a single table using a String discriminator.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.kernel.Attribute" abstract="true" table="attribute">
-
- <!-- int rid -->
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
- <discriminator column="type" type="string"/>
-
- <!-- Any owner -->
- <many-to-one name="owner" column="owner" access="field" not-null="true" />
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- *
- * @see Any
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-
-public abstract class Attribute extends Persistent {
-
- protected Any owner;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor.
- protected Attribute () {
- }
-// Initialization constructor
- protected Attribute (Any from) {
-// ------------------------------
- this.owner = from;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Persistent getFrom () {
-// ----------------------------
- return owner;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.jdbc.Work;
-import org.apache.log4j.Logger;
-
-
-public abstract class Database {
-
-// private static String CONFIG_FILE = "/hibernate.cfg.xml";
- private static SessionFactory mySessionFactory = null;
- protected static IDPool myIDpool = null;
-
- protected class CreateTables implements Work {
-// -----------------------------------------------
- protected Statement request;
-
- public void execute(Connection connex) throws SQLException
- {
- request = connex.createStatement();
-
-// Last identifier of Any objects
- String create = "CREATE TABLE `any` (" +
- "`rid` int(10) UNSIGNED NOT NULL," +
- "`version` tinytext NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Relation from entities
- create = "CREATE TABLE `relation` (" +
- "`rid` int(10) UNSIGNED NOT NULL," +
- "`name` tinytext NOT NULL," +
- "`owner` int(10) NOT NULL," +
- "`refer` int(10) NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Attribute objects
- create = "CREATE TABLE `attribute` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`type` tinytext NOT NULL," +
- "`owner` int(10) NOT NULL," +
- "`value` int(10) NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Java String objects
- create = "CREATE TABLE `text` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`value` longtext NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// User and role objects
- create = "CREATE TABLE `user` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`username` varchar(32) NOT NULL," +
- "`password` varchar(32)," +
- "`first` tinytext NOT NULL," +
- "`last` tinytext NOT NULL," +
- "`display` tinytext," +
- "`email` tinytext," +
- "`organid` tinytext," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
- create = "CREATE TABLE `role` (" +
- "`username` varchar(32) NOT NULL," +
- "`role` varchar(32) NOT NULL," +
- "PRIMARY KEY (`username`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
- }
- }
-
- protected final static Logger logger = Logger.getLogger(Database.class);
-
-// ==============================================================================================================================
-// Public services
-// ==============================================================================================================================
-
- public static Session getSession () {
-// -----------------------------------
- return getInstance().getCurrentSession();
- }
-
- public static void close () {
-// ---------------------------
- if (mySessionFactory != null) mySessionFactory.close();
- mySessionFactory = null;
- }
-
- public static IDPool getIDPool () {
-// ---------------------------------
- if (myIDpool == null) myIDpool = new IDPool(getSession());
- return myIDpool;
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected String getSchemaVersion () {
-// ------------------------------------
- return getIDPool().getSchemaVersion();
- }
-
- protected void setIDPoolSize (int size) {
-// ---------------------------------------
- IDPool.setPoolSize(size);
- }
-
- protected void setSchemaVersion (String version) {
-// ------------------------------------------------
- myIDpool = new IDPool(version);
- getSession().save(myIDpool);
- }
-
-// ==============================================================================================================================
-// Private services
-// ==============================================================================================================================
-
- private static SessionFactory getInstance () {
-// --------------------------------------------
- if (mySessionFactory == null) {
- org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration();
- try {
- cfg.configure(); // The configuration file (hibernate.cfg.xml)) is supposed to be on the classpath
- mySessionFactory = cfg.buildSessionFactory();
- }
- catch (Exception error) {
- logger.fatal("Could not initialize the Hibernate configuration, reason:", error);
- }
- }
- return mySessionFactory;
- }
-}
\ No newline at end of file
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
+import org.splat.dal.bo.kernel.User;
public class Do {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the root abstract class supporting relations.
- -
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.kernel.Entity" abstract="true">
-
- <!-- int rid -->
- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
- <generator class="org.splat.kernel.IDGenerator"/>
- </id>
-
-
- <!-- Set<Attribute> attributes -->
- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Attribute" />
- </set>
-
- <!-- Set<Relation> relations -->
- <set name="relations" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Relation" />
- </set>
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Abstract root class of persistent objects supporting relations to other persistent objects.<br/>
- * Relations are instances of concrete subclasses of Relation that are assigned to Entity objects at run time.<br/>
- * <br/>
- * Entity objects also support dynamic attributes provided by the Any class.
- *
- * @see Relation
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.Vector;
-
-import org.hibernate.Session;
-
-
-public abstract class Entity extends Any {
-
- private Set<Relation> relations;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected Entity () {
- }
-// Initialization constructor
- protected Entity (ObjectProperties prop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// ----------------------------------------
- super(prop);
- relations = new HashSet<Relation>();
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Relation getFirstRelation (Class<? extends Relation> type) {
-// -----------------------------------------------------------------
- for (Iterator<Relation> i=relations.iterator(); i.hasNext();) {
- Relation link = i.next();
- if (link.getClass().equals(type)) return link;
- }
- return null;
- }
-
- public List<Relation> getRelations (Class<? extends Relation> type) {
-// -------------------------------------------------------------------
- List<Relation> result = new Vector<Relation>();
-
- for (Iterator<Relation> i=relations.iterator(); i.hasNext();) {
- Relation link = i.next();
- if (link.getClass().equals(type)) result.add(link);
- }
- return result;
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected Set<Relation> getAllRelations () {
-// ------------------------------------------
- return relations;
- }
-
- protected Relation addRelation (Relation link) {
-// ----------------------------------------------
- Session session = Database.getSession();
-
- session.save(link);
- relations.add(link);
- session.update(this);
-
- if (link.isBidirectional()) {
- Entity to = (Entity)link.getTo(); // Bidirectional relation are necessarily between entities
-
- link = link.getReverse();
- session.save(link);
-// if (to.relations == null) to.relations = new HashSet<Relation>();
- to.relations.add(link);
- session.update(to);
- }
- return link;
- }
-
- protected void removeRelation (Class<? extends Relation> type, Persistent to) {
-// -----------------------------------------------------------------------------
- for (Iterator<Relation> i=relations.iterator(); i.hasNext();) {
- Relation link = i.next();
- if (!link.getClass().equals(type)) continue;
- if (!link.getTo().equals(to)) continue;
- i.remove();
- if (this.isSaved()) Database.getSession().update(this);
- return;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.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;
-
-
-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();
- }
-
-
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Class generating the persistent identifier of all objects instance of a subclass of Any.<br/>
- * The implementation of this generator is optimized basing on IDPool.
- *
- * @see IDPool
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.Serializable;
-
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.id.IdentifierGenerator;
-
-
-public class IDGenerator implements IdentifierGenerator {
-
- public Serializable generate (SessionImplementor session, Object any) throws HibernateException {
-// ---------------------------------------------------------------------
- return Database.getIDPool().getNextID();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.kernel.IDPool" table="any">
-
-
- <id name="lastid" column="rid" access="field">
- <generator class="assigned"/>
- </id>
-
- <property name="version" column="version" access="field" not-null="true" />
-
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Optimized generator of persistent identifiers.<br/>
- * This generator minimizes the database hits by grouping a bunch of identifiers in memory and only hitting the database
- * when the in-memory value group is exhausted.
- * Only one IDPool object held by the Database class is created during a session.
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import org.hibernate.Session;
-import org.hibernate.jdbc.Work;
-
-
-public class IDPool {
-
-// Persistent fields
- private Integer lastid; // Last generated ID
- private String version; // Version of the database schema
-
-// Transient fields
- private int remaining; // Remaining available ID held in this pool
- private static int poolsize = 1; // No pool by default
-
- private class LoadNewIDs implements Work {
-// -----------------------------------------
- public void execute(Connection connex) throws SQLException
- {
- Statement request = connex.createStatement();
- ResultSet result = request.executeQuery("SELECT MAX(rid) AS lastid FROM any");
- StringBuffer command = new StringBuffer("UPDATE any SET rid=");
-
- result.first();
- lastid = result.getInt("lastid");
-
- command.append(lastid + poolsize).append(" WHERE rid=").append(lastid);
- request.execute(command.toString());
-
- remaining = poolsize;
- }
- }
- private class LoadLastID implements Work {
-// -----------------------------------------
- public void execute(Connection connex) throws SQLException
- {
- Statement request = connex.createStatement();
- ResultSet result = request.executeQuery("SELECT MAX(rid) AS lastid FROM any");
- StringBuffer command = new StringBuffer("SELECT version FROM any WHERE rid=");
-
- result.first();
- lastid = result.getInt("lastid");
-
- command.append(lastid);
- result = request.executeQuery(command.toString());
- result.first();
- version = result.getString("version");
- remaining = 0;
- }
- }
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
- protected IDPool () {
- }
-/**
- * Constructor called only once, when initializing the database.
- *
- * @param version the version of the constructed database schema.
- */
- protected IDPool (String version) {
-// ---------------------------------
- this.lastid = 0; //TODO: Get the current last ID if a previous version exists
- this.version = version;
- this.remaining = 0;
- }
-/**
- * Constructor called at start of every database session.
- *
- * @param base the started database session
- */
- protected IDPool (Session base) {
-// -------------------------------
- base.doWork( new LoadLastID() );
- }
-
-// ==============================================================================================================================
-// Protected member functions
-// ==============================================================================================================================
-
- protected Integer getNextID () {
-// ------------------------------
- if (remaining <= 0) Database.getSession().doWork( new LoadNewIDs() );
- lastid += 1;
- remaining -= 1;
- return lastid;
- }
-
- protected String getSchemaVersion () {
-// ------------------------------------
- return version;
- }
-
- protected static void setPoolSize (int size) {
-// --------------------------------------------
- if (size > 1) poolsize = size;
- }
-}
\ No newline at end of file
package org.splat.kernel;
+
+import org.splat.dal.bo.kernel.Persistent;
+
/**
* Common interface of intermediate properties objects used for constructing persistent objects supporting the API Design Pattern
* provided by this package.
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the primary key common to all Persistent objects.
- -
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.kernel.Persistent" abstract="true">
-
-
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
-
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Base implementation of the API Design Pattern of objects which persistence is based on Hibernate.<br/>
- * This Design Pattern supports the following features:
- * <ul>
- * <li>Flexible API for constructing objects from many variable arguments</li>
- * <li>Impossible to leave persistent objects in inconsistent state, even temporarily, during their construction</li>
- * <li>Same Object Oriented API for constructing and selecting objects from the database</li>
- * <li>Centralized validity check of arguments</li>
- * </ul>
- * The API is based on intermediate properties objects used for collecting arguments and checking their validity.
- * These properties objects are passed to persistent object constructors and database select functions for execution.
- * For example, as based on this Design Pattern, a User object could be created that way:
- * <pre>
- * User.Properties args = new User.Properties();
- * User user = new User( args.setUsername("mypseudo").setMailAddress("me@provider.domain") );
- * </pre>
- * Classes implementing this Design Pattern must inherit from Persistent and implement their Properties class as a nested
- * subclass of Persistent.Properties.<br/>
- * <br/>
- * Naturally, as usual with Hibernate, any class can be persistent (you don't need to inherit from Persistent for being
- * persistent). Inheriting from Persistent is only a matter of enabling the API supported by the above Design Pattern.
- *
- * @see ObjectProperties
- * @see Persistent.Properties
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-
-public abstract class Persistent {
-
- private int rid; // Primary key of persistent objects
-
- protected abstract static class Properties implements ObjectProperties {
-// ----------------------------------------------------------------------
- private boolean tobechecked = true; // Property validity check flag
-
- public void disableCheck () {
- tobechecked = false;
- }
- public boolean mustBeChecked () {
- return tobechecked;
- }
- public void clear () {
- tobechecked = true;
- }
- }
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-/**
- * Database fetch constructor.
- */
- protected Persistent () {
-// -----------------------
- rid = 0; // Set when loading the object
- }
-
-/**
- * Checks the mutual compatibility of arguments previously set in the given properties object, if the validity check is enabled.
- * As this validity depends on concrete classes, the check is delegated to subclasses of the given Persistent.Properties.
- */
- protected Persistent (ObjectProperties oprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// ---------------------------------------------
- if (oprop.mustBeChecked()) oprop.checkValidity(); // Throws one of the above exception if not valid
- rid = 0; // Set when saving the object
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean equals(Object entity) {
-// ------------------------------------
- if (entity == null) return false;
- if (entity.getClass().equals(this.getClass())) {
- Persistent object = (Persistent)entity;
- int he = object.getIndex(); // getIndex() is supposed fetching the index if not yet done
- int me = this.getIndex(); // getIndex() is supposed fetching the index if not yet done
- if (me*he != 0) return (he == me);
- if (me+he == 0) return (this == object);
- }
- return false;
- }
-
-/**
- * Returns the Persistent ID of this object. The PID is set when saving this object. It is unique in the scope of the class
- * of this object only.
- *
- * @return the PID of this, or 0 if this is not saved.
- * @see isSaved()
- */
- public int getIndex () {
-// ----------------------
- return rid;
- }
-
- public int hashCode () {
-// ----------------------
- return toString().hashCode();
- }
-
-/**
- * Returns true if this object is saved.
- *
- * @return true if this is saved.
- * @see getIndex()
- */
- public boolean isSaved () {
-// -------------------------
- return (getIndex() != 0); // getIndex() is supposed fetching the index if not yet done
- }
-
-/**
- * Return a string representing uniquely this object.
- *
- * @return the unique string representation of this object.
- */
- public String toString () {
-// -------------------------
- int oid = getIndex(); // getIndex() is supposed fetching the index if not yet done
- if (oid == 0) oid = super.hashCode(); //WARNING: Must not call super.toString() as it goes back here (this.toString())
- return new StringBuffer("object ").append(getClass().getName()).append("@").append(oid).toString();
- }
-}
\ No newline at end of file
import javax.security.auth.spi.*;
import org.apache.log4j.Logger;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.kernel.Database;
public class RealmLoginModule implements LoginModule {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the Relation class hierarchy.
- - The entire hierarchy is mapped to one single table using a String discriminator.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.kernel.Relation" abstract="true" table="relation">
-
- <!-- int rid -->
- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
- <generator class="org.splat.kernel.IDGenerator"/>
- </id>
- <discriminator column="name" type="string"/>
-
- <!-- Set<Attribute> attributes -->
- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Attribute" />
- </set>
-
- <!-- Entity owner -->
- <many-to-one name="owner" column="owner" access="field" not-null="true" />
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Base implementation of relations between entities.<br/>
- * A relation makes a typed link from an entity to any kind persistent object. The relations are typed by subclasses of this
- * abstract class which define the actual object referenced by the relation.<br/>
- * This Relation base class implements unidirectional relations. The bidirectionality must be implemented in concrete subclasses
- * by:
- * <ul>
- * <li>overriding the isBidirectional() and getReverseClass() methods,</li>
- * <li>creating the reverse relation in constructors.</li>
- * </ul>
- * Relation objects also support dynamic attributes provided by the Any class.
- *
- * @see Entity
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Iterator;
-
-import org.hibernate.Session;
-
-
-public abstract class Relation extends Any {
-
-// Persistent fields
- protected Entity owner; // Study or Document
-
-// Transient field
- protected Relation reverse;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected Relation () {
-// ---------------------
- reverse = null;
- }
-// Initialization constructor
- protected Relation (Entity from) {
-// --------------------------------
- super((Attribute)null); // For building the collection of attributes
- this.owner = from;
- this.reverse = null; // Initialized by subclasses
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Entity getFrom () {
-// ------------------------
- return owner;
- }
-
- public Relation getReverse () {
-// -----------------------------
- if (!this.isBidirectional() || reverse != null) return reverse;
-
- Class<? extends Relation> type = this.getReverseClass();
- Entity to = (Entity)this.getTo(); // Bidirectional relations are necessarily between Entities
-
- for (Iterator<Relation> i=to.getAllRelations().iterator(); i.hasNext(); ) {
- Relation asked = i.next();
- if (!asked.getClass().equals(type)) continue;
- if (!asked.getTo().equals(owner)) continue;
- reverse = asked;
- reverse.reverse = this; // For benefiting from this execution
- return reverse;
- }
- return null;
- }
-
- public Class<? extends Relation> getReverseClass () {
-// ---------------------------------------------------
- return null;
- }
-
- public boolean isBidirectional () {
-// ---------------------------------
- return false;
- }
-
-/**
- * Moves this relation from its current owner entity to the given one.
- *
- * @param nowner the document to which this relation is moved
- * */
- public void moveTo (Entity nowner) {
-// ----------------------------------
- Session session = Database.getSession();
-
- this.owner = nowner;
- nowner.getAllRelations().add(this);
-// myold.getAllRelations().remove(this); Harmful as it leads to remove this relation from the database (!?)
- session.update(this);
- session.update(nowner);
-
- if (this.isBidirectional()) {
- Relation link = this.getReverse();
- link.setTo(nowner);
- session.update(link);
- }
- }
-
-// ==============================================================================================================================
-// Abstract functions
-// ==============================================================================================================================
-
- public abstract Persistent getTo ();
- protected abstract void setTo (Persistent to); // For the need of the moveTo() method
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- * Class of objects representing the role of users.
- * A role is named by an application-dependent string (reason why role names are not defined by an enumeration).
- * A user may have several roles, user roles being stored into the database as a list of role names separated by a comma.
- *
- * @see User
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Vector;
-
-
-public class Role {
-
- private String username;
- private String role;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected Role () {
- }
-// Initialization constructor
- protected Role (String username, String role) {
-// ---------------------------------------------
- this.username = username;
- this.role = role;
- }
-
-// ==============================================================================================================================
-// Protected member functions
-// ==============================================================================================================================
-
- protected void addRole (String role) {
-// ------------------------------------
- this.role = this.role + "," + role;
- }
-
- protected Role[] toArray () {
-// ---------------------------
- String[] name = role.split(",");
- Vector<Role> role = new Vector<Role>();
-
- for (int i=0; i<name.length; i++) role.add(new Role(username, name[i]));
- return role.toArray(new Role[name.length]);
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-// In functions bellow, the role is supposed having previously been extracted as an array.
-
- public String getName () {
-// ------------------------
- return role;
- }
-
- public boolean is (String name) {
-// -------------------------------
- return this.role.equals(name);
- }
-
- public boolean isSame (Role other) {
-// ----------------------------------
- return this.role.equals(other.role);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
-<!-- <subclass name="org.splat.kernel.TextAttribute" extends="org.splat.kernel.Attribute" discriminator-value="text">-->
-
- <joined-subclass name="org.splat.kernel.TextAttribute" extends="org.splat.kernel.Attribute" table="text_attr">
- <key column="rid"/>
- <!-- <many-to-one name="mytext" column="value" access="field" cascade="all" not-null="true" /> -->
- <property name="mytext" column="value" type="text" access="field" not-null="true"/>
-
- </joined-subclass>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-
-public abstract class TextAttribute extends Attribute {
-
- //private Text mytext;
- private String mytext;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor.
- protected TextAttribute () {
- }
-
-// Initialization constructor
- protected TextAttribute (Any from, String value) {
-// ----------------------------------------------
- super(from);
- mytext = value;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public String getValue () {
-// -------------------------
- return mytext;
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected void setValue (String value) {
-// --------------------------------------
- mytext = value;
- if (this.isSaved()) Database.getSession().update(this);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the User class and its corresponding Role definition.
- - User and Role are associated by a one-to-one association on the username User foreign key.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
-<!-- Class User
- -->
- <class name="org.splat.kernel.User" table="user" lazy="false">
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
- <natural-id>
- <property name="username" column="username" access="field" />
- <many-to-one name="role" column="username" insert="false" update="false" unique="true" cascade="save-update" access="field" />
- <property name="email" column="email" access="field" />
- </natural-id>
- <property name="password" column="password" access="field" />
- <property name="first" column="first" access="field" not-null="true" />
- <property name="last" column="last" access="field" not-null="true" />
- <property name="display" column="display" access="field" />
- <property name="organid" column="organid" access="field" />
- </class>
-
-<!-- Class Role
- -->
- <class name="org.splat.kernel.Role" table="role" lazy="false">
- <id name="username" column="username" access="field">
- <generator class="assigned"/>
- </id>
- <property name="role" column="role" access="field" not-null="true" />
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.kernel;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.security.Principal;
-
-import org.splat.kernel.Persistent;
-
-
-public class User extends Persistent implements Principal, Name {
-
-// Persistent fields
- @SuppressWarnings("unused")
- private String password; // Property without getter function
-
- private String username; // Unique in the user directory
- private String first;
- private String last;
- private String display; // Optional
- private Role role; // Roles as list (as stored into the database)
- private String email;
- private String organid;
-
-// Fields initialization class
- public static class Properties extends Persistent.Properties {
-// ------------------------------------------------------------
- private String username = null;
- private String password = null;;
- private String first = null;
- private String last = null;
- private String display = null;
- private Role role = null;
- private String email = null;
- private String organid = null;
-
-// - Public services
-
- public void clear () {
- super.clear();
- username = null;
- password = null;;
- first = null;
- last = null;
- display = null;
- role = null;
- email = null;
- organid = null;
- }
- public String getOrganizationName () {
- return organid;
- }
- public String getPassword () {
- return password;
- }
- public String getUsername () {
- return username;
- }
-// - Property setters
-
- public Properties addRole (String role) throws InvalidPropertyException
- {
- if (role.length() == 0) throw new InvalidPropertyException("role");
- if (this.role == null) {
- this.role = new Role(username, role);
- } else {
- Role[] curole = this.role.toArray();
- for (int i=0; i<curole.length; i++) if (curole[i].is(role)) return this;
- this.role.addRole(role);
- }
- return this;
- }
- public Properties setDisplayName (String display) throws InvalidPropertyException
- {
- if (display.length() == 0) throw new InvalidPropertyException("displayname");
- this.display = display;
- return this;
- }
- public Properties setFirstName (String first) throws InvalidPropertyException
- {
- if (first.length() == 0) throw new InvalidPropertyException("firstname");
- this.first = first;
- return this;
- }
- public Properties setMailAddress (String address) throws InvalidPropertyException
- {
- String[] term = address.split("@"); // Must be of the form x@y
- if (term.length != 2) throw new InvalidPropertyException("address");
- term = term[1].split("\\x2E"); // Must be of the form x@y.z
- if (term.length != 2) throw new InvalidPropertyException("address");
- this.email = address;
- return this;
- }
- public Properties setName (String last) throws InvalidPropertyException
- {
- if (last.length() == 0) throw new InvalidPropertyException("lastname");
- this.last = last;
- return this;
- }
- public Properties setOrganizationName (String organization) throws InvalidPropertyException
- {
- if (organization.length() == 0) throw new InvalidPropertyException("organization");
- this.organid = organization;
- return this;
- }
- public Properties setPassword (String password) throws InvalidPropertyException
- {
- if (password != null) {
- if (password.length() < 1) throw new InvalidPropertyException("password");
- this.password = String.valueOf(password.hashCode());
- }
- return this;
- }
- public Properties setUsername (String username) throws InvalidPropertyException
- {
- if (username.length() == 0) throw new InvalidPropertyException("username");
- this.username = username;
- return this;
- }
-// - Global validity check
-
- public void checkValidity () throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (username == null) throw new MissedPropertyException("username");
- if (first == null) throw new MissedPropertyException("firstname");
- if (last == null) throw new MissedPropertyException("lastname");
- if (role == null) throw new MissedPropertyException("role");
- if (email == null) throw new MissedPropertyException("email");
-//TODO: Check if username exists
- }
- }
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected User () {
-// --------------
- }
-// Anonymous user supposed not to be saved
- public User (String name) {
-// -------------------------
- username = null;
- password = null;
- first = null;
- last = null;
- display = name;
- role = null;
- email = null;
- organid = null;
- }
-// New user
- public User (Properties uprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// ------------------------------
- super(uprop); // Throws one of the above exception if not valid
- this.username = uprop.username;
- this.password = uprop.password;
- this.first = uprop.first;
- this.last = uprop.last;
- this.display = uprop.display;
- this.role = uprop.role;
- this.email = uprop.email;
- this.organid = uprop.organid;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean equals (Object item) {
-// -----------------------------------
- if (item == null) return false;
- if (item instanceof String) {
- return this.username.equals((String)item); // Usernames are unique
- }
- else if (item instanceof User) {
- User given = (User)item;
- if (isSaved()) return (this.getIndex() == given.getIndex());
- else return (this.username.equals(given.username)); // Usernames are unique
- } else {
- return false;
- }
- }
-
- public String getDisplayName () {
-// -------------------------------
- if (display == null) return last + " " + first;
- else return display;
- }
-
- public String getFirstName () {
-// -----------------------------
- return first;
- }
-
- public String getMailAddress () {
-// -------------------------------
- return email;
- }
-
- public String getName () {
-// ------------------------
- return last;
- }
-
- public String getOrganizationName () {
-// ------------------------------------
- return organid;
- }
-
- public String getRoleNames () {
-// -----------------------------
- return role.getName();
- }
-
- public Role[] getRoles () {
-// -------------------------
- return role.toArray();
- }
-
- public String getUsername () {
-// ----------------------------
- return username;
- }
-
- public String toString () {
-// -------------------------
- return last + " " + first;
- }
-}
\ No newline at end of file
import javax.xml.parsers.ParserConfigurationException;
import org.hibernate.Session;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
import org.splat.manox.XDOM;
import org.splat.manox.XMLException;
-import org.splat.som.Database;
import org.w3c.dom.Node;
import org.apache.log4j.Logger;
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+/**
+ * @author RKV
+ *
+ */
+public interface DocumentService {
+
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+/**
+ * @author RKV
+ *
+ */
+public class DocumentServiceImpl implements DocumentService {
+
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.som.DocumentType;
+
+/**
+ * @author RKV
+ *
+ */
+public interface DocumentTypeService {
+
+ /**
+ * Checks if documents of this type are result of a study.
+ * A document is the result of a study when it is the result of the last step of the study.
+ *
+ * @return true if documents of this type are result of a study.
+ * @see #isStepResult()
+ * @see #isResultOf(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
+ */
+ public boolean isStudyResult (DocumentType aType);
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.util.List;
+
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.service.technical.ProjectSettingsService;
+
+/**
+ * @author RKV
+ *
+ */
+public class DocumentTypeServiceImpl implements DocumentTypeService {
+
+ private ProjectSettingsService _projectSettingsService;
+
+ /**
+ * Checks if documents of this type are result of a study.
+ * A document is the result of a study when it is the result of the last step of the study.
+ *
+ * @return true if documents of this type are result of a study.
+ * @see #isStepResult()
+ * @see #isResultOf(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
+ */
+ public boolean isStudyResult (DocumentType aType) {
+ // -------------------------------
+ List<ProjectSettingsService.Step> step = getProjectSettingsService().getAllSteps();
+ ProjectSettingsService.Step lastep = step.get( step.size()-1 );
+ return (aType.isResultOf(lastep));
+ }
+
+ /**
+ * @return
+ */
+ public ProjectSettingsService getProjectSettingsService() {
+ return _projectSettingsService;
+ }
+
+ public void setProjectSettingsService(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.kernel.InvalidPropertyException;
+
+/**
+ * @author RKV
+ *
+ */
+public interface KnowledgeElementService {
+
+ public boolean approve(KnowledgeElement knowledgeElement);
+
+ public boolean demote(KnowledgeElement knowledgeElement);
+
+ public boolean promote(KnowledgeElement knowledgeElement);
+
+ public void rename(KnowledgeElement knowledgeElement, String title)
+ throws InvalidPropertyException;
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.dao.kernel.GenericDAO;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.dao.som.KnowledgeElementDAO;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.service.technical.IndexService;
+
+/**
+ * @author RKV
+ *
+ */
+public class KnowledgeElementServiceImpl implements KnowledgeElementService {
+
+ private IndexService _indexService;
+ private KnowledgeElementDAO _knowledgeElementDAO;
+
+ public boolean approve(KnowledgeElement knowledgeElement) {
+ // -------------------------
+ if (knowledgeElement.getProgressState() != ProgressState.inCHECK)
+ return false;
+ knowledgeElement.setProgressState(ProgressState.APPROVED);
+ return update(knowledgeElement);
+ }
+
+ public boolean demote(KnowledgeElement knowledgeElement) {
+ // ------------------------
+ if (knowledgeElement.getProgressState() != ProgressState.APPROVED
+ && knowledgeElement.getProgressState() != ProgressState.inCHECK)
+ return false;
+ knowledgeElement.setProgressState(ProgressState.inDRAFT);
+ return update(knowledgeElement);
+ }
+
+ protected boolean update(KnowledgeElement knowledgeElement) {
+ // -----------------------------
+ try {
+ getKnowledgeElementDAO().update(knowledgeElement);
+ getIndexService().update(knowledgeElement);
+ return true;
+ } catch (Exception error) {
+ // logger.error("Unable to re-index the knowledge '" + getIndex() + "', reason:", error);
+ return false;
+ }
+ }
+
+ public boolean promote (KnowledgeElement knowledgeElement) {
+// -------------------------
+ if (knowledgeElement.getProgressState() != ProgressState.inDRAFT) return false;
+ knowledgeElement.setProgressState(ProgressState.inCHECK);
+ return update(knowledgeElement);
+ }
+
+ public void rename (KnowledgeElement knowledgeElement, String title) throws InvalidPropertyException {
+ if (title.length() == 0) throw new InvalidPropertyException("name");
+ knowledgeElement.setTitle(title);
+ update(knowledgeElement);
+ }
+
+ /**
+ * @return
+ */
+ public IndexService getIndexService() {
+ return _indexService;
+ }
+
+ public void setIndexService(IndexService indexService) {
+ _indexService = indexService;
+ }
+
+ /**
+ * @return
+ */
+ public KnowledgeElementDAO getKnowledgeElementDAO() {
+ return _knowledgeElementDAO;
+ }
+
+ public void setKnowledgeElementDAO(KnowledgeElementDAO knowledgeElementDAO) {
+ _knowledgeElementDAO = knowledgeElementDAO;
+ }
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 07.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public interface ProjectElementService {
+
+ public Step getFirstStep(ProjectElement elem);
+
+ public Step[] getSteps(ProjectElement elem);
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 07.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public class ProjectElementServiceImpl implements ProjectElementService {
+
+ private ProjectSettingsService _projectSettingsService;
+
+ public Step getFirstStep(ProjectElement elem) {
+ // ---------------------------
+ return getSteps(elem)[0];
+ }
+
+ public Step getLastStep(ProjectElement elem) {
+ // --------------------------
+ Step[] mystep = getSteps(elem); // For getting the folders length, if null
+ return mystep[mystep.length - 1];
+ }
+
+ public Step[] getSteps(ProjectElement elem) {
+ // -------------------------
+ if (elem.getFolders() == null) {
+ List<ProjectSettingsService.Step> steps = getProjectSettings()
+ .getStepsOf(elem.getClass());
+ Iterator<ProjectSettingsService.Step> nstep = steps.iterator();
+
+ elem.setFolders(new Step[steps.size()]);
+ for (int i = 0; i < elem.getFolders().length; i++) {
+ elem.getFolders()[i] = new Step(nstep.next(), elem);
+ }
+ }
+ return elem.getFolders(); // No protection against this object corruption as it would not corrupt the database
+ }
+
+ /**
+ * Get project settings.
+ *
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ *
+ * @param projectSettingsService
+ * project settings service
+ */
+ public void setProjectSettings(ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.io.FileNotFoundException;
+import java.util.Date;
+
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.Timestamp;
+import org.splat.kernel.NotApplicableException;
+import org.splat.som.DocumentRights;
+import org.splat.som.Revision;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public interface PublicationService {
+
+ public Publication copy(Publication aPublication, ProjectElement publisher);
+
+ /**
+ * Returns the study Step into which the document version referenced by this publication has been published.
+ */
+ public Step getInvolvedStep(Publication aPublication);
+
+ /**
+ * Promotes the document referenced by this publication from In-Check to Approved state, if not out-dated, and attaches the
+ * corresponding time-stamp to the document.</br> If the promoted document is the final result of the owner study, the study is itself
+ * is promoted as well.</br> </br> Limitation: the way this promotion is propagated to the study supposes that the study has only ONE
+ * final result document.
+ *
+ * @param adate
+ * the date of approval
+ * @return true if the approval succeeded
+ * @see #getProgressState()
+ * @see DocumentRights#canApprove()
+ * @see DocumentType#isStudyResult()
+ * @see Study#getApproverOf(Publication)
+ */
+ public Timestamp approve(Publication aPublication, Date adate);
+
+ /**
+ * Demotes the document referenced by this publication to In-Work state, and removes the Promoter of the document, if exist.</br> The
+ * In-Draft state is skipped (direct demotion to In-Work) if the validation cycle of the document does not include the review step.</br>
+ * If the demoted document is the final result of the owner study, the study is itself is demoted as well.</br> </br> Limitation: the
+ * way this demotion is propagated to the study supposes that the study has only ONE final result document.
+ *
+ * @return true if the demotion succeeded
+ * @see #getProgressState()
+ * @see DocumentRights#canDemote()
+ * @see DocumentType#isStudyResult()
+ */
+ public boolean demote(Publication aPublication);
+
+ /**
+ * Undo the review operation by demoting the document referenced by this publication from In-Check to In-Draft state and removing the
+ * Reviewer.</br> If the demoted document is the final result of the owner study, the study is itself is demoted as well.</br> </br>
+ * Limitation: the way this demotion is propagated to the study supposes that the study has only ONE final result document.
+ *
+ * @return true if the demotion succeeded
+ * @see #getProgressState()
+ * @see #review()
+ * @see DocumentRights#canInvalidate()
+ * @see DocumentType#isStudyResult()
+ */
+ public boolean invalidate(Publication aPublication);
+
+ /**
+ * Promotes the document referenced by this publication from In-Work to In-Draft or In-Check state, if not out-dated, and attaches the
+ * corresponding time-stamp to the document.</br> The In-Draft state is skipped (direct promotion to In-Check) if the validation cycle
+ * of the document does not include the review step.</br> Also, if the promoted document is the final result of the owner study, the
+ * study is itself promoted as well.</br> This operation can be undo-ed by demote().</br> </br> Limitation: the way this promotion is
+ * propagated to the study supposes that the study has only ONE final result document.
+ *
+ * @return true if the promotion succeeded
+ * @see #getProgressState()
+ * @see #demote()
+ * @see DocumentRights#canPromote()
+ * @see DocumentType#isStudyResult()
+ */
+ public Timestamp promote(Publication aPublication, Date pdate);
+
+ /**
+ * Promotes the document referenced by this publication from In-Draft to In-Check state, if not out-dated, and attaches the
+ * corresponding time-stamp to the document.</br> If the promoted document is the final result of the owner study, the study is itself
+ * is promoted as well.</br> This operation can be undo-ed by invalidate().</br> </br> Limitation: the way this promotion is propagated
+ * to the study supposes that the study has only ONE final result document.
+ *
+ * @param rdate
+ * the date of review
+ * @return true if the review succeeded
+ * @see #getProgressState()
+ * @see #invalidate()
+ * @see DocumentRights#canReview()
+ * @see DocumentType#isStudyResult()
+ * @see Study#getReviewerOf(Publication)
+ */
+ public Timestamp review(Publication aPublication, Date rdate);
+
+ /**
+ * Publishes the document referenced by this publication into the owner Project Element under the given state, the revision number of
+ * the document being automatically set accordingly. If the given state is In-Draft and the document is final result of the owner study,
+ * this automatically promotes the study to In-Draft.
+ *
+ * @param state
+ * the required progress state
+ * @throws FileNotFoundException
+ * If the referenced document is empty
+ * @throws NotApplicableException
+ * If the referenced document is undefined
+ */
+ public void saveAs(Publication aPublication, ProgressState state)
+ throws FileNotFoundException, NotApplicableException;
+
+ /**
+ * Publishes the document referenced by this publication into the owner Project Element under the given revision number.<br/>
+ * The state of the referenced document is supposed being automatically set according to the given revision number, but, due to the
+ * versioning scheme, as it is not possible to differentiate In-Work and In-Draft states, this function has been deprecated (it is
+ * currently used only for the need of integration of Microsoft Office which anyway has to be redesigned). <br/>
+ * Note: in the context of branch versioning, the given revision may be modified by an update of the branch name.
+ *
+ * @param newvers
+ * the required revision number
+ * @throws FileNotFoundException
+ * If the referenced document is empty
+ * @throws NotApplicableException
+ * If the referenced document is undefined
+ * @deprecated
+ */
+ public void saveAs(Publication aPublication, Revision newvers)
+ throws FileNotFoundException, NotApplicableException;
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.Timestamp;
+import org.splat.dal.bo.som.ValidationCycle;
+import org.splat.dal.bo.som.ValidationStep;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.NotApplicableException;
+import org.splat.manox.Reader;
+import org.splat.manox.Toolbox;
+import org.splat.som.DocumentRights;
+import org.splat.som.Revision;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public class PublicationServiceImpl implements PublicationService {
+
+ private StudyService _studyService;
+ private StepService _stepService;
+ private DocumentTypeService _documentTypeService;
+ private ProjectElementService _projectElementService;
+
+ public Publication copy(Publication aPublication, ProjectElement publisher) {
+ // -----------------------------------------------------
+ Publication copy = new Publication();
+ copy.setValue(aPublication.value());
+ copy.setStep(aPublication.getStep()); // May not be initialized yet
+ copy.setOwner(publisher);
+ copy.setIsnew(aPublication.getIsnew());
+ if (!copy.getOwnerStudy().equals(aPublication.getOwnerStudy())) {
+ copy.setIsnew('N'); // The referenced document is not new for the given study
+ }
+ return copy;
+ }
+
+ /**
+ * Promotes the document referenced by this publication from In-Check to Approved state, if not out-dated, and attaches the
+ * corresponding time-stamp to the document.</br> If the promoted document is the final result of the owner study, the study is itself
+ * is promoted as well.</br> </br> Limitation: the way this promotion is propagated to the study supposes that the study has only ONE
+ * final result document.
+ *
+ * @param adate
+ * the date of approval
+ * @return true if the approval succeeded
+ * @see #getProgressState()
+ * @see DocumentRights#canApprove()
+ * @see DocumentType#isStudyResult()
+ * @see Study#getApproverOf(Publication)
+ */
+ public Timestamp approve(Publication aPublication, Date adate) {
+ // -------------------------------------
+ if (aPublication.isOutdated())
+ return null;
+ else if (aPublication.value().getProgressState() != ProgressState.inCHECK)
+ return null; // This statement must conform to the corresponding right
+
+ DocumentType type = aPublication.value().getType();
+ Study owner = aPublication.getOwnerStudy();
+ ValidationCycle cycle = owner.getValidationCycleOf(type);
+ User approver = cycle.getActor(ValidationStep.APPROVAL);
+ Timestamp stamp = new Timestamp(ValidationStep.APPROVAL,
+ aPublication.value(), approver, adate);
+ if (!aPublication.value().promote(stamp))
+ return null;
+ if (getDocumentTypeService().isStudyResult(type)
+ && owner.getProgressState() == ProgressState.inCHECK)
+ getStudyService().promote(owner);
+ return stamp; // Hoping that promotion of the study succeeded
+ }
+
+ /**
+ * Demotes the document referenced by this publication to In-Work state, and removes the Promoter of the document, if exist.</br> The
+ * In-Draft state is skipped (direct demotion to In-Work) if the validation cycle of the document does not include the review step.</br>
+ * If the demoted document is the final result of the owner study, the study is itself is demoted as well.</br> </br> Limitation: the
+ * way this demotion is propagated to the study supposes that the study has only ONE final result document.
+ *
+ * @return true if the demotion succeeded
+ * @see #getProgressState()
+ * @see DocumentRights#canDemote()
+ * @see DocumentType#isStudyResult()
+ */
+ public boolean demote(Publication aPublication) {
+ // ------------------------
+ DocumentType type = aPublication.value().getType();
+ Study owner = aPublication.getOwnerStudy();
+
+ if (aPublication.value().getProgressState() == ProgressState.inCHECK) {
+ ValidationCycle cycle = owner.getValidationCycleOf(type);
+ if (cycle.enables(ValidationStep.REVIEW)) {
+ if (!aPublication.value().demote())
+ return false;
+ } else {
+ if (!aPublication.value().demote())
+ return false;
+ aPublication.value().demote();
+ }
+ } else if (aPublication.value().getProgressState() == ProgressState.inDRAFT) {
+ if (!aPublication.value().demote())
+ return false;
+ } else {
+ return false;
+ }
+ if (getDocumentTypeService().isStudyResult(type)
+ && owner.getProgressState() != ProgressState.inWORK)
+ getStudyService().demote(owner);
+ return true;
+ }
+
+ /**
+ * Undo the review operation by demoting the document referenced by this publication from In-Check to In-Draft state and removing the
+ * Reviewer.</br> If the demoted document is the final result of the owner study, the study is itself is demoted as well.</br> </br>
+ * Limitation: the way this demotion is propagated to the study supposes that the study has only ONE final result document.
+ *
+ * @return true if the demotion succeeded
+ * @see #getProgressState()
+ * @see #review()
+ * @see DocumentRights#canInvalidate()
+ * @see DocumentType#isStudyResult()
+ */
+ public boolean invalidate(Publication aPublication) {
+ // ----------------------------
+ if (aPublication.value().getProgressState() != ProgressState.inCHECK)
+ return false;
+ if (!aPublication.value().demote()) // Removes the reviewer if this document is In-Check
+ return false;
+ DocumentType type = aPublication.value().getType();
+ Study owner = aPublication.getOwnerStudy();
+ if (getDocumentTypeService().isStudyResult(type)
+ && owner.getProgressState() == ProgressState.inCHECK)
+ getStudyService().demote(owner);
+ return true;
+ }
+
+ /**
+ * Promotes the document referenced by this publication from In-Work to In-Draft or In-Check state, if not out-dated, and attaches the
+ * corresponding time-stamp to the document.</br> The In-Draft state is skipped (direct promotion to In-Check) if the validation cycle
+ * of the document does not include the review step.</br> Also, if the promoted document is the final result of the owner study, the
+ * study is itself promoted as well.</br> This operation can be undo-ed by demote().</br> </br> Limitation: the way this promotion is
+ * propagated to the study supposes that the study has only ONE final result document.
+ *
+ * @return true if the promotion succeeded
+ * @see #getProgressState()
+ * @see #demote()
+ * @see DocumentRights#canPromote()
+ * @see DocumentType#isStudyResult()
+ */
+ public Timestamp promote(Publication aPublication, Date pdate) {
+ if (aPublication.isOutdated())
+ return null;
+ else if (aPublication.value().getProgressState() != ProgressState.inWORK)
+ return null; // This statement must conform to the corresponding right
+ else {
+ DocumentType type = aPublication.value().getType();
+ Study owner = aPublication.getOwnerStudy();
+ ValidationCycle cycle = owner.getValidationCycleOf(type);
+ User promoter = cycle.getActor(ValidationStep.PROMOTION);
+ if (promoter == null)
+ promoter = getInvolvedStep(aPublication).getActor();
+ if (promoter == null)
+ promoter = owner.getAuthor();
+ Timestamp stamp = new Timestamp(ValidationStep.PROMOTION,
+ aPublication.value(), promoter, pdate);
+
+ if (!aPublication.value().promote(stamp)) // Promotion to being reviewed
+ return null;
+ if (!cycle.enables(ValidationStep.REVIEW)) {
+ aPublication.value().promote(null);
+ }
+ if (getDocumentTypeService().isStudyResult(type)
+ && owner.getProgressState() == ProgressState.inWORK)
+ getStudyService().promote(owner);
+ return stamp; // Hoping that promotion of the study succeeded
+ }
+ }
+
+ /**
+ * Promotes the document referenced by this publication from In-Draft to In-Check state, if not out-dated, and attaches the
+ * corresponding time-stamp to the document.</br> If the promoted document is the final result of the owner study, the study is itself
+ * is promoted as well.</br> This operation can be undo-ed by invalidate().</br> </br> Limitation: the way this promotion is propagated
+ * to the study supposes that the study has only ONE final result document.
+ *
+ * @param rdate
+ * the date of review
+ * @return true if the review succeeded
+ * @see #getProgressState()
+ * @see #invalidate()
+ * @see DocumentRights#canReview()
+ * @see DocumentType#isStudyResult()
+ * @see Study#getReviewerOf(Publication)
+ */
+ public Timestamp review(Publication aPublication, Date rdate) {
+ if (aPublication.isOutdated())
+ return null;
+ else if (aPublication.value().getProgressState() != ProgressState.inDRAFT)
+ return null; // This statement must conform to the corresponding right
+
+ DocumentType type = aPublication.value().getType();
+ Study owner = aPublication.getOwnerStudy();
+ ValidationCycle cycle = owner.getValidationCycleOf(type);
+ User reviewer = cycle.getActor(ValidationStep.REVIEW);
+ Timestamp stamp = new Timestamp(ValidationStep.REVIEW,
+ aPublication.value(), reviewer, rdate);
+ if (!aPublication.value().promote(stamp))
+ return null;
+ if (getDocumentTypeService().isStudyResult(type)
+ && owner.getProgressState() == ProgressState.inDRAFT)
+ getStudyService().promote(owner);
+ return stamp; // Hoping that promotion of the study succeeded
+ }
+
+ /**
+ * Publishes the document referenced by this publication into the owner Project Element under the given revision number.<br/>
+ * The state of the referenced document is supposed being automatically set according to the given revision number, but, due to the
+ * versioning scheme, as it is not possible to differentiate In-Work and In-Draft states, this function has been deprecated (it is
+ * currently used only for the need of integration of Microsoft Office which anyway has to be redesigned). <br/>
+ * Note: in the context of branch versioning, the given revision may be modified by an update of the branch name.
+ *
+ * @param newvers
+ * the required revision number
+ * @throws FileNotFoundException
+ * If the referenced document is empty
+ * @throws NotApplicableException
+ * If the referenced document is undefined
+ * @deprecated
+ */
+ public void saveAs(Publication aPublication, Revision newvers)
+ throws FileNotFoundException, NotApplicableException {
+ // -------------------------------------
+ if (aPublication.value().isUndefined())
+ throw new NotApplicableException(
+ "Cannot save a Publication object refering an undefined Document");
+ if (!aPublication.value().getSourceFile().exists())
+ throw new FileNotFoundException();
+
+ Database.getSession().save(aPublication); // Must be done before updating the study in order to fix this final (rid-based) hascode
+ aPublication.value().updateAs(newvers); // May change the branch name of given revision
+ updateOwner(aPublication);
+ }
+
+ /**
+ * Publishes the document referenced by this publication into the owner Project Element under the given state, the revision number of
+ * the document being automatically set accordingly. If the given state is In-Draft and the document is final result of the owner study,
+ * this automatically promotes the study to In-Draft.
+ *
+ * @param state
+ * the required progress state
+ * @throws FileNotFoundException
+ * If the referenced document is empty
+ * @throws NotApplicableException
+ * If the referenced document is undefined
+ */
+ public void saveAs(Publication aPublication, ProgressState state)
+ throws FileNotFoundException, NotApplicableException {
+ // ----------------------------------------
+ if (aPublication.value().isUndefined())
+ throw new NotApplicableException(
+ "Cannot save a Publication object refering an undefined Document");
+ if (!aPublication.value().getSourceFile().exists())
+ throw new FileNotFoundException();
+
+ if (state == ProgressState.inWORK || state == ProgressState.EXTERN) {
+ Database.getSession().save(this); // Must be done before updating the study in order to fix this final (rid-based) hascode
+ aPublication.value().updateAs(state);
+ } else {
+ DocumentType mytype = aPublication.value().getType();
+ Study owner = aPublication.getOwnerStudy();
+ ValidationCycle cycle = owner.getValidationCycleOf(mytype);
+ boolean review = cycle.enables(ValidationStep.REVIEW);
+ if (!(state == ProgressState.inDRAFT && review)
+ && !(state == ProgressState.inCHECK && !review)) {
+ throw new NotApplicableException(
+ "Cannot save a result document in " + state.toString()
+ + " state");
+ }
+ Database.getSession().save(aPublication); // Must be done before updating the study in order to fix this final (rid-based)
+ // hascode
+ aPublication.value().updateAs(ProgressState.inWORK);
+
+ promote(aPublication, aPublication.value()
+ .getLastModificationDate()); // Promotes to the appropriate state in accordance to the validation cycle
+ }
+ updateOwner(aPublication);
+ }
+
+ public void updateOwner(Publication aPublication) {
+ // ---------------------------
+ Session session = Database.getSession();
+ Step step = getInvolvedStep(aPublication);
+
+ // Update of involved step
+ Document previous = aPublication.value().getPreviousVersion();
+ if (previous != null) {
+ Publication oldoc = step.getDocument(previous.getIndex());
+ boolean done = step.remove(oldoc); // Decrements the configuration tag count of document
+ if (done)
+ session.delete(oldoc); // WARNING: Potential problem because it's not automatically done as orphan object
+ }
+ step.add(aPublication); // Increments the configuration tag count of document
+
+ // Import the document properties and update of the study
+ forwardProperties(aPublication, aPublication.value().getSourceFile()
+ .asFile(), step);
+ session.update(aPublication.getOwner());
+ }
+
+ private void forwardProperties(Publication aPublication, java.io.File from,
+ Step to) {
+ // -----------------------------------------------------------
+ Reader tool = Toolbox.getReader(from);
+ if (tool == null)
+ return; // No properties extractor available for this type of document
+
+ SimulationContextType.Properties sprop = new SimulationContextType.Properties()
+ .setStep(to.getStep()).setState(ProgressState.APPROVED);
+ List<SimulationContextType> contype = SimulationContext
+ .selectTypesWhere(sprop);
+ if (contype.isEmpty())
+ return; // No approved property type configured at this step
+
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ List<SimulationContext> context = to.getAllSimulationContexts();
+
+ context = new ArrayList<SimulationContext>(context.size());
+ context.addAll(to.getAllSimulationContexts());
+ cprop.disableCheck();
+ for (Iterator<SimulationContextType> i = contype.iterator(); i
+ .hasNext();) {
+ SimulationContextType property = i.next();
+ for (Iterator<SimulationContext> j = context.iterator(); j
+ .hasNext();) {
+ SimulationContext existing = j.next();
+ if (!existing.getType().equals(property))
+ continue;
+ property = null; // Forget this property as it is already set
+ break;
+ }
+ if (property != null)
+ try {
+ String value = tool.extractProperty(property.getName());
+ if (value == null)
+ continue; // Property not defined into the document
+
+ cprop.setType(property).setValue(value);
+ if (aPublication.getOwner() instanceof Study)
+ getStudyService().addProjectContext(
+ (Study) aPublication.getOwner(), cprop); // Re-indexes knowledges and the study
+ else
+ getStepService().addSimulationContext(to, cprop); // Re-indexes knowledges only
+ } catch (Exception e) {
+ break;
+ }
+ }
+ }
+
+ /**
+ * Returns the study Step into which the document version referenced by this publication has been published.
+ */
+ public Step getInvolvedStep(Publication aPublication) {
+ if (aPublication.getStep() == null) {
+ Step[] step = getProjectElementService().getSteps(aPublication.getOwner());
+ for (int i = 0; i < step.length; i++) {
+ aPublication.setStep(step[i]); // The involved step necessarily exists
+ if (aPublication.value().isInto(aPublication.getStep()))
+ break;
+ }
+ }
+ return aPublication.getStep();
+ }
+
+ /**
+ * @return
+ */
+ private StepService getStepService() {
+ return _stepService;
+ }
+
+ public void setStepService(StepService stepService) {
+ _stepService = stepService;
+ }
+
+ /**
+ * @return
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
+
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
+ }
+
+ /**
+ * @return
+ */
+ public DocumentTypeService getDocumentTypeService() {
+ return _documentTypeService;
+ }
+
+ public void setDocumentTypeService(DocumentTypeService documentTypeService) {
+ _documentTypeService = documentTypeService;
+ }
+
+ /**
+ * Get the projectElementService.
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ * @param projectElementService the projectElementService to set
+ */
+ public void setProjectElementService(ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public interface ScenarioService {
+
+ public KnowledgeElement addKnowledgeElement(Scenario aScenario,
+ KnowledgeElement.Properties kprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException;
+
+ public void checkin(Scenario aScenario);
+
+ public void copyContentsUpTo(Scenario scenario, Step lastep);
+
+ public boolean isEmpty(Scenario scenario);
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.io.IOException;
+import java.util.Calendar;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.KnowledgeElement;
+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.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.service.technical.IndexService;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public class ScenarioServiceImpl implements ScenarioService {
+
+ protected final static Logger logger = Logger
+ .getLogger(ScenarioServiceImpl.class);
+
+ private IndexService _indexService;
+ private StepService _stepService;
+ private PublicationService _publicationService;
+ private ProjectElementService _projectElementService;
+
+ /**
+ * Get the projectElementService.
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ * @param projectElementService the projectElementService to set
+ */
+ public void setProjectElementService(ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
+
+ /**
+ * Get the publicationService.
+ * @return the publicationService
+ */
+ public PublicationService getPublicationService() {
+ return _publicationService;
+ }
+
+ /**
+ * Set the publicationService.
+ * @param publicationService the publicationService to set
+ */
+ public void setPublicationService(PublicationService publicationService) {
+ _publicationService = publicationService;
+ }
+
+ /**
+ * Get the stepService.
+ * @return the stepService
+ */
+ public StepService getStepService() {
+ return _stepService;
+ }
+
+ /**
+ * Set the stepService.
+ * @param stepService the stepService to set
+ */
+ public void setStepService(StepService stepService) {
+ _stepService = stepService;
+ }
+
+ public KnowledgeElement addKnowledgeElement(Scenario aScenario,
+ KnowledgeElement.Properties kprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException {
+ // -------------------------------------------------------------------------------
+ KnowledgeElement kelm = new KnowledgeElement(
+ kprop.setOwnerScenario(aScenario));
+ Session session = Database.getSession();
+ Transaction transax = session.getTransaction();
+ try {
+ session.save(kelm);
+ // Update of my persistent data
+ aScenario.getKnowledgeElements().add(kelm);
+ // Update of my transient data
+ List<KnowledgeElement> known = aScenario
+ .getKnowledgeElementsOf(kelm.getType()); // Initializes this.known, if not yet done
+ known.add(kelm);
+ if (kelm.getType().equals("usecase")) {
+ aScenario.setUcase(kelm);
+ } else if (aScenario.getKnowledgeElementsList() != null) { // If null, knowl will be initialized when needed
+ aScenario.getKnowledgeElementsList().add(kelm);
+ }
+ // Update of the index of Knowledge Elements
+ getIndexService().add(kelm);
+ update(aScenario);
+ return kelm;
+ } catch (RuntimeException e) {
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException error) {
+ logger.debug("Error rolling back transaction", error);
+ }
+ // Throw again the first exception
+ throw e;
+ }
+ return null;
+ } catch (IOException error) {
+ logger.error(
+ "Unable to index the knowedge element '" + kelm.getIndex()
+ + "', reason:", error);
+ return null;
+ }
+ }
+
+ private boolean update(Scenario aScenario) {
+ // ---------------------------
+ try {
+ Database.getSession().update(aScenario); // Update of relational base
+ return true;
+ } catch (Exception error) {
+ logger.error("Unable to re-index the knowledge element '"
+ + aScenario.getIndex() + "', reason:", error);
+ return false;
+ }
+ }
+
+ /**
+ * @return
+ */
+ public IndexService getIndexService() {
+ return _indexService;
+ }
+
+ public void setIndexService(IndexService indexService) {
+ _indexService = indexService;
+ }
+
+ public void checkin(Scenario aScenario) {
+ // ----------------------
+ aScenario.setUser(null);
+ aScenario.setLastModificationDate(Calendar.getInstance().getTime());
+ Database.getSession().update(aScenario);
+ }
+
+ public boolean checkout(Scenario aScenario, User user) {
+ // -----------------------------------
+ if (!aScenario.getOwnerStudy().isStaffedBy(user))
+ return false;
+
+ aScenario.setUser(user);
+ aScenario.setLastModificationDate(Calendar.getInstance().getTime());
+ Database.getSession().update(this);
+ return true;
+ }
+
+ // ==============================================================================================================================
+ // Private services
+ // ==============================================================================================================================
+
+ public void copyContentsUpTo (Scenario scenario, Step lastep) {
+ // -------------------------------------------
+ Scenario base = (Scenario)lastep.getOwner();
+ Step[] from = getProjectElementService().getSteps(base);
+ Step[] to = getProjectElementService().getSteps(scenario);
+ for (int i=0; i<from.length; i++) {
+ Step step = from[i];
+ if (step.getNumber() > lastep.getNumber()) break;
+
+ List<Publication> docs = step.getAllDocuments();
+ for (Iterator<Publication> j=docs.iterator(); j.hasNext(); ) {
+ Publication doc = getPublicationService().copy(j.next(), scenario); // Creation of a new reference to the document
+ // Database.getSession().save(doc); Publications MUST be saved later through cascading when saving the scenario
+ to[i].add(doc);
+ }
+ List<SimulationContext> ctex = step.getAllSimulationContexts();
+ for (Iterator<SimulationContext> j=ctex.iterator(); j.hasNext(); ) {
+ getStepService().addSimulationContext(to[i], j.next());
+ }
+ }
+ }
+
+ public boolean isEmpty (Scenario scenario) {
+ // -------------------------
+ Step[] mystep = getProjectElementService().getSteps(scenario);
+ for (int i=0; i<mystep.length; i++) if (mystep[i].isStarted()) return false;
+ return true;
+ }
+
+ public boolean isFinished (Scenario scenario) {
+ // ----------------------------
+ Step[] mystep = getProjectElementService().getSteps(scenario);
+ boolean notempty = false; // If this is empty, this is not finished
+ for (int i=0; i<mystep.length; i++) {
+ if (!mystep[i].isStarted()) continue;
+ if (!mystep[i].isFinished()) return false;
+ notempty = true;
+ }
+ return notempty;
+ }
+
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 05.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.util.List;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.Study;
+import org.splat.service.dto.Proxy;
+
+/**
+ * @author rkv
+ *
+ */
+public interface SearchService {
+
+ public List<Proxy> selectKnowledgeElementsWhere (KnowledgeElement.Properties... kprop);
+ public List<Proxy> selectStudiesWhere (Study.Properties... sprop);
+ public void indexStudy (Study study);
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 05.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanFilter;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.FilterClause;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.SortField;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TermsFilter;
+import org.apache.lucene.search.TopFieldDocs;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FSDirectory;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.Visibility;
+import org.splat.dal.bo.som.Study.Properties;
+import org.splat.dal.dao.som.Database;
+import org.splat.service.dto.Proxy;
+import org.splat.service.technical.IndexService;
+import org.splat.service.technical.IndexServiceImpl;
+import org.splat.service.technical.RepositoryService;
+
+/**
+ * @author rkv
+ *
+ */
+public class SearchServiceImpl implements SearchService {
+
+ public final static Logger logger = org.splat.service.SearchServiceImpl.logger;
+
+ private RepositoryService _repositoryService;
+
+ private IndexService _indexService;
+
+ public List<Proxy> selectKnowledgeElementsWhere (KnowledgeElement.Properties... kprop) {
+ // ---------------------------------------------------------------------------------------------
+ List<Proxy> result = new ArrayList<Proxy>();
+ int hitsize = 20;
+ try {
+
+ // Creation of the Lucene query
+ File indir = getRepositoryService().getRepositoryIndexDirectory();
+ Directory index = FSDirectory.open(indir);
+ IndexSearcher searcher = new IndexSearcher(index, true);
+ BooleanQuery fulquery = new BooleanQuery();
+
+ for (int i=0; i<kprop.length; i++) {
+ BooleanQuery query = new BooleanQuery();
+ Term input; // Supposed initialized below at least by the visibility
+
+ Visibility area = kprop[i].getVisibility(); // Visibility
+ if (area != null) {
+ input = new Term("area");
+ query.add(new TermQuery(input.createTerm(area.toString())), BooleanClause.Occur.MUST);
+ }
+ ProgressState state = kprop[i].getProgressState(); // State
+ if (state != null) {
+ input = new Term("state");
+ query.add(new TermQuery(input.createTerm(state.toString())), BooleanClause.Occur.MUST);
+ }
+ String refid = kprop[i].getReference(); // Reference
+ if (refid != null) {
+ input = new Term("ref");
+ query.add(new TermQuery(input.createTerm(refid)), BooleanClause.Occur.MUST);
+ }
+ KnowledgeElementType type = kprop[i].getType(); // Type
+ if (type != null) {
+ input = new Term("type");
+ query.add(new TermQuery(input.createTerm(type.getName())), BooleanClause.Occur.MUST);
+ }
+ User manager = kprop[i].getAuthor(); // Author
+ if (manager != null) {
+ input = new Term("author");
+ query.add(new TermQuery(input.createTerm(manager.toString())), BooleanClause.Occur.MUST);
+ }
+ User actor = kprop[i].getActor(); // Contributor, Reviewer or Approver of the owner study
+ if (actor != null) {
+ input = new Term("actor");
+ query.add(new TermQuery(input.createTerm(actor.toString())), BooleanClause.Occur.MUST);
+ }
+ String title = kprop[i].getTitle(); // Title
+ if (title != null) {
+ input = new Term("contents");
+ BooleanQuery critext = new BooleanQuery();
+ String operator = "AND"; // Future user input
+ BooleanClause.Occur clause = BooleanClause.Occur.MUST;
+ if (operator.equals("OR")) clause = BooleanClause.Occur.SHOULD;
+ String[] word = title.split(" ");
+ for (int j=0; j<word.length; j++) {
+ critext.add(new TermQuery(input.createTerm(word[j])), clause);
+ }
+ query.add(critext, BooleanClause.Occur.MUST);
+ }
+ List<SimulationContext> context = kprop[i].getSimulationContexts();
+ if (context != null && context.size() > 0) {
+ BooleanQuery critext = new BooleanQuery();
+ for (Iterator<SimulationContext> j=context.iterator(); j.hasNext();) {
+ SimulationContext seltext = j.next();
+ input = new Term(String.valueOf(seltext.getType().getIndex()));
+ critext.add(new TermQuery(input.createTerm(seltext.getValue())), BooleanClause.Occur.MUST);
+ }
+ query.add(critext, BooleanClause.Occur.MUST);
+ }
+ fulquery.add(query, BooleanClause.Occur.SHOULD);
+ }
+ if (logger.isInfoEnabled()) {
+ logger.info("Searching knowledges by Lucene query \"" + fulquery.toString() + "\".");
+ }
+ // Creation of the knowledge filter
+ BooleanFilter filter = new BooleanFilter();
+ TermsFilter select = new TermsFilter();
+ Term mytype = new Term("class");
+ select.addTerm( mytype.createTerm("KnowledgeElement") );
+ filter.add(new FilterClause(select, BooleanClause.Occur.SHOULD));
+
+ // Creation of the sort criteria
+ Sort sort = new Sort(new SortField("title", SortField.STRING));
+
+ // Search
+ TopFieldDocs found = searcher.search(fulquery, filter, hitsize, sort);
+
+ if (found.totalHits < 1) return result; // No study found
+
+ // Construction of the result list
+ ScoreDoc[] hits = found.scoreDocs;
+ for (int i=0; i<hits.length; i++) {
+ result.add( new IndexServiceImpl.ObjectProxy(searcher.doc(hits[i].doc)) );
+ }
+ searcher.close();
+ }
+ catch (Exception error) {
+ logger.error("Error during Lucene search, reason:", error);
+ }
+ return result;
+ }
+
+ public List<Proxy> selectStudiesWhere (Study.Properties... sprop) {
+ // ------------------------------------------------------------------------
+ List<Proxy> result = new ArrayList<Proxy>();
+ int hitsize = 20;
+ try {
+
+ // Creation of the Lucene query
+ File indir = getRepositoryService().getRepositoryIndexDirectory();
+ Directory index = FSDirectory.open(indir);
+ IndexSearcher searcher = new IndexSearcher(index, true);
+ BooleanQuery fulquery = new BooleanQuery();
+
+ for (int i=0; i<sprop.length; i++) {
+ BooleanQuery query = new BooleanQuery();
+ Term input; // Supposed initialized below at least by the visibility
+
+ Visibility area = sprop[i].getVisibility(); // Visibility
+ if (area != null) {
+ input = new Term("area");
+ query.add(new TermQuery(input.createTerm(area.toString())), BooleanClause.Occur.MUST);
+ }
+ ProgressState state = sprop[i].getProgressState(); // State
+ if (state != null) {
+ input = new Term("state");
+ if (state == ProgressState.inPROGRESS) {
+ BooleanQuery cristate = new BooleanQuery();
+ cristate.add(new TermQuery(input.createTerm("inWORK")), BooleanClause.Occur.SHOULD);
+ cristate.add(new TermQuery(input.createTerm("inDRAFT")), BooleanClause.Occur.SHOULD);
+ cristate.add(new TermQuery(input.createTerm("inCHECK")), BooleanClause.Occur.SHOULD);
+ query.add(cristate, BooleanClause.Occur.MUST);
+ } else {
+ query.add(new TermQuery(input.createTerm(state.toString())), BooleanClause.Occur.MUST);
+ }
+ }
+ String refid = sprop[i].getReference(); // Reference
+ if (refid != null) {
+ input = new Term("ref");
+ query.add(new TermQuery(input.createTerm(refid)), BooleanClause.Occur.MUST);
+ }
+ User manager = sprop[i].getManager(); // Author
+ if (manager != null) {
+ input = new Term("author");
+ query.add(new TermQuery(input.createTerm(manager.toString())), BooleanClause.Occur.MUST);
+ }
+ User actor = sprop[i].getActor(); // Contributor, Reviewer or Approver
+ if (actor != null) {
+ input = new Term("actor");
+ query.add(new TermQuery(input.createTerm(actor.toString())), BooleanClause.Occur.MUST);
+ }
+ String title = sprop[i].getTitle(); // Title
+ if (title != null) {
+ input = new Term("contents");
+ BooleanQuery critext = new BooleanQuery();
+ String operator = "AND"; // Future user input
+ BooleanClause.Occur clause = BooleanClause.Occur.MUST;
+ if (operator.equals("OR")) clause = BooleanClause.Occur.SHOULD;
+ String[] word = title.split(" ");
+ for (int j=0; j<word.length; j++) {
+ critext.add(new TermQuery(input.createTerm(word[j])), clause);
+ }
+ query.add(critext, BooleanClause.Occur.MUST);
+ }
+ List<SimulationContext> context = sprop[i].getSimulationContexts();
+ if (context != null && context.size() > 0) {
+ BooleanQuery critext = new BooleanQuery();
+ for (Iterator<SimulationContext> j=context.iterator(); j.hasNext();) {
+ SimulationContext seltext = j.next();
+ input = new Term(String.valueOf(seltext.getType().getIndex()));
+ critext.add(new TermQuery(input.createTerm(seltext.getValue())), BooleanClause.Occur.MUST);
+ }
+ query.add(critext, BooleanClause.Occur.MUST);
+ }
+ fulquery.add(query, BooleanClause.Occur.SHOULD);
+ }
+ if (logger.isInfoEnabled()) {
+ logger.info("Searching studies by Lucene query \"" + fulquery.toString() + "\".");
+ }
+ // Creation of the studies filter
+ BooleanFilter filter = new BooleanFilter();
+ TermsFilter select = new TermsFilter();
+ Term mytype = new Term("class");
+ select.addTerm( mytype.createTerm("Study") );
+ filter.add(new FilterClause(select, BooleanClause.Occur.SHOULD));
+
+ // Creation of the sort criteria
+ Sort sort = new Sort(new SortField("title", SortField.STRING));
+
+ // Search
+ TopFieldDocs found = searcher.search(fulquery, filter, hitsize, sort);
+
+ if (found.totalHits < 1) return result; // No study found
+
+ // Construction of the result list
+ ScoreDoc[] hits = found.scoreDocs;
+ for (int i=0; i<hits.length; i++) {
+ result.add( new IndexServiceImpl.ObjectProxy(searcher.doc(hits[i].doc)) );
+ }
+ searcher.close();
+ }
+ catch (Exception error) {
+ logger.error("Error during Lucene search, reason:", error);
+ }
+ return result;
+ }
+
+ public void indexStudy (Study study) {
+ // -------------------------------------------
+ try {
+ Study.Properties sprop = new Study.Properties();
+ List<Proxy> index = selectStudiesWhere(sprop.setReference(study.getReference()));
+
+ if (index.size() != 0) return; // The given study is already indexed
+
+ IndexService lucin = getIndex();
+ Scenario[] scenes = study.getScenarii();
+
+ lucin.add(study);
+ if (study.getProgressState() != ProgressState.inWORK) for (int i=0; i<scenes.length; i++) {
+ List<KnowledgeElement> list = scenes[i].getAllKnowledgeElements();
+ for (Iterator<KnowledgeElement> j=list.iterator(); j.hasNext(); ) {
+ lucin.add(j.next());
+ }
+ }
+ }
+ catch (Exception error) {
+ Database.logger.error("Unable to index the study '" + study.getIndex() + "', reason:", error);
+ }
+ }
+
+ public IndexService getIndex () throws IOException {
+ IndexService lucin = getIndexService();
+ if ( !lucin.exists() ) lucin.create(); // Happens when re-indexing all studies
+ return lucin;
+ }
+
+ /**
+ * Get the repositoryService.
+ * @return the repositoryService
+ */
+ public RepositoryService getRepositoryService() {
+ return _repositoryService;
+ }
+
+ /**
+ * Set the repositoryService.
+ * @param repositoryService the repositoryService to set
+ */
+ public void setRepositoryService(RepositoryService repositoryService) {
+ _repositoryService = repositoryService;
+ }
+
+ /**
+ * Get the indexService.
+ * @return the indexService
+ */
+ public IndexService getIndexService() {
+ return _indexService;
+ }
+
+ /**
+ * Set the indexService.
+ * @param indexService the indexService to set
+ */
+ public void setIndexService(IndexService indexService) {
+ _indexService = indexService;
+ }
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public interface StepService {
+
+ public SimulationContext addSimulationContext(Step aStep,
+ SimulationContext.Properties dprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException,
+ RuntimeException;
+
+ /**
+ * @param firstStep
+ * @param context
+ * @return
+ */
+ public SimulationContext addSimulationContext(Step firstStep,
+ SimulationContext context);
+
+ public boolean removeSimulationContext(Step aStep, SimulationContext context);
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.service.technical.IndexService;
+import org.splat.service.technical.IndexServiceImpl;
+import org.splat.som.Step;
+
+/**
+ * @author RKV
+ *
+ */
+public class StepServiceImpl implements StepService {
+
+ private IndexService _indexService;
+
+ public SimulationContext addSimulationContext(Step aStep,
+ SimulationContext.Properties dprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException,
+ RuntimeException {
+ // ----------------------------------------------------------------------------------
+ SimulationContext context = new SimulationContext(dprop.setStep(aStep
+ .getStep()));
+ return addSimulationContext(aStep, context);
+ }
+
+ public SimulationContext addSimulationContext(Step aStep,
+ SimulationContext context) {
+ // -------------------------------------------------------------------------
+ context.hold(); // Increments the reference count of simulation context
+ if (aStep.getOwner().isSaved())
+ try {
+ Session session = Database.getSession();
+ IndexService lucin = getIndexService();
+
+ if (!context.isSaved())
+ session.save(context);
+ aStep.getOwner().add(context);
+ aStep.getContex().add(context); // The context is also referenced from this (transient) Step
+ session.update(aStep.getOwner());
+ updateKnowledgeElementsIndex(aStep, lucin);
+ } catch (Exception error) {
+ return null;
+ }
+ else { // Happens when copying a scenario
+ aStep.getOwner().add(context);
+ aStep.getContex().add(context); // The context is also referenced from this (transient) Step
+ // In case of owner scenario, the Knowledge Element index will be updated later, when saving the scenario
+ }
+ return context;
+ }
+
+ private void updateKnowledgeElementsIndex(Step aStep, IndexService lucin) {
+ // ------------------------------------------------------
+ Scenario[] scenarii;
+ if (aStep.getOwner() instanceof Scenario) {
+ scenarii = new Scenario[1];
+ scenarii[0] = (Scenario) aStep.getOwner();
+ } else {
+ scenarii = aStep.getOwnerStudy().getScenarii();
+ }
+ try {
+ for (int i = 0; i < scenarii.length; i++) {
+ Scenario scene = scenarii[i];
+ List<KnowledgeElement> knelm = scene.getAllKnowledgeElements();
+ for (Iterator<KnowledgeElement> j = knelm.iterator(); j
+ .hasNext();) {
+ KnowledgeElement kelm = j.next();
+ lucin.update(kelm);
+ }
+ scene.updateMyIndex(lucin);
+ }
+ } catch (Exception error) {
+ // logger.error("Unable to re-index Knowledge Elements, reason:", error);
+ }
+ }
+
+ public boolean removeSimulationContext (Step aStep, SimulationContext context) {
+// ------------------------------------------------------------------
+ SimulationContext torem = aStep.getSimulationContext(context.getIndex());
+ Session session = Database.getSession();
+
+ if (torem == null) return false;
+ if (!aStep.getOwner().remove(torem)) return false;
+
+ aStep.getContex().remove(torem);
+ session.update(aStep.getOwner());
+ if (torem.isShared()) {
+ torem.release();
+ session.update(torem);
+ } else {
+ session.delete(torem);
+ }
+ return true;
+ }
+
+ /**
+ * @return
+ */
+ public IndexService getIndexService() {
+ return _indexService;
+ }
+
+ public void setIndexService(IndexService indexService) {
+ _indexService = indexService;
+ }
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.ValidationCycle;
+import org.splat.dal.bo.som.Study.Properties;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+
+/**
+ * @author RKV
+ *
+ */
+public interface StudyService {
+
+ public int generateLocalIndex(Study aStudy);
+
+ public Study createStudy(Study.Properties sprop)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, RuntimeException;
+
+ public SimulationContext addProjectContext(Study aStudy,
+ SimulationContext.Properties cprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException,
+ RuntimeException;
+
+ public SimulationContext addProjectContext(Study aStudy,
+ SimulationContext context);
+
+ public Scenario addScenario(Study aStudy, Scenario.Properties sprop)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, RuntimeException;
+
+ public boolean removeProjectContext(Study aStudy, SimulationContext context);
+
+ /**
+ * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
+ * document of the study.
+ *
+ * @return true if the demotion succeeded.
+ */
+ public boolean demote(Study aStudy);
+
+ /**
+ * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
+ * final result document of the study.
+ *
+ * @return true if the demotion succeeded.
+ */
+ public boolean promote(Study aStudy);
+
+ public boolean addContributor(Study aStudy, User user);
+
+ public boolean removeContributor(Study aStudy, User... users);
+
+ public void setValidationCycle(Study aStudy, DocumentType type,
+ ValidationCycle.Properties vprop);
+
+ /**
+ * Moves this study from the Private to the Public area of the repository.
+ *
+ * @return true if the move succeeded.
+ * @see #isPublic()
+ */
+ public boolean moveToPublic(Study aStudy);
+
+ /**
+ * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
+ * previously be approved.
+ *
+ * @return true if the move succeeded.
+ * @see #moveToPublic()
+ * @see #isPublic()
+ * @see Publication#approve(Date)
+ */
+ public boolean moveToReference(Study aStudy);
+
+ public boolean update(Study aStudy, Properties sprop)
+ throws InvalidPropertyException;
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.hibernate.Session;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.ActorRelation;
+import org.splat.dal.bo.som.ContributorRelation;
+import org.splat.dal.bo.som.DescriptionAttribute;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.IDBuilder;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.ValidationCycle;
+import org.splat.dal.bo.som.ValidationCycleRelation;
+import org.splat.dal.bo.som.Visibility;
+import org.splat.dal.bo.som.Study.Properties;
+import org.splat.dal.dao.som.Database;
+import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.UserDirectory;
+import org.splat.service.technical.IndexService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.som.Revision;
+
+/**
+ * @author RKV
+ *
+ */
+public class StudyServiceImpl implements StudyService {
+
+ public final static Logger logger = org.splat.service.StudyServiceImpl.logger;
+
+ private IndexService _indexService;
+
+ private StepService _stepService;
+
+ private ScenarioService _scenarioService;
+
+ private ProjectSettingsService _projectSettingsService;
+
+ private ProjectElementService _projectElementService;
+
+ public Study createStudy(Study.Properties sprop)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, RuntimeException {
+ sprop.setReference(getProjectSettings().getReferencePattern());
+ Study study = new Study(sprop);
+
+ buildReference(study);
+ Database.getSession().save(study); // TODO: use StudyDAO and throw out Database.
+ try {
+ IndexService lucin = getIndex();
+ lucin.add(study);
+ } catch (IOException error) {
+ logger.error("Unable to index the study '" + study.getIndex()
+ + "', reason:", error);
+ // Continue and try to index later
+ }
+ return study;
+ }
+
+ public IndexService getIndex() throws IOException {
+ IndexService lucin = getIndexService();
+ if (!lucin.exists())
+ lucin.create(); // Happens when re-indexing all studies
+ return lucin;
+ }
+
+ public SimulationContext addProjectContext(Study aStudy,
+ SimulationContext.Properties cprop) throws MissedPropertyException,
+ InvalidPropertyException, MultiplyDefinedException,
+ RuntimeException {
+ // -------------------------------------------------------------------------------
+ SimulationContext added = getStepService().addSimulationContext(
+ getProjectElementService().getFirstStep(aStudy), cprop);
+ update(aStudy);
+ return added;
+ }
+
+ /**
+ * @return
+ */
+ public StepService getStepService() {
+ return _stepService;
+ }
+
+ public void setStepService(StepService stepService) {
+ _stepService = stepService;
+ }
+
+ public SimulationContext addProjectContext(Study aStudy,
+ SimulationContext context) {
+ // ----------------------------------------------------------------------
+ SimulationContext added = getStepService().addSimulationContext(
+ getProjectElementService().getFirstStep(aStudy), context);
+ update(aStudy);
+ return added;
+ }
+
+ public boolean addContributor(Study aStudy, User user) {
+ // -----------------------------------------
+ List<User> contributor = aStudy.getModifiableContributors(); // Initializes contributor
+ for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
+ User present = i.next();
+ if (present.equals(user))
+ return false;
+ }
+ boolean absent = aStudy.getModifiableActors().add(user); // User may already be a reviewer or an approver
+
+ aStudy.addRelation(new ContributorRelation(aStudy, user));
+ if (absent)
+ update(aStudy); // Else, useless to re-index the study
+ contributor.add(user);
+ return true;
+ }
+
+ /**
+ * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
+ * previously be approved.
+ *
+ * @return true if the move succeeded.
+ * @see #moveToPublic()
+ * @see #isPublic()
+ * @see Publication#approve(Date)
+ */
+ public boolean moveToReference(Study aStudy) {
+ // ---------------------------------
+ if (aStudy.getProgressState() != ProgressState.APPROVED)
+ return false;
+ if (aStudy.getVisibility() != Visibility.PUBLIC)
+ return false;
+
+ aStudy.setVisibility(Visibility.REFERENCE);
+ if (update(aStudy)) {
+ return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
+ }
+ return false;
+ }
+
+ public boolean update(Study aStudy, Properties sprop)
+ throws InvalidPropertyException {
+ if (sprop.getTitle() != null)
+ aStudy.setTitle(sprop.getTitle());
+ if (sprop.getSummary() != null)
+ aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
+ .getSummary()));
+ // TODO: To be completed
+ return update(aStudy);
+ }
+
+ public boolean buildReference(Study aStudy) {
+ String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
+ IDBuilder tool = Database.selectIDBuilder(aStudy.getDate());
+ if (tool == null) {
+ tool = new IDBuilder(aStudy.getDate());
+ Database.getSession().save(tool);
+ }
+ aStudy.setReference(tool.buildReference(pattern, aStudy));
+ return true;
+ }
+
+ public boolean publishes(Study aStudy, 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;
+ }
+
+ public boolean removeContributor(Study aStudy, User... users) {
+ // ------------------------------------------------
+ List<User> contributor = aStudy.getModifiableContributors(); // Initializes contributor
+ Boolean done = false;
+ for (int i = 0; i < users.length; i++) {
+ User user = users[i];
+ for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
+ User present = j.next();
+ if (!present.equals(user))
+ continue;
+
+ aStudy.removeRelation(ContributorRelation.class, user);
+ j.remove(); // Updates the contributor shortcut
+ done = true;
+ break;
+ }
+ }
+ if (done)
+ update(aStudy);
+ return done;
+ }
+
+ public boolean removeProjectContext(Study aStudy, SimulationContext context) {
+ // ---------------------------------------------------------------
+ boolean done = getStepService().removeSimulationContext(
+ getProjectElementService().getFirstStep(aStudy), context);
+ update(aStudy);
+ return done;
+ }
+
+ public void setValidationCycle(Study aStudy, DocumentType type,
+ ValidationCycle.Properties vprop) {
+ HashMap<String, ValidationCycle> validactor = aStudy
+ .getValidationCycles();
+ if (validactor == null)
+ aStudy.setShortCuts(); // Initializes validactor and actor
+
+ String cname = type.getName();
+ ValidationCycle cycle = validactor.get(cname);
+
+ if (cycle != null && cycle.isAssigned()) {
+ cycle.resetActors(vprop);
+ } else
+ try {
+ cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
+
+ ValidationCycleRelation link = cycle.getContext();
+ aStudy.addRelation(link);
+ validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
+ } catch (Exception error) {
+ logger.error("Unable to re-index Knowledge Elements, reason:",
+ error);
+ return;
+ }
+ resetActorsShortCut(aStudy);
+ update(aStudy); // Re-index the study, just in case
+ }
+
+ private void resetActorsShortCut(Study aStudy) {
+ aStudy.getModifiableActors().clear();
+ // Get all actors involved in validation cycles
+ for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
+ .values().iterator(); i.hasNext();) {
+ ValidationCycle cycle = i.next();
+ User[] user = cycle.getAllActors();
+ for (int j = 0; j < user.length; j++)
+ aStudy.getModifiableActors().add(user[j]);
+ }
+ // Get all other actors
+ for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
+ .hasNext();) {
+ Relation link = i.next();
+ Class<?> kindof = link.getClass().getSuperclass();
+ if (!kindof.equals(ActorRelation.class))
+ continue;
+ aStudy.getModifiableActors().add(((ActorRelation) link).getTo());
+ }
+ }
+
+ /**
+ * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
+ * document of the study.
+ *
+ * @return true if the demotion succeeded.
+ */
+ public boolean demote(Study aStudy) {
+ // ---------------------------
+ if (aStudy.getProgressState() == ProgressState.inCHECK)
+ aStudy.setProgressState(ProgressState.inDRAFT);
+ else if (aStudy.getProgressState() == ProgressState.inDRAFT)
+ aStudy.setProgressState(ProgressState.inWORK);
+ else
+ return false;
+ return update(aStudy);
+ }
+
+ public int generateLocalIndex(Study aStudy) {
+ aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
+ Database.getSession().update(this);
+ return aStudy.getLastLocalIndex();
+ }
+
+ // ==============================================================================================================================
+ // Public member functions
+ // ==============================================================================================================================
+
+ public Scenario addScenario(Study aStudy, Scenario.Properties sprop)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, RuntimeException {
+ // -------------------------------------------------------
+ if (sprop.getManager() == null)
+ sprop.setManager(aStudy.getAuthor());
+
+ Scenario scenario = new Scenario(sprop.setOwnerStudy(aStudy));
+ if (sprop.getBaseStep() != null)
+ getScenarioService()
+ .copyContentsUpTo(scenario, sprop.getBaseStep());
+ Scenario previous = sprop.getInsertAfter();
+ Session session = Database.getSession();
+
+ if (previous == null) {
+ aStudy.getScenariiList().add(scenario);
+ } else {
+ aStudy.getScenariiList().add(
+ aStudy.getScenariiList().indexOf(previous) + 1, scenario);
+ }
+ session.update(this); // No need to update the Lucene index
+ session.save(scenario); // Must be done after updating this study because of the back reference to the study
+ if (sprop.getBaseStep() != null) {
+ // No need to update the Knowledge Element index as Knowledge Elements are not copied
+ scenario.refresh(); // Because saving the scenario changes the hashcode of copied Publications
+ }
+ KnowledgeElementType ucase = KnowledgeElement.selectType("usecase");
+ KnowledgeElement.Properties kprop = new KnowledgeElement.Properties();
+ User admin = UserDirectory.selectUser(1); // First user created when creating the database
+ kprop.setType(ucase).setTitle(aStudy.getTitle())
+ .setValue(scenario.getTitle()).setAuthor(admin); // Internal Knowledge Element required by the validation process of
+ // knowledges
+ getScenarioService().addKnowledgeElement(scenario, kprop);
+ return scenario;
+ }
+
+ /**
+ * @return
+ */
+ private ScenarioService getScenarioService() {
+ return _scenarioService;
+ }
+
+ public void setScenarioService(ScenarioService scenarioService) {
+ _scenarioService = scenarioService;
+ }
+
+ /**
+ * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
+ * final result document of the study.
+ *
+ * @return true if the demotion succeeded.
+ */
+ public boolean promote(Study aStudy) {
+ // ----------------------------
+ if (aStudy.getProgressState() == ProgressState.inWORK) {
+ aStudy.setProgressState(ProgressState.inDRAFT);
+ } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
+ aStudy.setProgressState(ProgressState.inCHECK);
+ Revision myvers = new Revision(aStudy.getVersion());
+ if (myvers.isMinor()) {
+ aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
+ .toString());
+ }
+ } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
+ aStudy.setProgressState(ProgressState.APPROVED);
+ } else
+ return false;
+
+ return update(aStudy);
+ }
+
+ /**
+ * Moves this study from the Private to the Public area of the repository.
+ *
+ * @return true if the move succeeded.
+ * @see #isPublic()
+ */
+ public boolean moveToPublic(Study aStudy) {
+ // ------------------------------
+ if (aStudy.getVisibility() != Visibility.PRIVATE)
+ return false;
+
+ aStudy.setVisibility(Visibility.PUBLIC);
+ if (update(aStudy)) {
+ return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
+ }
+ return false;
+ }
+
+ private boolean update(Study aStudy) {
+ try {
+ Database.getSession().update(aStudy); // Update of relational base
+ getIndex().update(aStudy); // Update of Lucene index
+ return true;
+ } catch (Exception error) {
+ logger.error("Unable to re-index the study '" + aStudy.getIndex()
+ + "', reason:", error);
+ return false;
+ }
+ }
+
+ private boolean updateKnowledgeElementsIndex(Study aStudy) {
+ // ----------------------------------------------
+ try {
+ IndexService lucin = getIndex();
+
+ for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
+ .hasNext();) {
+ Scenario scene = i.next();
+ for (Iterator<KnowledgeElement> j = scene
+ .getAllKnowledgeElements().iterator(); j.hasNext();) {
+ KnowledgeElement kelm = j.next();
+ lucin.update(kelm);
+ }
+ }
+ return true;
+ } catch (Exception error) {
+ logger.error("Unable to re-index Knowledge Elements, reason:",
+ error);
+ return false;
+ }
+ }
+
+ /**
+ * @return
+ */
+ public IndexService getIndexService() {
+ return _indexService;
+ }
+
+ public void setIndexService(IndexService indexService) {
+ _indexService = indexService;
+ }
+
+ /**
+ * Get project settings.
+ *
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ *
+ * @param projectSettingsService
+ * project settings service
+ */
+ public void setProjectSettings(ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
+}
--- /dev/null
+package org.splat.service.dto;
+
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.dao.som.Database;
+
+
+import org.splat.service.technical.IndexServiceImpl;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.Study.Properties;
+
+/**
+ * Stand proxy for entities such as Study and Knowledge Element returned by Lucene-based searches.
+ * This interface provides access to properties of searched entities which can be presented in a result search list
+ * before loading the corresponding persistent objects from the database (reason for most properties to be returned as
+ * strings).
+ * One of these properties is the internal persistent identifier of the object represented by a proxy allowing the
+ * user of this interface to load the object from the database.
+ *
+ * @see Database#selectStudiesWhere(Study.Properties...)
+ * @see Database#selectKnowledgeElementsWhere(KnowledgeElement.Properties)
+ * @see Database#selectStudy(int)
+ * @see Database#selectKnowledgeElement(int)
+ * @see IndexServiceImpl
+ * @see IndexServiceImpl.ObjectProxy
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+public interface Proxy {
+
+ public String getAuthorName ();
+
+/**
+ * Returns the internal persistent identifier of the object represented by this proxy. The returned identifier can be used
+ * for selecting the corresponding persistent object from the database.
+ * @return the internal persistent identifier of the object represented by this proxy.
+ */
+ public Integer getIndex ();
+
+ public ProgressState getProgressState ();
+
+/**
+ * Returns the external reference number of the object represented by this proxy. The returned reference is formated
+ * according to the format defined in the configuration file of the application.
+ * @return the external reference number of the object represented by this proxy.
+ */
+ public String getReference ();
+
+ public String getTitle ();
+
+/**
+ * Returns the type of the object represented by this proxy. Depending on the implementation, the returned type may or
+ * may not be localized in the current locale of final user.
+ * @return the type of the object represented by this proxy.
+ */
+ public String getType ();
+}
\ No newline at end of file
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 05.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service.technical;
+
+/**
+ * @author rkv
+ *
+ */
+public interface DatabaseService {
+
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 05.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service.technical;
+
+/**
+ * @author rkv
+ *
+ */
+public class DatabaseServiceImpl implements DatabaseService {
+
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 05.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service.technical;
+
+import java.io.IOException;
+
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.Study;
+
+/**
+ * @author rkv
+ *
+ */
+public interface IndexService {
+
+ public void configure() throws IOException;
+
+ public void create() throws IOException;
+
+ public boolean exists();
+
+ public void add(KnowledgeElement kelm) throws IOException;
+
+ public void add(Study study) throws IOException;
+
+ public void update(Study study) throws IOException;
+
+ public void update(KnowledgeElement kelm) throws IOException;
+}
--- /dev/null
+package org.splat.service.technical;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.store.LockObtainFailedException;
+import org.apache.lucene.util.Version;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+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.dao.som.Database;
+import org.splat.service.ProjectElementService;
+import org.splat.service.dto.Proxy;
+import org.splat.som.Step;
+
+
+public class IndexServiceImpl implements IndexService {
+
+ private Directory index;
+ private org.apache.lucene.document.Document body;
+ private ProjectElementService _projectElementService;
+ private RepositoryService _repositoryService;
+
+ protected static StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
+ private static final Logger logger = Logger.getLogger(IndexServiceImpl.class);
+
+ private class Entry extends IndexWriter {
+// ---------------------------------------
+ private org.apache.lucene.document.Document entry;
+
+ private Entry (Study study) throws CorruptIndexException, LockObtainFailedException, IOException
+ {
+ super(index, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
+
+// Addition of mandatory fields
+ entry = new org.apache.lucene.document.Document();
+ Field field;
+ field = body.getField("index");
+ field.setValue(String.valueOf(study.getIndex()));
+ entry.add(field);
+ field = body.getField("class");
+ field.setValue("Study");
+ entry.add(field);
+ field = body.getField("type");
+ field.setValue(""); // Reserved for configurable Study type
+ entry.add(field);
+ field = body.getField("ref");
+ field.setValue(study.getReference());
+ entry.add(field);
+ field = body.getField("area");
+ field.setValue(study.getVisibility().toString());
+ entry.add(field);
+ field = body.getField("state");
+ field.setValue(study.getProgressState().toString());
+ entry.add(field);
+ field = body.getField("author");
+ field.setValue(study.getAuthor().toString());
+ entry.add(field);
+ field = body.getField("title");
+ field.setValue(study.getTitle());
+ entry.add(field);
+ field = body.getField("contents");
+ field.setValue(study.getTitle());
+ entry.add(field);
+
+// Addition of optional fields
+ setActorsOf(study);
+ setContextAt(getProjectElementService().getSteps(study));
+ }
+ private Entry (KnowledgeElement kelm) throws CorruptIndexException, LockObtainFailedException, IOException
+ {
+ super(index, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
+
+// Addition of mandatory fields
+ entry = new org.apache.lucene.document.Document();
+ Field field;
+ field = body.getField("index");
+ field.setValue(String.valueOf(kelm.getIndex()));
+ entry.add(field);
+ field = body.getField("class");
+ field.setValue("KnowledgeElement");
+ entry.add(field);
+ field = body.getField("type");
+ field.setValue(kelm.getType().getName());
+ entry.add(field);
+ field = body.getField("ref");
+ field.setValue(kelm.getReference());
+ entry.add(field);
+ field = body.getField("area");
+ field.setValue(kelm.getVisibility().toString());
+ entry.add(field);
+ field = body.getField("state");
+ field.setValue(kelm.getProgressState().toString());
+ entry.add(field);
+ field = body.getField("author");
+ field.setValue(kelm.getAuthor().toString());
+ entry.add(field);
+ field = body.getField("title");
+ field.setValue(kelm.getTitle());
+ entry.add(field);
+ field = body.getField("contents");
+ field.setValue(kelm.getTitle());
+ entry.add(field);
+
+//TODO: Addition of optional fields
+ Scenario scene = kelm.getOwnerScenario();
+ Study study = scene.getOwnerStudy();
+ setActorsOf(study); // For restricting the visibility of knowledges attached to private studies
+ setContextAt(getProjectElementService().getSteps(study));
+ setContextAt(getProjectElementService().getSteps(scene));
+ }
+ private void add () throws CorruptIndexException, IOException
+ {
+ addDocument(entry);
+// Save the new entry
+ optimize(); // Should be called before committing the index
+ close(); // Commits the index
+ }
+ private void update () throws CorruptIndexException, IOException
+ {
+ String value = entry.getField("ref").stringValue(); // Only field with unique value
+ Term term = new Term("ref").createTerm(value);
+ updateDocument(term, entry);
+// Save the updated entry
+ optimize(); // Should be called before committing the index
+ close(); // Commits the index
+ }
+ private void setContextAt (Step[] step)
+ {
+ for (int i=0; i<step.length; i++) {
+ List<SimulationContext> contexts = step[i].getAllSimulationContexts();
+ for (Iterator<SimulationContext> j=contexts.iterator(); j.hasNext();) {
+ SimulationContext context = j.next();
+ String type = String.valueOf(context.getType().getIndex());
+ String value = context.getValue();
+ entry.add( new Field(type, value, Field.Store.NO, Field.Index.NOT_ANALYZED) );
+ }
+ }
+ }
+ private void setActorsOf (Study study)
+ {
+ Set<User> actors = study.getActors();
+ for (Iterator<User> i=actors.iterator(); i.hasNext(); ) {
+ String value = i.next().toString();
+ entry.add( new Field("actor", value, Field.Store.NO, Field.Index.NOT_ANALYZED) );
+ }
+ }
+ }
+ public static class ObjectProxy implements Proxy, Serializable {
+// --------------------------------------------------------------
+ private int rid;
+ private String sid;
+ private ProgressState state;
+ private String title;
+ private String type;
+ private String name;
+ private static final long serialVersionUID = -4386494192709562221L;
+
+ public ObjectProxy (org.apache.lucene.document.Document ludoc) {
+ rid = Integer.valueOf(ludoc.get("index"));
+ sid = ludoc.get("ref");
+ state = ProgressState.valueOf(ludoc.get("state"));
+ title = ludoc.get("title");
+ name = ludoc.get("author");
+ }
+ public String getAuthorName () {
+ return name;
+ }
+ public Integer getIndex () {
+ return rid;
+ }
+ public ProgressState getProgressState () {
+ return state;
+ }
+ public String getReference () {
+ return sid;
+ }
+ public String getTitle () {
+ return title;
+ }
+ public String getType () {
+ return type;
+ }
+ }
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+ public void configure () throws IOException {
+ File indir = getRepositoryService().getRepositoryIndexDirectory();
+ index = FSDirectory.open(indir);
+ body = new org.apache.lucene.document.Document();
+ body.add( new Field("index", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("class", "", Field.Store.NO, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("type", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("ref", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("area", "", Field.Store.NO, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("state", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("author", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("title", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
+ body.add( new Field("contents","", Field.Store.NO, Field.Index.ANALYZED) );
+ if ( !this.exists() ) this.create(); // Happens when re-indexing all studies
+ }
+
+ public void create () throws IOException {
+// -------------------------------
+ Directory index = FSDirectory.open(getRepositoryService().getRepositoryIndexDirectory());
+ IndexWriter writer = new IndexWriter(index, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
+ writer.close(); // ==== Creates an empty index
+ }
+
+// ==============================================================================================================================
+// Member functions
+// ==============================================================================================================================
+
+ public void add (Study study) throws IOException {
+// --------------------------------
+ IndexServiceImpl.Entry entry = new Entry(study);
+ entry.add();
+ if (logger.isInfoEnabled()) {
+ logger.info("Study \"" + study.getIndex() + "\" indexed.");
+ }
+ }
+
+ public void add (KnowledgeElement kelm) throws IOException {
+// ------------------------------------------
+ IndexServiceImpl.Entry entry = new Entry(kelm);
+ entry.add();
+ if (logger.isInfoEnabled()) {
+ logger.info("Knowledge \"" + kelm.getIndex() + "\" indexed.");
+ }
+ }
+
+ public boolean exists () {
+// ---------------------------
+ try {
+ return IndexReader.indexExists(index);
+ }
+ catch (IOException error) {
+ error.printStackTrace();
+ return false;
+ }
+ }
+
+ public void update (Study study) throws IOException {
+// -----------------------------------
+ IndexServiceImpl.Entry entry = new Entry(study);
+ entry.update();
+ if (logger.isInfoEnabled()) {
+ logger.info("Study \"" + study.getIndex() + "\" re-indexed.");
+ }
+ }
+
+ public void update (KnowledgeElement kelm) throws IOException {
+// ---------------------------------------------
+ IndexServiceImpl.Entry entry = new Entry(kelm);
+ entry.update();
+ if (logger.isInfoEnabled()) {
+ logger.info("Knowledge \"" + kelm.getIndex() + "\" re-indexed.");
+ }
+ }
+ /**
+ * Get the projectElementService.
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ * @param projectElementService the projectElementService to set
+ */
+ public void setProjectElementService(ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
+
+ /**
+ * Get the repositoryService.
+ * @return the repositoryService
+ */
+ public RepositoryService getRepositoryService() {
+ return _repositoryService;
+ }
+
+ /**
+ * Set the repositoryService.
+ * @param repositoryService the repositoryService to set
+ */
+ public void setRepositoryService(RepositoryService repositoryService) {
+ _repositoryService = repositoryService;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 05.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service.technical;
+
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.service.technical.ProjectSettingsService.Step;
+import org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming;
+
+/**
+ * @author rkv
+ *
+ */
+public interface ProjectSettingsService {
+
+ public static class Step {
+ // ------------------------
+ int number;
+ private Class<? extends ProjectElement> level; // Study or Scenario
+ Set<Class<?>> contents; // Set of Document and/or Knowledge
+ private String path;
+
+ Step(int number, Class<? extends ProjectElement> level, String path) {
+ this.initialize(number, level, path);
+ }
+
+ private Step(int number, Class<? extends ProjectElement> level,
+ Class<?> contents, String path) {
+ this.initialize(number, level, path);
+ this.contents.add(contents);
+ }
+
+ private void initialize(int number,
+ Class<? extends ProjectElement> level, String path) {
+ this.number = number;
+ this.level = level;
+ this.path = path + "/";
+ this.contents = new HashSet<Class<?>>();
+ }
+
+ public boolean appliesTo(Class<? extends ProjectElement> level) {
+ return (level == this.level);
+ }
+
+ public boolean mayContain(Class<?> type) {
+ return contents.contains(type);
+ }
+
+ public int getNumber() {
+ return number;
+ }
+
+ public String getPath() {
+ return path;
+ }
+ }
+
+ public FileNaming getFileNamingScheme();
+
+ public List<ProjectSettingsService.Step> getAllSteps();
+
+ public String getReferencePattern();
+
+ public String getRevisionPattern();
+
+ public void configure(String filename) throws IOException, SQLException;
+
+ public List<ProjectSettingsService.Step> getStepsOf(
+ Class<? extends ProjectElement> level);
+}
--- /dev/null
+package org.splat.service.technical;
+/**
+ *
+ * @author Daniel Brunier-Coulin
+ * @copyright OPEN CASCADE 2012
+ */
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Vector;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.ValidationCycle.Actor;
+import org.splat.dal.dao.som.Database;
+import org.splat.manox.XDOM;
+
+
+public class ProjectSettingsServiceImpl implements ProjectSettingsService {
+
+// Non persistent configuration information
+ private Properties reprop; // Repository settings
+ private String pattern; // Pattern of study references
+ private FileNaming naming; // Scheme of file names stored into the repository
+ private String versioning; // Pattern of the presentation of version numbers
+ private Vector<ProjectSettingsService.Step> steps; // Ordered list of (transient) study steps
+ private Vector<ProjectSettingsValidationCycle> concycles; // Configuration document validation cycles
+
+// Temporary attributes initialized from the configuration file for populating the database with object types
+ private LinkedHashMap<String,String> mapuse; // Document type names and uses mapping
+ private Vector<String> context; // Simulation Context type names
+ private Vector<String> kname; // Knowledge Element type names
+ private Vector<NamedNodeMap> flows; // Document flows
+ private Vector<NamedNodeMap> sclass; // Study classifications
+
+// Other resources
+ private static ProjectSettingsServiceImpl my = null; // Singleton instance
+ private Database _database;
+ protected final static Logger logger = Logger.getLogger(ProjectSettingsServiceImpl.class);
+
+ public enum FileNaming { title, encoded, asis }
+ public static class ProjectSettingsValidationCycle {
+// -----------------------------------
+ private String name;
+ private Actor[] actor;
+
+ private ProjectSettingsValidationCycle () {
+ this.name = "built-in";
+ this.actor = new Actor[] { null, null, null };
+ }
+ private ProjectSettingsValidationCycle (String name, Actor[] actor) {
+ this.name = name;
+ this.actor = actor;
+ }
+ public String getName () {
+ return name;
+ }
+ public Actor[] getActorTypes () {
+ return actor;
+ }
+ }
+
+// ==============================================================================================================================
+// Construction
+// ==============================================================================================================================
+
+ public static ProjectSettingsServiceImpl getMe () {
+// --------------------------------------
+ if (my == null) my = new ProjectSettingsServiceImpl();
+ return my;
+ }
+ protected ProjectSettingsServiceImpl () {
+// ----------------------------
+ reprop = new Properties();
+ steps = new Vector<ProjectSettingsService.Step>();
+ }
+
+// ==============================================================================================================================
+// Public functions
+// ==============================================================================================================================
+
+ public void configure (String filename) throws IOException, SQLException {
+// ---------------------------------------
+ if (!steps.isEmpty()) return; // Project already configured
+
+ Database base = getDatabase().getMe();
+ File config = new File(filename);
+ if (config.exists()) {
+ loadCustomization(config);
+ } else {
+ logger.fatal("Could not find the database configuration file \"" + config.getAbsolutePath() + "\"");
+ throw new FileNotFoundException();
+ }
+ base.configure(reprop);
+ if (!base.isInitialized()) {
+ base.initialize();
+ initialize(); // Populates the database with all necessary stuff
+ }
+ }
+
+ public List<ProjectSettingsService.Step> getAllSteps () {
+// ---------------------------------------
+ return steps;
+ }
+
+/**
+ * Return the validation cycles of result documents defined in the workflow, ordered by study activities
+ * and ending by the default validation cycle, if defined.
+ *
+ * @return the validation cycles of the workflow
+ */
+ public static List<ProjectSettingsValidationCycle> getAllValidationCycles () {
+// -------------------------------------------------------------
+ return my.concycles;
+ }
+
+ public FileNaming getFileNamingScheme () {
+// -----------------------------------------------
+ return naming;
+ }
+
+ public static ProjectSettingsValidationCycle getNewValidationCycle () {
+// ------------------------------------------------------
+ return new ProjectSettingsValidationCycle();
+ }
+
+ public String getReferencePattern () {
+ return pattern;
+ }
+
+ public String getRevisionPattern () {
+// ------------------------------------------
+ return versioning;
+ }
+
+ public static ProjectSettingsService.Step getStep (int number) {
+// ---------------------------------------
+ for (int i=0; i<my.steps.size(); i++) {
+ ProjectSettingsService.Step step = my.steps.get(i);
+ if (step.number == number) return step;
+ }
+ return null;
+ }
+
+ public List<ProjectSettingsService.Step> getStepsOf (Class<? extends ProjectElement> level) {
+// ---------------------------------------------------------------------------
+ Vector<ProjectSettingsService.Step> result = new Vector<ProjectSettingsService.Step>();
+
+ for (int i=0; i<steps.size(); i++) {
+ ProjectSettingsService.Step step = steps.get(i);
+ if (step.appliesTo(level)) result.add(step);
+ }
+ return result;
+ }
+
+// ==============================================================================================================================
+// Protected member function
+// ==============================================================================================================================
+
+ public void initialize () {
+// ----------------------------
+ createDocumentTypes();
+ createSimulationContextTypes();
+ createKnowledgeElementTypes();
+ }
+
+// ==============================================================================================================================
+// Private member function
+// ==============================================================================================================================
+
+ private void loadCustomization (File config) {
+// --------------------------------------------
+ try {
+ DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
+ DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
+
+ org.w3c.dom.Document conf = dBuilder.parse(config.getPath());
+ HashMap<String, Node> children = XDOM.getNamedChildNodes(conf.getDocumentElement());
+
+// Repository tag initializing the reprop attribute
+ Node child = children.get("database");
+ HashMap<String, Node> datag = XDOM.getNamedChildNodes(child);
+
+ String disk = datag.get("repository").getAttributes().getNamedItem("disk").getNodeValue();
+ if (!disk.endsWith("/")) disk = disk + "/";
+ logger.info("Database root set to " + disk);
+ reprop.setProperty("repository", disk);
+
+// Formats tag initializing the reference pattern and date attributes
+ child = children.get("formats");
+ datag = XDOM.getNamedChildNodes(child);
+
+ NamedNodeMap natr = datag.get("references").getAttributes();
+ pattern = natr.getNamedItem("study").getNodeValue();
+
+ natr = datag.get("files").getAttributes();
+ naming = FileNaming.valueOf(natr.getNamedItem("name").getNodeValue());
+
+ natr = datag.get("versions").getAttributes();
+ versioning = natr.getNamedItem("pattern").getNodeValue();
+
+// Activities tag initializing the steps and rex attributes
+ child = children.get("activities");
+ NodeList nlist = child.getChildNodes();
+ Vector<NamedNodeMap> flist = new Vector<NamedNodeMap>();
+ Vector<String> resultype = new Vector<String>();
+ Vector<NamedNodeMap> clist = new Vector<NamedNodeMap>();
+
+ int snum = 1; // Base number of steps
+ for (int i=0; i<nlist.getLength(); i++) {
+ child = nlist.item(i);
+ if (child.getNodeName().equals("scenario")) {
+ NodeList slist = child.getChildNodes();
+ for (int j=0; j<slist.getLength(); j++) {
+ child = slist.item(j);
+ if (!child.getNodeName().equals("step")) continue;
+ HashMap<String, Node> tags = XDOM.getNamedChildNodes(child);
+
+ natr = tags.get("storage").getAttributes();
+ ProjectSettingsService.Step step = new ProjectSettingsService.Step(snum, Scenario.class, natr.getNamedItem("path").getNodeValue());
+
+// Keeping flow and classification information for eventual later use
+ natr = tags.get("flow").getAttributes();
+ flist.add(natr);
+ child = natr.getNamedItem("result");
+ if (child != null) resultype.add(child.getNodeValue());
+
+ child = tags.get("classification");
+ if (child != null) clist.add( child.getAttributes() );
+ else clist.add( null );
+
+ if (natr.getNamedItem("contents").getNodeValue().equals("knowledge")) {
+//TODO In a given scenario, only one step must contain knowledges
+ step.contents.add(KnowledgeElement.class);
+ } else {
+ step.contents.add(Document.class);
+ }
+ steps.add(step);
+ snum += 1;
+ }
+ } else {
+ if (!child.getNodeName().equals("step")) continue;
+ HashMap<String, Node> tags = XDOM.getNamedChildNodes(child);
+
+ natr = tags.get("storage").getAttributes(); // Mandatory information
+ ProjectSettingsService.Step step = new ProjectSettingsService.Step(snum, Study.class, natr.getNamedItem("path").getNodeValue());
+
+// Keeping flow and classification information for eventual later use
+ natr = tags.get("flow").getAttributes();
+ flist.add(natr);
+ child = natr.getNamedItem("result");
+ if (child != null) resultype.add(child.getNodeValue());
+
+ child = tags.get("classification"); // Optional information
+ if (child != null) clist.add( child.getAttributes() );
+ else clist.add( null );
+
+ if (natr.getNamedItem("contents").getNodeValue().equals("knowledge")) {
+//TODO Error: knowledges must be attached to scenarios
+ } else {
+ step.contents.add(Document.class);
+ }
+ steps.add(step);
+ snum += 1;
+ }
+ }
+// Validations tag
+ child = children.get("validations");
+ concycles = new Vector<ProjectSettingsValidationCycle>();
+ datag = XDOM.getNamedChildNodes(child);
+
+ String[] step = { "review", "approval", "acceptance" };
+ resultype.add("default");
+ for (Iterator<String> i=resultype.iterator(); i.hasNext(); ) {
+ Actor[] actor = { null, null, null };
+ String name = i.next();
+ child = datag.get(name);
+ if (child == null) continue; // Document type not subject of any validation
+ natr = child.getAttributes();
+ for (int j=0; j<step.length; j++) {
+ child = natr.getNamedItem(step[j]);
+ if (child == null) continue; // Validation step not required
+ actor[j] = Actor.valueOf(child.getNodeValue());
+ }
+ concycles.add( new ProjectSettingsValidationCycle(name, actor) );
+ }
+ concycles.add( new ProjectSettingsValidationCycle() ); // Adds the built-in validation cycle
+
+ if (getDatabase().getMe().isInitialized()) return; // No need to load object type definitions as they are already stored
+
+// Documents tag
+ child = children.get("documents");
+ nlist = child.getChildNodes();
+
+ flows = flist; // Kept for later use in document type definition
+ sclass = clist; // Kept for later use in simulation context type definition
+ mapuse = new LinkedHashMap<String,String>();
+ for (int i=0; i<nlist.getLength(); i++) {
+ child = nlist.item(i);
+ if (!child.getNodeName().equals("article")) continue;
+
+ natr = child.getAttributes();
+ String type = natr.getNamedItem("type").getNodeValue();
+ String uses = null;
+ child = natr.getNamedItem("uses");
+ if (child != null) uses = child.getNodeValue();
+ mapuse.put(type, uses); // Must be added to the map even if no (null) uses
+ }
+// Simulation Contexts tag
+ child = children.get("contexts");
+ nlist = child.getChildNodes();
+
+ context = new Vector<String>();
+ for (int i=0; i<nlist.getLength(); i++) {
+ child = nlist.item(i);
+ if (!child.getNodeName().equals("article")) continue;
+
+ context.add(child.getAttributes().getNamedItem("type").getNodeValue());
+ }
+// Knowledge Elements tag
+ child = children.get("knowledges");
+ nlist = child.getChildNodes();
+
+ kname = new Vector<String>();
+ for (int i=0; i<nlist.getLength(); i++) {
+ child = nlist.item(i);
+ if (!child.getNodeName().equals("article")) continue;
+
+ kname.add(child.getAttributes().getNamedItem("type").getNodeValue());
+ }
+ }
+ catch (Exception error) {
+ logger.info("Error in customization", error);
+ }
+ }
+
+ private void createDocumentTypes () {
+// -----------------------------------
+ DocumentType.Properties tprop = new DocumentType.Properties();
+ HashMap<String,Vector<ProjectSettingsService.Step>> mapsteps = new HashMap<String,Vector<ProjectSettingsService.Step>>();
+ HashMap<String,ProjectSettingsService.Step> mapresult = new HashMap<String,ProjectSettingsService.Step>();
+ HashMap<String,DocumentType> maptype = new HashMap<String,DocumentType>();
+
+ Vector<ProjectSettingsService.Step> slist = null; // List of Steps to which each document type is valid
+ int snum = 0; // Step number
+ String type = null;
+ String uses = null;
+ for (Iterator<NamedNodeMap> i=flows.iterator(); i.hasNext(); snum++) {
+ NamedNodeMap flow = i.next();
+ ProjectSettingsService.Step step = steps.get(snum);
+ String[] contents = flow.getNamedItem("contents").getNodeValue().split(",");
+ for (int j=0; j<contents.length; j++) {
+ type = contents[j];
+ if (!mapuse.containsKey(type)) {
+ logger.warn("Undefined \"" + type + "\" document type.");
+ continue;
+ } slist = mapsteps.get(type);
+ if (slist == null) slist = new Vector<ProjectSettingsService.Step>();
+ slist.add(step);
+ mapsteps.put(type, slist);
+ }
+ Node result = flow.getNamedItem("result");
+ if (result != null) mapresult.put(result.getNodeValue(), step);
+ }
+ try {
+ DocumentType tdoc = null;
+ Set<String> tset = mapuse.keySet();
+ ProjectSettingsService.Step step;
+ for (Iterator<String> i=tset.iterator(); i.hasNext(); ) {
+ type = i.next();
+ slist = mapsteps.get(type);
+ uses = mapuse.get(type);
+ step = mapresult.get(type);
+
+ tprop.clear();
+ tprop.setName(type).setStep(slist.toArray(new ProjectSettingsService.Step[slist.size()]));
+ if (uses != null) {
+ tdoc = maptype.get(uses);
+ if (tdoc == null) logger.warn("Undefined \"" + uses + "\" document type.");
+ else tprop.setUses(tdoc);
+ }
+ if (step != null) tprop.setResult(step);
+
+ tprop.disableCheck();
+ tdoc = Document.createType(tprop); // Creation of Document Types
+ tdoc.approve();
+ maptype.put(type, tdoc);
+ }
+ } catch (Exception error) {
+ logger.warn("Error creating document types, reason:", error); // Should not happen
+ }
+ }
+
+ private void createKnowledgeElementTypes () {
+// -------------------------------------------
+ try {
+ KnowledgeElementType ktype = KnowledgeElement.createType("usecase"); // Internal reserved knowledge element type
+ ktype.reserve();
+ for (Iterator<String> i=kname.iterator(); i.hasNext(); ) {
+ String type = i.next();
+
+ ktype = KnowledgeElement.createType(type); // Knowledge Elements Types defined in the configuration
+ ktype.approve();
+ }
+ } catch (Exception error) {
+ logger.warn("Error creating knowledge types, reason:", error); // Should not happen
+ }
+ }
+
+ private void createSimulationContextTypes () {
+// --------------------------------------------
+ HashMap<String,ProjectSettingsService.Step> mapstep = new HashMap<String,ProjectSettingsService.Step>();
+ int snum = 0;
+ for (Iterator<NamedNodeMap> i=sclass.iterator(); i.hasNext(); snum++) {
+ NamedNodeMap clatr = i.next();
+ if (clatr == null) continue;
+
+ String[] clist = clatr.getNamedItem("context").getNodeValue().split(",");
+ for (int j=0; j<clist.length; j++) {
+ mapstep.put(clist[j], steps.get(snum));
+ }
+ }
+ try {
+ SimulationContextType tctex = null;
+ for (Iterator<String> i=context.iterator(); i.hasNext(); ) {
+ String type = i.next();
+ if (!mapstep.containsKey(type)) {
+ logger.warn("Could not find \"" + type + "\" classification. Simulation Context type ignored.");
+ continue;
+ }
+ tctex = SimulationContext.createType(type, mapstep.get(type)); // Creation of Simulation Context Types
+ tctex.approve();
+ }
+ } catch (Exception error) {
+ logger.warn("Error creating context types, reason:", error); // Should not happen
+ }
+ }
+ /**
+ * Get the database.
+ * @return the database
+ */
+ public Database getDatabase() {
+ return _database;
+ }
+ /**
+ * Set the database.
+ * @param database the database to set
+ */
+ public void setDatabase(Database database) {
+ _database = database;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service.technical;
+
+import java.io.File;
+
+import org.splat.dal.bo.kernel.User;
+
+/**
+ * @author RKV
+ *
+ */
+public interface RepositoryService {
+
+ public File getRepositoryIndexDirectory();
+
+ public String getRepositoryVaultPath();
+
+ public String getBasepath();
+
+ public void setBasepath(String basepath);
+
+ public File getDownloadDirectory(User user);
+
+ public String getTemplatePath();
+}
--- /dev/null
+/*****************************************************************************
+ * Company EURIWARE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 06.10.2012
+ * @author $Author$
+ * @version $Revision$
+ *****************************************************************************/
+
+package org.splat.service.technical;
+
+import java.io.File;
+
+import org.splat.dal.bo.kernel.User;
+
+/**
+ * @author RKV
+ *
+ */
+public class RepositoryServiceImpl implements RepositoryService {
+
+ private String _basepath;
+
+ public File getRepositoryIndexDirectory() {
+ return new File(getBasepath() + "lucin/");
+ }
+
+ public String getRepositoryVaultPath() {
+ return (getBasepath() + "vault/");
+ }
+
+ public File getDownloadDirectory(User user) {
+ StringBuffer path = new StringBuffer(_basepath).append("downloads/")
+ .append(user.getUsername()).append("/");
+ return new File(path.toString());
+ }
+
+ public String getTemplatePath() {
+ return (_basepath + "templates/");
+ }
+
+ /**
+ * Get the basepath.
+ * @return the basepath
+ */
+ public String getBasepath() {
+ return _basepath;
+ }
+
+ /**
+ * Set the basepath.
+ * @param basepath the basepath to set
+ */
+ public void setBasepath(String basepath) {
+ _basepath = basepath;
+ }
+}
+++ /dev/null
-package org.splat.som;
-/**
- * Base implementation of actor relations such as Contributor, Reviewer and Approver.
- * ActorRelation objects are attached to Documents for defining those who HAVE CONTRIBUTED to these documents,
- * while instances of subclasses of ActorRelation are attached to Studies for setting those who CAN CONTRIBUTE to given document types.</br>
- * </br>
- * Depending on the actual relation object, the value of the actor relation has different meaning:
- * <ul>
- * <li>The description of ActorRelation objects defines the type of contributions (Contributor, Reviewer, Approver...)</li>
- * <li>The description of instances of subclasses of ActorRelation defines the type of acting documents</li>
- * </ul>
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-import org.splat.kernel.User;
-
-
-public abstract class ActorRelation extends Relation {
-
- private User refer;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected ActorRelation () {
- }
-// ActorRelation subclasses constructor
- protected ActorRelation (Study from, User to) {
-// ---------------------------------------------
- super(from);
- this.refer = to;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- @Override
- public User getTo () {
-// --------------------
- return refer;
- }
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (User)to;
- }
-}
\ No newline at end of file
import java.util.HashSet;
import java.util.Set;
-import org.splat.kernel.Role;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.Role;
+import org.splat.dal.bo.kernel.User;
public class ApplicationRights {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the Attribute concrete subclasses.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
-<!-- Description attribute
- -->
- <subclass name="org.splat.som.DescriptionAttribute" extends="org.splat.kernel.TextAttribute" discriminator-value="description">
- </subclass>
-
-<!-- Comment attribute
- -->
- <subclass name="org.splat.som.CommentAttribute" extends="org.splat.kernel.TextAttribute" discriminator-value="comment">
- </subclass>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- * Attribute class of type Comment.<br/>
- * A comment is made of any text up to 65 thousand characters.
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.TextAttribute;
-
-
-public class CommentAttribute extends TextAttribute {
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor.
- protected CommentAttribute () {
- }
-/**
- * Constructs a comment attached to a time stamp.
- *
- * @param from the time stamp to which this comment is attached.
- * @param value the text of this comment
- */
- protected CommentAttribute (Timestamp from, String value) {
-// ---------------------------------------------------------
- super(from, value);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.User;
-
-
-public class ContributorRelation extends ActorRelation {
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected ContributorRelation () {
- }
-// Initialization constructor
- protected ContributorRelation (Study from, User to) {
-// --------------------------------------------------
- super(from, to);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-
-
-public class ConvertsRelation extends Relation {
-
-// Persistent field
- private File refer;
-
-// Transient fields
- private boolean got; // For optimizing getDescription()
- private String description; // Null if this is not described
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected ConvertsRelation () {
-// -----------------------------
- got = false;
- description = null;
- }
-// Initialization constructors
- protected ConvertsRelation (Document from, File to) {
-// ---------------------------------------------------
- super(from);
- this.refer = to;
- this.got = true;
- this.description = null; // Conversion not described
- }
- protected ConvertsRelation (Document from, File to, String description) {
-// -----------------------------------------------------------------------
- super(from);
- this.refer = to;
- this.got = true;
- this.description = description; // May be null
- if (description != null) this.setAttribute( new DescriptionAttribute(this, description) );
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public String getDescription () {
-// -------------------------------
- if (!got) {
- DescriptionAttribute field = (DescriptionAttribute)this.getAttribute(DescriptionAttribute.class);
- if (field != null) description = field.getValue();
- got = true; // Don't need to be modified later as set and remove attribute functions are private to this class
- }
- return description; // May be null
- }
-
- public File getTo () {
-// --------------------
- return refer;
- }
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (File)to;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.io.File;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.jdbc.Work;
-import org.apache.log4j.Logger;
-import org.apache.lucene.index.Term;
-import org.apache.lucene.search.BooleanClause;
-import org.apache.lucene.search.BooleanFilter;
-import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.FilterClause;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.ScoreDoc;
-import org.apache.lucene.search.Sort;
-import org.apache.lucene.search.SortField;
-import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.search.TermsFilter;
-import org.apache.lucene.search.TopFieldDocs;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.FSDirectory;
-
-import org.splat.kernel.User;
-import org.splat.kernel.UserDirectory;
-import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-
-
-public class Database extends org.splat.kernel.Database {
-
- private int uplevel = 0; // Level of database upgrade
- private String basepath = null; // Path of the root directory of repository
-
- private static Database my = null; // Singleton instance
-
- protected class CreateTables extends org.splat.kernel.Database.CreateTables {
-// ---------------------------------------------------------------------------
- public void execute(Connection connex) throws SQLException
- {
- super.execute(connex);
-
-// Study Entity
- String create = "CREATE TABLE `study` (" +
- "`rid` int(10) UNSIGNED NOT NULL," +
- "`sid` tinytext NOT NULL," +
- "`title` tinytext NOT NULL," +
- "`state` enum('inWORK','inDRAFT','inCHECK','APPROVED', 'TEMPLATE') NOT NULL default 'inWORK'," +
- "`area` enum('PRIVATE','PUBLIC','REFERENCE') NOT NULL default 'PRIVATE'," +
- "`manager` int(10) NOT NULL," +
- "`version` tinytext NOT NULL," +
- "`docount` int(10) UNSIGNED NOT NULL," +
- "`history` int(10) UNSIGNED NOT NULL," +
- "`credate` date NOT NULL," +
- "`lasdate` date NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Scenario Entity
- create = "CREATE TABLE `scenario` (" +
- "`rid` int(10) UNSIGNED NOT NULL," +
- "`sid` int(10) UNSIGNED NOT NULL," +
- "`owner` int(10) NOT NULL," +
- "`scendex` int(3) NOT NULL," +
- "`title` tinytext NOT NULL," +
- "`manager` int(10) NOT NULL," +
- "`cuser` int(10)," +
- "`credate` date NOT NULL," +
- "`lasdate` date NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Document Entity and document tag (Publication)
- create = "CREATE TABLE `document` (" +
- "`rid` int(10) UNSIGNED NOT NULL," +
- "`did` tinytext NOT NULL," +
- "`type` int(10) NOT NULL," +
- "`step` int(10) NOT NULL," +
- "`state` enum('inWORK','inDRAFT','inCHECK','APPROVED','EXTERN') NOT NULL default 'inWORK'," +
- "`name` tinytext NOT NULL," +
- "`author` int(10) NOT NULL," +
- "`version` tinytext," +
- "`countag` int(10) UNSIGNED NOT NULL," +
- "`history` int(10) NOT NULL," +
- "`myfile` int(10) NOT NULL," +
- "`lasdate` date NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
- create = "CREATE TABLE `doctag` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`doc` int(10) NOT NULL," +
- "`owner` int(10) NOT NULL," +
- "`isnew` char(1) NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-// Document types
- create = "CREATE TABLE `doctype` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`name` tinytext NOT NULL," +
- "`state` enum('inCHECK','APPROVED') NOT NULL default 'inCHECK'," +
- "`step` tinytext NOT NULL," +
- "`result` tinytext," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-// Document types dependencies
- create = "CREATE TABLE `docuse` (" +
- "`owner` int(10) NOT NULL," +
- "`rid` int(10) NOT NULL" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// ValidationCycle related object
- create = "CREATE TABLE `cycle` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`type` int(10) NOT NULL," +
- "`publisher` int(10)," +
- "`reviewer` int(10)," +
- "`approver` int(10)," +
- "`signatory` int(10)," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Timestamp related object
- create = "CREATE TABLE `stamp` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`type` enum('PROMOTION','REVIEW','APPROVAL','ACCEPTANCE','DISTRIBUTION','REFUSAL') NOT NULL," +
- "`author` int(10) NOT NULL," +
- "`date` datetime NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// KnowledgeElements objects
- create = "CREATE TABLE `knowelm` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`type` int(10) NOT NULL," +
- "`owner` int(10) NOT NULL," +
- "`state` enum('inWORK','inDRAFT','inCHECK','APPROVED') NOT NULL default 'inDRAFT'," +
- "`title` tinytext NOT NULL," +
- "`value` text NOT NULL," +
- "`author` int(10) NOT NULL," +
- "`date` date NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-// KnowledgeElement types
- create = "CREATE TABLE `knowtype` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`name` tinytext NOT NULL," +
- "`state` enum('inWORK','inCHECK','APPROVED') NOT NULL default 'inCHECK'," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// SimulationContext objects
- create = "CREATE TABLE `contelm` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`type` int(10) NOT NULL," +
- "`step` int(10) NOT NULL," +
- "`state` enum('inCHECK','APPROVED') NOT NULL default 'inCHECK'," +
- "`value` text NOT NULL," +
- "`counter` int(10) UNSIGNED NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-// SimulationContext types
- create = "CREATE TABLE `contype` (" +
- "`rid` int(10) UNSIGNED NOT NULL auto_increment," +
- "`name` tinytext NOT NULL," +
- "`state` enum('inCHECK','APPROVED') NOT NULL default 'inCHECK'," +
- "`step` int(10) NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Many-to-many association between ProjectElement (Study and Scenario) and SimulationContext
- create = "CREATE TABLE `projext` (" +
- "`owner` int(10) NOT NULL," +
- "`ordex` int(10) NOT NULL," +
- "`rid` int(10) NOT NULL" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// File objects
- create = "CREATE TABLE `file` (" +
- "`rid` int(10) UNSIGNED NOT NULL," +
- "`format` tinytext NOT NULL," +
- "`path` tinytext NOT NULL," +
- "`date` date NOT NULL," +
- "PRIMARY KEY (`rid`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
-
-// Reference objects
- create = "CREATE TABLE `refid` (" +
- "`cycle` int(10) NOT NULL," +
- "`base` int(10) NOT NULL," +
- "PRIMARY KEY (`cycle`)" +
- ") ENGINE=MyISAM DEFAULT CHARSET=latin1";
- request.execute(create);
- }
- }
- protected class CheckVersion implements Work {
-// --------------------------------------------
- public void execute(Connection connex) throws SQLException
- {
- DatabaseMetaData dbmdata = connex.getMetaData();
- String dbname = "simer"; //TODO: Get the name from meta-data
- ResultSet table;
-
- table = dbmdata.getTables(dbname, null, "study", null);
- if (table.next()) return;
- uplevel = -1; // Database not initialized
- }
- }
-
- protected final static Logger logger = org.splat.kernel.Database.logger;
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
- public static Database getMe () {
-// -------------------------------
- if (my == null) try {
- my = new Database();
- }
- catch (Exception error) {
- logger.fatal("Could not access the database, reason:", error);
- }
- return my;
- }
- private Database () {
-// -------------------
- Database.getSession().doWork(new CheckVersion());
- this.setIDPoolSize(4); // Average number of generated IDs when creating a study and versioning a document
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean isInitialized () {
-// -------------------------------
- return (uplevel >= 0);
- }
-
- public void initialize () throws IOException, SQLException {
-// -------------------------
- logger.info("Creation of the database.");
-
-// Creation of the Lucene index
- Index.create(); // May throw IOException if the index repository is improperly configured
-
-// Creation of the SIMER SQL tables
- Session session = Database.getSession();
- session.doWork(new CreateTables()); // May throw SQLException if the SIMER database does not exist
- session.flush();
-
-// Population of the database with customized data
- this.populate();
-
- session.flush();
- uplevel = 0; // The database is now up-to-date
- }
-
-// ==============================================================================================================================
-// Protected member functions
-// ==============================================================================================================================
-
- protected void configure (Properties reprop) {
-// --------------------------------------------
- basepath = reprop.getProperty("repository");
- }
-
- protected void populate () {
-// --------------------------
- try {
-// Initialization of the schema version
- this.setSchemaVersion("D0.3"); //TODO: Get the version name from the configuration file
-
-// Creation of the default system administrator
-//TODO: Get the username password from the Hibernate configuration
- User.Properties uprop = new User.Properties();
- uprop.setUsername("simer")
- .setPassword("admin")
- .setName("Simulation")
- .setFirstName("Manager")
- .setDisplayName("label.sysadmin")
- .addRole("sysadmin")
- .setMailAddress("noreply@salome-platform.org");
- uprop.disableCheck();
- UserDirectory.createUser(uprop);
- }
- catch (Exception e) {
-// Let's continue, hoping the best...
- }
- ProjectSettings.getMe().initialize(); // Populates the database with all necessary stuff
- }
-
-// ==============================================================================================================================
-// Public services
-// ==============================================================================================================================
-
- public static Study createStudy (Study.Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, RuntimeException {
-// --------------------------------------------------------
- Study study = new Study(sprop);
-
- study.buildReference();
- Database.getSession().save(study);
- try {
- Index lucin = getIndex();
- lucin.add(study);
- }
- catch (IOException error) {
- logger.error("Unable to index the study '" + study.getIndex() + "', reason:", error);
-// Continue and try to index later
- }
- return study;
- }
-
- public static void indexStudy (Study study) {
-// -------------------------------------------
- try {
- Study.Properties sprop = new Study.Properties();
- List<Proxy> index = Database.selectStudiesWhere(sprop.setReference(study.getReference()));
-
- if (index.size() != 0) return; // The given study is already indexed
-
- Index lucin = getIndex();
- Scenario[] scenes = study.getScenarii();
-
- lucin.add(study);
- if (study.getProgressState() != ProgressState.inWORK) for (int i=0; i<scenes.length; i++) {
- List<KnowledgeElement> list = scenes[i].getAllKnowledgeElements();
- for (Iterator<KnowledgeElement> j=list.iterator(); j.hasNext(); ) {
- lucin.add(j.next());
- }
- }
- }
- catch (Exception error) {
- logger.error("Unable to index the study '" + study.getIndex() + "', reason:", error);
- }
- }
-
- public static Index getIndex () throws IOException {
-// -------------------------------
- Index lucin = new Index();
- if ( !lucin.exists() ) Index.create(); // Happens when re-indexing all studies
- return lucin;
- }
-
- public static File getDownloadDirectory (User user) {
-// ---------------------------------------------------
- StringBuffer path = new StringBuffer(my.basepath).append("downloads/").append(user.getUsername()).append("/");
- return new File(path.toString());
- }
-
- public static File getRepositoryIndexDirectory () {
-// -------------------------------------------------
- return new File(my.basepath + "lucin/");
- }
-
- public static String getRepositoryVaultPath () {
-// --------------------------------------------
- return (my.basepath + "vault/");
- }
-
- public static String getTemplatePath () {
-// ---------------------------------------
- return (my.basepath + "templates/");
- }
-
- public static Document selectDocument (int index) {
-// -------------------------------------------------
- StringBuffer query = new StringBuffer("from Document where rid='").append(index).append("'");
- return (Document)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
- public static Document selectDocument (String refid, String version) {
-// --------------------------------------------------------------------
- StringBuffer query = new StringBuffer("from Document where did='").append(refid).append("' and version='").append(version).append("'");
- return (Document)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
- public static KnowledgeElement selectKnowledgeElement (int index) {
-// -----------------------------------------------------------------
- StringBuffer query = new StringBuffer("from KnowledgeElement where rid='").append(index).append("'");
- KnowledgeElement result = (KnowledgeElement)Database.getSession().createQuery(query.toString()).uniqueResult();
-
- result.getOwnerScenario().getOwnerStudy().loadWorkflow();
- return result;
- }
-
- public static List<Proxy> selectKnowledgeElementsWhere (KnowledgeElement.Properties... kprop) {
-// ---------------------------------------------------------------------------------------------
- List<Proxy> result = new ArrayList<Proxy>();
- int hitsize = 20;
- try {
-
-// Creation of the Lucene query
- File indir = Database.getRepositoryIndexDirectory();
- Directory index = FSDirectory.open(indir);
- IndexSearcher searcher = new IndexSearcher(index, true);
- BooleanQuery fulquery = new BooleanQuery();
-
- for (int i=0; i<kprop.length; i++) {
- BooleanQuery query = new BooleanQuery();
- Term input; // Supposed initialized below at least by the visibility
-
- Visibility area = kprop[i].getVisibility(); // Visibility
- if (area != null) {
- input = new Term("area");
- query.add(new TermQuery(input.createTerm(area.toString())), BooleanClause.Occur.MUST);
- }
- ProgressState state = kprop[i].getProgressState(); // State
- if (state != null) {
- input = new Term("state");
- query.add(new TermQuery(input.createTerm(state.toString())), BooleanClause.Occur.MUST);
- }
- String refid = kprop[i].getReference(); // Reference
- if (refid != null) {
- input = new Term("ref");
- query.add(new TermQuery(input.createTerm(refid)), BooleanClause.Occur.MUST);
- }
- KnowledgeElementType type = kprop[i].getType(); // Type
- if (type != null) {
- input = new Term("type");
- query.add(new TermQuery(input.createTerm(type.getName())), BooleanClause.Occur.MUST);
- }
- User manager = kprop[i].getAuthor(); // Author
- if (manager != null) {
- input = new Term("author");
- query.add(new TermQuery(input.createTerm(manager.toString())), BooleanClause.Occur.MUST);
- }
- User actor = kprop[i].getActor(); // Contributor, Reviewer or Approver of the owner study
- if (actor != null) {
- input = new Term("actor");
- query.add(new TermQuery(input.createTerm(actor.toString())), BooleanClause.Occur.MUST);
- }
- String title = kprop[i].getTitle(); // Title
- if (title != null) {
- input = new Term("contents");
- BooleanQuery critext = new BooleanQuery();
- String operator = "AND"; // Future user input
- BooleanClause.Occur clause = BooleanClause.Occur.MUST;
- if (operator.equals("OR")) clause = BooleanClause.Occur.SHOULD;
- String[] word = title.split(" ");
- for (int j=0; j<word.length; j++) {
- critext.add(new TermQuery(input.createTerm(word[j])), clause);
- }
- query.add(critext, BooleanClause.Occur.MUST);
- }
- List<SimulationContext> context = kprop[i].getSimulationContexts();
- if (context != null && context.size() > 0) {
- BooleanQuery critext = new BooleanQuery();
- for (Iterator<SimulationContext> j=context.iterator(); j.hasNext();) {
- SimulationContext seltext = j.next();
- input = new Term(String.valueOf(seltext.getType().getIndex()));
- critext.add(new TermQuery(input.createTerm(seltext.getValue())), BooleanClause.Occur.MUST);
- }
- query.add(critext, BooleanClause.Occur.MUST);
- }
- fulquery.add(query, BooleanClause.Occur.SHOULD);
- }
- if (logger.isInfoEnabled()) {
- logger.info("Searching knowledges by Lucene query \"" + fulquery.toString() + "\".");
- }
-// Creation of the knowledge filter
- BooleanFilter filter = new BooleanFilter();
- TermsFilter select = new TermsFilter();
- Term mytype = new Term("class");
- select.addTerm( mytype.createTerm("KnowledgeElement") );
- filter.add(new FilterClause(select, BooleanClause.Occur.SHOULD));
-
-// Creation of the sort criteria
- Sort sort = new Sort(new SortField("title", SortField.STRING));
-
-// Search
- TopFieldDocs found = searcher.search(fulquery, filter, hitsize, sort);
-
- if (found.totalHits < 1) return result; // No study found
-
-// Construction of the result list
- ScoreDoc[] hits = found.scoreDocs;
- for (int i=0; i<hits.length; i++) {
- result.add( new Index.ObjectProxy(searcher.doc(hits[i].doc)) );
- }
- searcher.close();
- }
- catch (Exception error) {
- logger.error("Error during Lucene search, reason:", error);
- }
- return result;
- }
-
- public static SimulationContext selectSimulationContext (int index) {
-// -------------------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContext where rid='").append(index).append("'");
- return (SimulationContext)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
- public static SimulationContext selectSimulationContext (SimulationContextType celt, String value) {
-// --------------------------------------------------------------------------------------------------
- SimulationContext result = null;
- try {
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- List<SimulationContext> clist = selectSimulationContextsWhere(cprop.setType(celt).setValue(value));
- if (!clist.isEmpty()) result = clist.get(0); // Supposed being the most used one if many exist
- }
- catch (InvalidPropertyException error) {
- logger.info("Attempt to select a simulation context \"" + celt.getName() + "\" with an invalid value.");
- }
- return result;
- }
-
- @SuppressWarnings("unchecked")
- public static List<SimulationContext> selectSimulationContextsWhere (SimulationContext.Properties cprop) {
-// --------------------------------------------------------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContext");
- String separator = " where";
- SimulationContextType celt = cprop.getType();
- String value = cprop.getValue();
- ProgressState state = cprop.getProgressState();
- String order = "";
-
- if (celt != null) { query = query.append(separator).append(" type='").append(celt.getIndex()).append("'");
- separator = " and";
- order = " order by value asc";
- }
- if (value != null ) { query = query.append(separator).append(" value='").append(value).append("'");
- separator = " and";
- }
- if (state != null ) { query = query.append(separator).append(" state='").append(state).append("'");
- if (celt == null) order = " order by type asc";
- }
- query.append(order);
- return (List<SimulationContext>)Database.getSession().createQuery(query.toString()).list();
- }
-
- public static Study selectStudy (int index) {
-// -------------------------------------------
- StringBuffer query = new StringBuffer("from Study where rid='").append(index).append("'");
- Study result = (Study)Database.getSession().createQuery(query.toString()).uniqueResult();
-
- result.loadWorkflow();
- return result;
- }
-
- public static Study selectStudy (String refid) {
-// ----------------------------------------------
- StringBuffer query = new StringBuffer("from Study where sid='").append(refid).append("'");
- Study result = (Study)Database.getSession().createQuery(query.toString()).uniqueResult();
-
- result.loadWorkflow();
- return result;
- }
-
- public static List<Proxy> selectStudiesWhere (Study.Properties... sprop) {
-// ------------------------------------------------------------------------
- List<Proxy> result = new ArrayList<Proxy>();
- int hitsize = 20;
- try {
-
-// Creation of the Lucene query
- File indir = Database.getRepositoryIndexDirectory();
- Directory index = FSDirectory.open(indir);
- IndexSearcher searcher = new IndexSearcher(index, true);
- BooleanQuery fulquery = new BooleanQuery();
-
- for (int i=0; i<sprop.length; i++) {
- BooleanQuery query = new BooleanQuery();
- Term input; // Supposed initialized below at least by the visibility
-
- Visibility area = sprop[i].getVisibility(); // Visibility
- if (area != null) {
- input = new Term("area");
- query.add(new TermQuery(input.createTerm(area.toString())), BooleanClause.Occur.MUST);
- }
- ProgressState state = sprop[i].getProgressState(); // State
- if (state != null) {
- input = new Term("state");
- if (state == ProgressState.inPROGRESS) {
- BooleanQuery cristate = new BooleanQuery();
- cristate.add(new TermQuery(input.createTerm("inWORK")), BooleanClause.Occur.SHOULD);
- cristate.add(new TermQuery(input.createTerm("inDRAFT")), BooleanClause.Occur.SHOULD);
- cristate.add(new TermQuery(input.createTerm("inCHECK")), BooleanClause.Occur.SHOULD);
- query.add(cristate, BooleanClause.Occur.MUST);
- } else {
- query.add(new TermQuery(input.createTerm(state.toString())), BooleanClause.Occur.MUST);
- }
- }
- String refid = sprop[i].getReference(); // Reference
- if (refid != null) {
- input = new Term("ref");
- query.add(new TermQuery(input.createTerm(refid)), BooleanClause.Occur.MUST);
- }
- User manager = sprop[i].getManager(); // Author
- if (manager != null) {
- input = new Term("author");
- query.add(new TermQuery(input.createTerm(manager.toString())), BooleanClause.Occur.MUST);
- }
- User actor = sprop[i].getActor(); // Contributor, Reviewer or Approver
- if (actor != null) {
- input = new Term("actor");
- query.add(new TermQuery(input.createTerm(actor.toString())), BooleanClause.Occur.MUST);
- }
- String title = sprop[i].getTitle(); // Title
- if (title != null) {
- input = new Term("contents");
- BooleanQuery critext = new BooleanQuery();
- String operator = "AND"; // Future user input
- BooleanClause.Occur clause = BooleanClause.Occur.MUST;
- if (operator.equals("OR")) clause = BooleanClause.Occur.SHOULD;
- String[] word = title.split(" ");
- for (int j=0; j<word.length; j++) {
- critext.add(new TermQuery(input.createTerm(word[j])), clause);
- }
- query.add(critext, BooleanClause.Occur.MUST);
- }
- List<SimulationContext> context = sprop[i].getSimulationContexts();
- if (context != null && context.size() > 0) {
- BooleanQuery critext = new BooleanQuery();
- for (Iterator<SimulationContext> j=context.iterator(); j.hasNext();) {
- SimulationContext seltext = j.next();
- input = new Term(String.valueOf(seltext.getType().getIndex()));
- critext.add(new TermQuery(input.createTerm(seltext.getValue())), BooleanClause.Occur.MUST);
- }
- query.add(critext, BooleanClause.Occur.MUST);
- }
- fulquery.add(query, BooleanClause.Occur.SHOULD);
- }
- if (logger.isInfoEnabled()) {
- logger.info("Searching studies by Lucene query \"" + fulquery.toString() + "\".");
- }
-// Creation of the studies filter
- BooleanFilter filter = new BooleanFilter();
- TermsFilter select = new TermsFilter();
- Term mytype = new Term("class");
- select.addTerm( mytype.createTerm("Study") );
- filter.add(new FilterClause(select, BooleanClause.Occur.SHOULD));
-
-// Creation of the sort criteria
- Sort sort = new Sort(new SortField("title", SortField.STRING));
-
-// Search
- TopFieldDocs found = searcher.search(fulquery, filter, hitsize, sort);
-
- if (found.totalHits < 1) return result; // No study found
-
-// Construction of the result list
- ScoreDoc[] hits = found.scoreDocs;
- for (int i=0; i<hits.length; i++) {
- result.add( new Index.ObjectProxy(searcher.doc(hits[i].doc)) );
- }
- searcher.close();
- }
- catch (Exception error) {
- logger.error("Error during Lucene search, reason:", error);
- }
- return result;
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected static IDBuilder selectIDBuilder (int cycle) {
-// ------------------------------------------------------
- StringBuffer buffer = new StringBuffer("from IDBuilder where cycle='").append(cycle).append("'");
- String qstring = buffer.toString();
- Query query = Database.getSession().createQuery(qstring);
- IDBuilder result = (IDBuilder)query.uniqueResult();
-
- return result;
- }
-
- protected static IDBuilder selectIDBuilder (Date date) {
-// ------------------------------------------------------
- SimpleDateFormat year = new SimpleDateFormat("yyyy");
- String cycle = year.format(date);
- StringBuffer buffer = new StringBuffer("from IDBuilder where cycle='").append(cycle).append("'");
- String qstring = buffer.toString();
- Query query = Database.getSession().createQuery(qstring);
- IDBuilder result = (IDBuilder)query.uniqueResult();
-
- return result;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- * Attribute class of type Description.<br/>
- * A description is made of any text up to 65 thousand characters.
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.TextAttribute;
-
-
-public class DescriptionAttribute extends TextAttribute {
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor.
- protected DescriptionAttribute () {
- }
-/**
- * Constructs the description of a study or a scenario.
- *
- * @param from the study or the scenario to which this description is attached.
- * @param value the text of this description
- */
- protected DescriptionAttribute (ProjectElement from, String value) {
-// ------------------------------------------------------------------
- super(from, value);
- }
-/**
- * Constructs the description attached to a version relation.
- *
- * @param from the version relation to which this description is attached.
- * @param value the text of this description
- */
- protected DescriptionAttribute (VersionsRelation from, String value) {
-// --------------------------------------------------------------------
- super(from, value);
- }
- /**
- * Constructs the description attached to a conversion relation.
- *
- * @param from the conversion relation to which this description is attached.
- * @param value the text of this description
- */
- protected DescriptionAttribute (ConvertsRelation from, String value) {
-// --------------------------------------------------------------------
- super(from, value);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the Document class and its type information implemented by the DocumentType class.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.Document" table="document" lazy="false">
-
-<!-- Properties inherited from Entity
- -->
- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
- <generator class="org.splat.kernel.IDGenerator"/>
- </id>
- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Attribute" />
- </set>
- <set name="relations" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Relation" />
- </set>
-
-<!-- Document properties
- -
- - String did -->
- <property name="did" column="did" access="field" not-null="true" />
-
- <!-- DocumentType type -->
- <many-to-one name="type" column="type" access="field" not-null="true" />
-
- <!-- File myfile -->
- <many-to-one name="myfile" column="myfile" unique="true" cascade="all-delete-orphan" access="field" not-null="true" />
-
- <!-- String name -->
- <property name="name" column="name" access="field" not-null="true" />
-
- <!-- ProgressState state -->
- <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
-
- <!-- int step -->
- <property name="step" column="step" access="field" not-null="true" />
-
- <!-- String version -->
- <property name="version" column="version" access="field" />
-
- <!-- int countag -->
- <property name="countag" column="countag" access="field" not-null="true" />
-
- <!-- int history -->
- <property name="history" column="history" access="field" not-null="true" />
-
- <!-- User author -->
- <many-to-one name="author" column="author" access="field" not-null="true" />
-
- <!-- Date lasdate -->
- <property name="lasdate" column="lasdate" access="field" not-null="true" />
- </class>
-
-<!-- Class DocumentType
- -->
- <class name="org.splat.som.DocumentType" table="doctype" lazy="false">
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
- <property name="name" column="name" access="field" not-null="true" />
- <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
- <property name="step" column="step" access="field" not-null="true" />
- <property name="result" column="result" access="field" />
- <set name="uses" table="docuse" lazy="false" access="field">
- <key column="owner" />
- <many-to-many column="rid" class="org.splat.som.DocumentType" />
- </set>
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.text.DecimalFormat;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Vector;
-
-import org.hibernate.Hibernate;
-import org.hibernate.Session;
-
-import org.splat.kernel.NotApplicableException;
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.User;
-import org.splat.manox.Reader;
-import org.splat.manox.Toolbox;
-import org.splat.som.ProjectSettings.FileNaming;
-import org.splat.som.Timestamp.ComparatorByDate;
-
-
-public class Document extends Entity {
-
-// Persistent fields
- private DocumentType type; // User expendable types
- private File myfile;
- private String did;
- private int step;
- private ProgressState state;
- private String name;
- private String version;
- private int countag;
- private int history;
- private User author;
- private Date lasdate;
-
-// Transient fields
- public static String suformat = "00"; // Format of the suffix number of document did and file name
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// 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
- private ProjectSettings.Step step = null;
- private ProgressState state = null;
- private String name = null;
- protected String format = null;
- private String version = null;
- private User author = null;
- protected Date date = null;
- private String summary = null; // Only for versioning a document
- private String path = null; // Only for searching from a given path
-
-// - Public services
-
- public void clear () {
- super.clear();
- type = null;
- did = null;
- owner = null;
- step = null;
- state = null;
- name = null;
- format = null;
- version = null;
- author = null;
- date = null;
- summary = null;
- path = null;
- }
- public Properties copy () {
- Properties copy = new Properties();
- copy.type = this.type;
- copy.did = this.did;
- copy.owner = this.owner;
- copy.step = this.step;
- copy.state = this.state;
- copy.name = this.name;
- copy.format = this.format;
- copy.version = this.version;
- copy.author = this.author;
- copy.date = this.date;
- copy.summary = this.summary;
- copy.path = this.path;
- return copy;
- }
-// - Protected services
-
- protected User getAuthor () {
- return author;
- }
- protected String getDescription () {
- return summary;
- }
- protected String getLocalPath () {
- return path;
- }
- protected String getReference () {
- return did;
- }
- protected ProjectSettings.Step getStep () {
- return step;
- }
- protected DocumentType getType () {
- return type;
- }
-// - Property setters
-
- public Properties setAuthor (User user)
- {
- this.author = user;
- return this;
- }
- public Properties setDate (Date date)
- {
- this.date = date;
- return this;
- }
- public Properties setDescription (String summary) throws InvalidPropertyException
- {
- if (summary.length() == 0) throw new InvalidPropertyException("description");
- this.summary = summary;
- return this;
- }
- protected Properties setDocument (Document base)
- {
- type = base.type;
- step = ProjectSettings.getStep(base.step);
- name = base.name;
- format = base.getFormat();
- state = ProgressState.inWORK; // For incrementing the version number at save time
- version = base.version;
- return this;
- }
- public Properties setExternReference (String ref) throws InvalidPropertyException
- {
- if (ref.length() == 0) throw new InvalidPropertyException("reference");
- if (ref.equals(new Revision().toString())) throw new InvalidPropertyException("reference"); // Internal version number
- this.version = ref;
- return this;
- }
- public Properties setFormat (String format) throws InvalidPropertyException
- {
- if (format.length() == 0) throw new InvalidPropertyException("format");
- this.format = format;
- return this;
- }
-// Required only for passing search arguments
- public Properties setLocalPath (String path) throws InvalidPropertyException
- {
- if (path.length() == 0) throw new InvalidPropertyException("path");
- this.path = path;
- return this;
- }
- public Properties setName (String name) throws InvalidPropertyException
- {
- if (name.length() == 0) throw new InvalidPropertyException("name");
- this.name = name;
- return this;
- }
- protected Properties setOwner (ProjectElement owner)
- {
- this.owner = owner;
- return this;
- }
-// Required only for passing search arguments
- public Properties setReference (String did) throws InvalidPropertyException
- {
- if (did.length() == 0) throw new InvalidPropertyException("reference");
- this.did = did;
- return this;
- }
- public Properties setState (ProgressState state) throws InvalidPropertyException
- {
- if (state == ProgressState.inPROGRESS || state == ProgressState.TEMPLATE) throw new InvalidPropertyException("state"); // Non document states
- this.state = state;
- return this;
- }
- protected Properties setStep (ProjectSettings.Step step)
- {
- this.step = step;
- return this;
- }
- public Properties setType (DocumentType type)
- {
- this.type = type;
- return this;
- }
-// - Global validity check
-
- public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (type == null) throw new MissedPropertyException("type");
- if (owner == null) throw new MissedPropertyException("owner");
- if (step == null) throw new MissedPropertyException("step");
- if (author == null) throw new MissedPropertyException("author");
- if (format == null) throw new MissedPropertyException("format");
- if (owner instanceof Study && !step.appliesTo(Study.class)) throw new InvalidPropertyException("step");
- if (!type.isContentInto(step)) throw new InvalidPropertyException("step");
- if (state != null && state != ProgressState.EXTERN) {
-// inDRAFT, inCHECK or APPROVED + version = imposed version (future use)
-// inWORK + version = base version incremented at save time (used for versioning)
- if (version == null) throw new InvalidPropertyException("state");
- }
- if (version != null) {
- if (state == null) state = ProgressState.EXTERN;
- }
- }
- }
-// Database fetch constructor
- protected Document () {
- }
-// Internal constructor
- protected Document (Properties dprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// -------------------------------------
- super(dprop); // Throws one of the above exception if not valid
- myfile = new File(null, dprop.format, dprop.date); // The path is initialized below
- type = dprop.type;
- step = dprop.step.getNumber();
- name = dprop.name;
- version = dprop.version;
- author = dprop.author;
- countag = 0;
- history = 0;
- lasdate = myfile.getDate(); // Today if not defined in the properties
-
- state = dprop.state;
- if (state == null) {
- state = ProgressState.inWORK; // Promoted when saving this document
- version = new Revision().toString();
- }
- Study owner = null;
- if (dprop.owner instanceof Study) owner = (Study)dprop.owner;
- else owner = ((Scenario)dprop.owner).getOwnerStudy();
-
- ProjectSettings.Step step = ProjectSettings.getStep(this.step);
- SimpleDateFormat tostring = new SimpleDateFormat("yyyy");
- String year = tostring.format(owner.getDate());
- if (name == null) { // Newed document
- this.name = "%n"; // Named later at publication
- this.history = -1; // Marks the document as undefined for future assignment
- }
- String filename = generateEncodedName(owner);
- String path;
-
- path = owner.getReference();
- did = new StringBuffer(path).append(".%").append(suformat).toString(); // Document reference
- path = new StringBuffer(year).append("/").append(path).append("/").append(step.getPath()) // File path relative to the repository vault
- .append(filename).append(".").append(myfile.getFormat()) // File name and extension
- .toString();
- myfile.changePath(path);
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public File getAttachedFile (String format) {
-// -------------------------------------------
- List<Relation> exports = getRelations(ConvertsRelation.class);
-
- for (Iterator<Relation> i=exports.iterator(); i.hasNext(); ) {
- File export = (File)i.next().getTo();
- if (export.getFormat().equals(format)) return export;
- }
- return null;
- }
-
- public User getAuthor () {
-// ------------------------
- return author;
- }
-
- public Date getCreationDate () {
-// ------------------------------
- return myfile.getDate();
- }
-
- public Date getLastModificationDate () {
-// --------------------------------------
- return lasdate;
- }
-
- public String getFormat () {
-// --------------------------
- return myfile.getFormat();
- }
-
- public Document getPreviousVersion () {
-// -------------------------------------
- Relation previous = getFirstRelation(VersionsRelation.class);
- if (previous != null) return (Document)previous.getTo();
- else return null;
- }
-
- public ProgressState getProgressState () {
-// ----------------------------------------
- return state;
- }
-
-/**
- * Returns the path where all physical files attached to this document are saved.
- * This path is relative to the vault of the repository and include the file name, without extension, common
- * to all physical files attached to this document.
- *
- * @return the path of the document
- */
- public String getRelativePath () {
-// --------------------------------
- String[] table = myfile.getRelativePath().split("\\x2E");
- StringBuffer path = new StringBuffer(table[0]);
- for (int i=1; i<table.length-1; i++) path.append('.').append(table[i]);
- return path.toString();
- }
-
-/**
- * Returns the global unique reference of this document lineage.
- * The document reference is common to all versions of the document (versioning a document does not change its reference).
- * It is made of the owner study reference suffixed by a document identifier unique in the scope of the study.
- *
- * @return the document reference
- */
- public String getReference () {
-// -----------------------------
- return did;
- }
-
- public java.io.File getSaveDirectory () {
-// ---------------------------------------
- String mypath = Database.getRepositoryVaultPath() + myfile.getRelativePath();
- String[] table = mypath.split("/");
-
-// Cutting the filename
- StringBuffer path = new StringBuffer(table[0]);
- for (int i=1; i<table.length-1; i++) path = path.append("/").append(table[i]);
- return new java.io.File(path.append("/").toString());
- }
-
- public File getSourceFile () {
-// ----------------------------
- return myfile;
- }
-
-/**
- * Returns the stamps such as review and approval attached to this document, if exist.
- * If several stamps exist, they are returned in ascending order of dates.
- *
- * @return the stamps of the document in ascending order of dates, or an empty array if no stamp exist.
- */
- public Timestamp[] getStamps () {
-// -------------------------------
- Vector<Timestamp> stamps = new Vector<Timestamp>();
-
- for (Iterator<Relation> i=this.getAllRelations().iterator(); i.hasNext(); ) {
- Relation link = i.next();
- if (link instanceof StampRelation) stamps.add( ((StampRelation)link).getTo() );
- }
- Timestamp[] result = stamps.toArray( new Timestamp[stamps.size()] );
- ComparatorByDate bydate = new Timestamp.ComparatorByDate();
-
- Arrays.sort(result, bydate);
- return result;
- }
-
-/**
- * Returns the title of this document.
- *
- * @return the document title, or an empty string is this document is undefined.
- * @see #isUndefined()
- */
- public String getTitle () {
-// -------------------------
- if (this.isUndefined()) return "";
- else return name;
- }
-
- public DocumentType getType () {
-// ------------------------------
- return type;
- }
-
-/**
- * Returns the version number of this document.
- * The version number, when exists, is either of the internal form (m.n.s) usable for building a Revision object, or any string
- * in case of external document (document with EXTERN state).<br/>
- * <br/>
- * Note: document slots have a version number equal to "0.0.0".
- *
- * @return the version number of this document, or null if this is EXTERN.
- * @see #isUndefined()
- */
- public String getVersion () {
-// ---------------------------
- return version;
- }
-
-/**
- * Returns true if this document is undefined.
- * An undefined document is a meta-document created for reserving the persistent reference of a new document before saving
- * (or importing) this later into the repository.
- * The working copy of a such document may include this reference.
- *
- * @see #getTitle()
- * @see #getVersion()
- * @see #initialize(Properties)
- */
- public boolean isUndefined () {
-// -----------------------------
- return (history == -1);
- }
-
- public boolean isInto (Step container) {
-// --------------------------------------
- return (step == container.getNumber());
- }
-
- public boolean isPublished () {
-// -----------------------------
- return (countag > 0);
- }
-
- public boolean isShared () {
-// --------------------------
- return (countag + history > 1);
- }
-
- public boolean isVersioned () {
-// -----------------------------
- return (history > 0);
- }
-
-// ==============================================================================================================================
-// Public services
-// ==============================================================================================================================
-
- public static DocumentType createType (DocumentType.Properties tprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, RuntimeException {
-// ---------------------------------------------------------------------
-//TODO: Check for duplicate definition
- DocumentType type = new DocumentType(tprop);
- Session session = Database.getSession();
- session.save(type);
-
- return type;
- }
-
- public static Properties extractProperties (java.io.File file) {
-// --------------------------------------------------------------
- Properties fprop = new Properties();
- Reader tool = Toolbox.getReader(file);
- String value;
- if (tool != null) try {
- value = tool.extractProperty("title");
- if (value != null) fprop.setName(value);
-
- value = tool.extractProperty("reference");
- if (value != null) fprop.setReference(value);
- }
- catch (Exception e) {
- }
- return fprop;
- }
-
- @SuppressWarnings("unchecked")
- public static List<DocumentType> selectAllTypes () {
-// --------------------------------------------------
- String query = "from DocumentType";
-
- List<DocumentType> types = Database.getSession().createQuery(query).list();
- for (Iterator<DocumentType> i=types.iterator(); i.hasNext();) {
- Hibernate.initialize(i.next()); // Supposed fetching document types
- }
- return types;
- }
-
- @SuppressWarnings("unchecked")
- public static List<DocumentType> selectResultTypes () {
-// -----------------------------------------------------
- String query = "from DocumentType where result is not null order by result asc";
-
- return Database.getSession().createQuery(query).list();
- }
-
- public static DocumentType selectType (String name) {
-// ---------------------------------------------------
- String query = new StringBuffer("from DocumentType where name='").append(name).append("'").toString();
-
- return (DocumentType)Database.getSession().createQuery(query).uniqueResult();
- }
-
- public static DocumentType selectType (int index) {
-// -------------------------------------------------
- String query = new StringBuffer("from DocumentType where rid='").append(index).append("'").toString();
-
- return (DocumentType)Database.getSession().createQuery(query).uniqueResult();
- }
-
- @SuppressWarnings("unchecked")
- public static List<DocumentType> selectTypesOf (ProjectSettings.Step step) {
-// --------------------------------------------------------------------------
- Integer number = step.getNumber();
- String query = new StringBuffer("from DocumentType").append(" where step like '%-").append(number).append("-%'").toString();
-
- List<DocumentType> types = Database.getSession().createQuery(query).list();
- for (Iterator<DocumentType> i=types.iterator(); i.hasNext();) {
- Hibernate.initialize(i.next()); // For fetching document types
- }
- return types;
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected ConvertsRelation attach (String format) {
-// -------------------------------------------------
- return attach(format, null);
- }
-
- protected ConvertsRelation attach (String format, String description) {
-// ---------------------------------------------------------------------
- String path = this.getRelativePath();
- File export = new File(path + "." + format);
- ConvertsRelation attach = new ConvertsRelation(this, export, description);
- Session session = Database.getSession();
-
- session.save(export);
- session.save(attach);
-
- this.addRelation(attach); // Updates this
-
- return attach;
- }
-
- protected boolean buildReferenceFrom (ProjectElement scope, Document lineage) {
-// -----------------------------------------------------------------------------
- if (state != ProgressState.inWORK) return false;
- Study owner = null;
- Scenario context = null;
- if (scope instanceof Study) owner = (Study)scope;
- else {
- context = ((Scenario)scope);
- owner = context.getOwnerStudy();
- }
- did = lineage.did;
- if (context != null && (lineage.isVersioned() || owner.shares(lineage))) {
- version = new Revision(version).setBranch(context.getReference()).toString();
- }
- return true;
- }
-
- protected boolean buildReferenceFrom (Study scope) {
-// --------------------------------------------------
- if (state != ProgressState.inWORK && state != ProgressState.EXTERN) return false;
- DecimalFormat tostring = new DecimalFormat(suformat);
-
- did = did.replace ("%" + suformat, tostring.format(scope.getLastLocalIndex()));
- return true;
- }
-
- protected boolean demote () {
-// ---------------------------
- ValidationStep torem;
-
- if (state == ProgressState.inCHECK) {
- state = ProgressState.inDRAFT;
- torem = ValidationStep.REVIEW;
-// This operation must not change the version number of documents.
-// Consequently, inDRAFT documents may have a minor version number equal to zero.
- } else
- if (state == ProgressState.inDRAFT) {
- state = ProgressState.inWORK;
- torem = ValidationStep.PROMOTION;
- } else {
- return false;
- }
- for (Iterator<Relation> i=this.getAllRelations().iterator(); i.hasNext(); ) {
- Relation link = i.next();
- if (!(link instanceof StampRelation)) continue;
- if (((StampRelation)link).getStampType() != torem) continue;
- i.remove();
- break;
- }
- Database.getSession().update(this);
- return true;
- }
-
-/**
- * Increments the reference count of this document following its publication into a Study step.
- *
- * @see #release()
- */
- protected void hold () {
-// ----------------------
- countag += 1;
- if (this.isSaved()) Database.getSession().update(this);
- }
-
-/**
- * Defines this document.
- *
- * @param dprop the properties of the document
- *
- * @see Step#createDocument(Properties)
- * @see #isUndefined()
- */
- protected void initialize (Properties dprop) throws MissedPropertyException, InvalidPropertyException, NotApplicableException {
-// --------------------------------------------
- if (!this.isUndefined()) throw new NotApplicableException("Cannot initialize an existing Document");
- if (dprop.name == null) throw new MissedPropertyException("name");
- if (dprop.name.length() == 0) throw new InvalidPropertyException("name");
- if (dprop.owner == null) throw new MissedPropertyException("owner");
-// if (dprop.owner instanceof Study && !ProjectSettings.getStep(step).appliesTo(Study.class)) {
-// throw new InvalidPropertyException("step");
-// }
- name = dprop.name;
- myfile.changePath( myfile.getRelativePath().replace("%n", getEncodedRootName((Study)dprop.owner)) );
- if (history == -1) history = 0;
- if (dprop.date == null) {
- Calendar current = Calendar.getInstance();
- lasdate = current.getTime(); // Today
- } else {
- lasdate = dprop.date;
- }
- Database.getSession().update(this);
- }
-
- protected boolean promote (Timestamp stamp) {
-// -------------------------------------------
- ProgressState newstate = null;
-
- if (state == ProgressState.inWORK) {
- newstate = ProgressState.inDRAFT; // Promotion to being reviewed
- } else
- if (state == ProgressState.inDRAFT) {
- newstate = ProgressState.inCHECK; // Promotion to approval
- Revision myvers = new Revision(version);
- if (myvers.isMinor()) {
- version = myvers.incrementAs(newstate).toString();
-//TODO: If my physical file is programatically editable, update its (property) version number
-//ISSUE: What about attached files such as PDF if exist, should we remove them ?
- }
- } else
- if (state == ProgressState.inCHECK) {
- newstate = ProgressState.APPROVED;
- }
- this.state = newstate;
- if (stamp != null) this.addRelation( stamp.getContext() );
- Database.getSession().update(this);
- return true;
- }
-
-/**
- * Decrements the reference count of this document following the removal of a Publication from a Study step.
- *
- * @see #hold()
- */
- protected void release () {
-// -------------------------
- countag -= 1;
- if (this.isSaved()) Database.getSession().update(this);
- }
-
- protected void rename (String title) throws InvalidPropertyException {
-// ------------------------------------
- if (title.length() == 0) throw new InvalidPropertyException("name");
-
- Calendar current = Calendar.getInstance();
- this.name = title;
- this.lasdate = current.getTime(); // Today
- Database.getSession().update(this);
- }
-
- protected void updateAs (Revision newvers) {
-// ------------------------------------------
- version = newvers.setBranch(version).toString(); // Branch names are propagated by the versionning
- ProgressState newstate = ProgressState.inCHECK;
- if (newvers.isMinor()) newstate = ProgressState.inWORK;
- state = null; // Just to tell updateAs(sate) to not increment the version number
- updateAs(newstate);
- }
-
- protected void updateAs (ProgressState state) {
-// ---------------------------------------------
- Document previous = null;
-
-// Set of version number
- if (state == ProgressState.EXTERN) {
- if (this.state != ProgressState.EXTERN) this.version = null; // Strange use-case...
- } else {
- Revision myvers = new Revision(version);
- if (!myvers.isNull()) { // Versionning context
- for (Iterator<Relation> i=getAllRelations().iterator(); i.hasNext();) {
- Relation link = i.next();
- if (!link.getClass().equals(VersionsRelation.class)) continue;
- previous = (Document)link.getTo(); // Versioned document
- break;
- }
- }
- if (this.state != null) myvers.incrementAs(state); // Incrementation if the reversion number is not imposed
- this.version = myvers.toString();
- }
-// Update this document and the previous version, if exit
- Session session = Database.getSession();
- if (previous != null) {
- previous.history += 1;
- session.update(previous);
- }
- this.state = state;
- session.update(this);
- }
-
-// protected void upgrade () {
-// -------------------------
-// if (this.state != ProgressState.inWORK) return;
-//
-// Calendar current = Calendar.getInstance();
-// for (Iterator<Relation> i=getAllRelations().iterator(); i.hasNext();) {
-// Relation link = i.next();
-// if (!link.getClass().equals(UsesRelation.class)) continue;
-//
-// Document used = (Document)link.getTo();
-// if (!used.isVersioned()) continue;
-//TODO: Update the uses relation
-// }
-// this.promote();
-// this.lasdate = current.getTime(); // Today
-// Database.getSession().update(this);
-//
-//TODO: Promote documents using this one
-// }
-
-// ==============================================================================================================================
-// Private services
-// ==============================================================================================================================
-
- private String generateEncodedName (Study scope) {
-// ------------------------------------------------
- StringBuffer encoding = new StringBuffer();
- FileNaming scheme = ProjectSettings.getFileNamingScheme();
- DecimalFormat tostring = new DecimalFormat(suformat);
-
- int number = scope.generateLocalIndex();
-
- if (scheme == FileNaming.encoded) {
- encoding.append(scope.getReference()).append(".").append(tostring.format(number));
- } else { // title and (temporarily) asis
- encoding.append(name).append(".").append(tostring.format(number));
- }
- return encoding.toString();
- }
-
- private String getEncodedRootName (Study scope) {
-// -----------------------------------------------
- FileNaming scheme = ProjectSettings.getFileNamingScheme();
-
- if (scheme == FileNaming.encoded) return scope.getReference();
- else return name;
- }
-}
\ No newline at end of file
import java.util.Iterator;
import java.util.List;
-import org.splat.kernel.Relation;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Publication;
+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.ValidationStep;
+import org.splat.dal.bo.som.VersionsRelation;
public class DocumentRights {
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.List;
-import java.util.Set;
-import java.util.HashSet;
-
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.Persistent;
-
-
-public class DocumentType extends Persistent {
-
-// Persistent fields
- private String name;
- private ProgressState state;
- private String step; // List of (dash separated) steps (numbers) containing this type
- private String result; // Step (number ) having this type as result
- private Set<DocumentType> uses;
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Fields initialization class
- public static class Properties extends Persistent.Properties {
-// ------------------------------------------------------------
- private String name = null;
- private String step = null;
- private String result = null;
- private DocumentType[] uses = null;
-
-// - Public services
-
- public void clear () {
- super.clear();
- name = null;
- step = null;
- result = null;
- uses = null;
- }
-// - Setters of DocumentType properties
-
- public Properties setName (String name) throws InvalidPropertyException
- {
- if (name.length() == 0) throw new InvalidPropertyException("name");
- this.name = name;
- return this;
- }
- public Properties setResult (ProjectSettings.Step step)
- {
- this.result = String.valueOf(step.getNumber());
- return this;
- }
- public Properties setStep (ProjectSettings.Step... step)
- {
- this.step = "-";
- for (int i=0; i<step.length; i++) this.step = this.step + String.valueOf(step[i].getNumber()) + "-";
- return this;
- }
- public Properties setUses (DocumentType... type)
- {
- this.uses = type;
- return this;
- }
-// - Global validity check
-
- public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (name == null) throw new MissedPropertyException("name");
- if (step == null) throw new MissedPropertyException("path");
- }
- }
-// Database fetch constructor
- protected DocumentType () {
-// -------------------------
- }
-// Initialization constructor
- protected DocumentType (Properties dprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// -----------------------------------------
- super(dprop); // Throws one of the above exception if not valid
- name = dprop.name;
- state = ProgressState.inCHECK;
- step = dprop.step;
- result = dprop.result; // May be null
- uses = new HashSet<DocumentType>();
- if (dprop.uses != null) for (int i=0; i<dprop.uses.length; i++) uses.add(dprop.uses[i]);
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean approve () {
-// -------------------------
- if (state != ProgressState.inCHECK) return false;
- this.state = ProgressState.APPROVED; // The type name is supposed being localized
- Database.getSession().update(this);
- return true;
- }
-
- public boolean equals(Object entity) {
-// ------------------------------------
- if (entity == null) return false;
- if (entity instanceof String) {
- return this.name.equals((String)entity); // Names are unique
- } else
- if (entity instanceof DocumentType) {
- DocumentType object = (DocumentType)entity;
- int he = object.getIndex();
- int me = this.getIndex();
- if (me*he != 0) return (he == me);
- else return this.getName().equals(object.getName());
- } else {
- return false;
- }
- }
-
- public String getName () {
-// ------------------------
- return name;
- }
-
- public Set<DocumentType> getDefaultUses () {
-// -------------------------------------------
- return uses;
- }
-
- public boolean isApproved () {
-// ----------------------------
- return (state == ProgressState.APPROVED);
- }
-
-/**
- * Checks if documents of this type are attached to the given study step, either as result or content.
- *
- * @param step the involved study step
- * @return true if documents of this type are attached to the given step.
- * @see #isResultOf(org.splat.som.ProjectSettings.Step)
- */
- public boolean isContentInto (ProjectSettings.Step step) {
-// --------------------------------------------------------
- String[] path = this.step.split("-");
- for (int i=0; i<path.length; i++) {
- String value = path[i];
- if (value.length() == 0) continue;
- if (Integer.valueOf(value) == step.getNumber()) return true;
- }
- return false;
- }
-
-/**
- * Checks if documents of this type are result of any study step.
- *
- * @return true if documents of this type are result of a step.
- * @see #isStudyResult()
- * @see #isResultOf(org.splat.som.ProjectSettings.Step)
- */
- public boolean isStepResult () {
-// ------------------------------
- return (result != null);
- }
-
-/**
- * Checks if documents of this type are result of a study.
- * A document is the result of a study when it is the result of the last step of the study.
- *
- * @return true if documents of this type are result of a study.
- * @see #isStepResult()
- * @see #isResultOf(org.splat.som.ProjectSettings.Step)
- */
- public boolean isStudyResult () {
-// -------------------------------
- List<ProjectSettings.Step> step = ProjectSettings.getAllSteps();
- ProjectSettings.Step lastep = step.get( step.size()-1 );
- return (this.isResultOf(lastep));
- }
-
-/**
- * Checks if documents of this type are result of the given study step.
- *
- * @param step the involved study step
- * @return true if documents of this type are result of the given step.
- * @see #isContentInto(org.splat.som.ProjectSettings.Step)
- * @see #isStepResult()
- * @see #isStudyResult()
- */
- public boolean isResultOf (ProjectSettings.Step step) {
-// -----------------------------------------------------
- if (result == null) return false;
- return (Integer.valueOf(result) == step.getNumber());
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- * Class whose only purpose is to represent the kernel's Entity class for propagating to this package the visibility of relations
- * and attributes editing functions.
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Set;
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-import org.splat.kernel.ObjectProperties;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-
-
-public abstract class Entity extends org.splat.kernel.Entity {
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected Entity () {
- }
-// Initialization constructor
- protected Entity (ObjectProperties prop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// ----------------------------------------
- super(prop);
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected Relation addRelation (Relation link) {
-// ----------------------------------------------
- return super.addRelation(link);
- }
-
- protected Set<Relation> getAllRelations () {
-// ------------------------------------------
- return super.getAllRelations();
- }
-
- protected void removeRelation (Class<? extends Relation> type, Persistent to) {
-// -----------------------------------------------------------------------------
- super.removeRelation(type, to);
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.File" table="file" lazy="false">
-
-<!-- Properties inherited Persistent
- -->
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
-
-<!-- File properties
- -->
- <!-- String format -->
- <property name="format" column="format" access="field" not-null="true" />
-
- <!-- String path -->
- <property name="path" column="path" access="field" not-null="true" />
-
- <!-- String date -->
- <property name="date" column="date" access="field" not-null="true" />
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- * Class of meta files representing physical files under the control of Study Manager.
- * Typically, the files represented by this class are source files of Documents and exports in different formats.
- * The path of such files is relative to the vault of the repository of Study Manager.
- * When creating a Document, as the source file is produced by the caller which creates the Document, the corresponding
- * physical file may not exist at instantiation time.
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Calendar;
-import java.util.Date;
-
-import org.splat.kernel.Persistent;
-
-
-public class File extends Persistent {
-
-// Persistent fields
- protected String format;
- protected String path;
- protected Date date;
-
-// Transient fields
- private java.io.File myfile; // For optimization
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected File () {
-// -----------------
- this.myfile = null;
- }
-// Internal constructors
- protected File (String path) {
-// ----------------------------
- Calendar current = Calendar.getInstance();
- String[] table = path.split("\\x2E");
-
- this.format = table[table.length-1];
- this.path = path; // The corresponding physical file may not exist yet
- this.date = current.getTime(); // Today
- this.myfile = null;
- }
- protected File (String path, String format, Date date) {
-// ------------------------------------------------------
- this.path = path; // The corresponding physical file may not exist yet
- this.format = format; // The format name may be different from the physical file extension
- this.date = date;
- if (date == null) {
- Calendar current = Calendar.getInstance();
- this.date = current.getTime(); // Today
- }
- this.myfile = null;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-/**
- * Returns the data file associated to this meta file.
- *
- * @return the associated data file. If this meta data is an empty document, the returned file does not exist.
- */
- public java.io.File asFile () {
-// -----------------------------
- if (myfile == null) myfile = new java.io.File(Database.getRepositoryVaultPath() + path);
- return myfile;
- }
-
- public Date getDate () {
-// ----------------------
- return date;
- }
-
- public String getFormat () {
-// --------------------------
- return format;
- }
-
- public String getName () {
-// ------------------------
- return this.asFile().getName();
- }
-
- public String getRelativePath () {
-// --------------------------------
- return path;
- }
-
- public boolean exists () { // Shortcut
-// ------------------------
- return (this.asFile().exists());
- }
-
-// ==============================================================================================================================
-// Protected service
-// ==============================================================================================================================
-
- protected void changePath (String path) {
-// ---------------------------------------
- this.path = path;
- this.myfile = null;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.IDBuilder" table="refid">
-
- <!-- Integer cycle -->
- <id name="cycle" column="cycle" access="field">
- <generator class="assigned"/>
- </id>
-
- <!-- Integer base -->
- <property name="base" column="base" access="field" />
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.text.DecimalFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-
-public class IDBuilder {
-
- @SuppressWarnings("unused")
- private int cycle;
- private int base; // Number of studies created in this cycle
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
- protected IDBuilder () {
- }
- protected IDBuilder (Date date) {
-// -------------------------------
- SimpleDateFormat get = new SimpleDateFormat("yyyy");
- String year = get.format(date);
- cycle = Integer.valueOf(year);
- base = 0;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- protected String buildReference (String pattern, Study study) {
-// -------------------------------------------------------------
- char[] format = pattern.toCharArray();
- char[] ref = new char[80]; // Better evaluate the length of the generated string
- int next = base + 1;
-
- int count = 0;
- for (int i=0; i<format.length; i++) {
-
-// Insertion of attribute values
- if (format[i] == '%') {
- i += 1;
-
- if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
- int n = i;
- while (format[i] == 'y') {
- i += 1;
- if (i == format.length) break;
- }
- SimpleDateFormat tostring = new SimpleDateFormat("yyyy");
- String year = tostring.format(study.getDate());
- year = year.substring(4-(i-n), 4); // 4-(i-n) must be equal to either 0 or 2
- for (int j=0; j<year.length(); j++) {
- ref[count] = year.charAt(j);
- count += 1;
- }
- i -= 1; // Back to the last 'y' character
- } else
- if (format[i] == '0') { // Insertion of the index
- int n = i;
- while (format[i] == '0') {
- i += 1;
- if (i == format.length) break;
- }
- DecimalFormat tostring = new DecimalFormat(pattern.substring(n, i));
- String number = tostring.format(next);
- for (int j=0; j<number.length(); j++) {
- ref[count] = number.charAt(j);
- count += 1;
- }
- i -= 1; // Back to the last '0' character
- }
-// Keep the character
- } else {
- ref[count] = format[i];
- count += 1;
- }
- }
-// Incrementation of the number of study
- base = next;
- Database.getSession().update(this);
- return String.copyValueOf(ref, 0, count);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-
-import org.apache.lucene.analysis.standard.StandardAnalyzer;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.Term;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.FSDirectory;
-import org.apache.lucene.store.LockObtainFailedException;
-import org.apache.lucene.util.Version;
-import org.splat.kernel.User;
-
-
-class Index {
-
- private Directory index;
- private org.apache.lucene.document.Document body;
-
- protected static StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
- private static final Logger logger = Logger.getLogger(Index.class);
-
- private class Entry extends IndexWriter {
-// ---------------------------------------
- private org.apache.lucene.document.Document entry;
-
- private Entry (Study study) throws CorruptIndexException, LockObtainFailedException, IOException
- {
- super(index, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
-
-// Addition of mandatory fields
- entry = new org.apache.lucene.document.Document();
- Field field;
- field = body.getField("index");
- field.setValue(String.valueOf(study.getIndex()));
- entry.add(field);
- field = body.getField("class");
- field.setValue("Study");
- entry.add(field);
- field = body.getField("type");
- field.setValue(""); // Reserved for configurable Study type
- entry.add(field);
- field = body.getField("ref");
- field.setValue(study.getReference());
- entry.add(field);
- field = body.getField("area");
- field.setValue(study.getVisibility().toString());
- entry.add(field);
- field = body.getField("state");
- field.setValue(study.getProgressState().toString());
- entry.add(field);
- field = body.getField("author");
- field.setValue(study.getAuthor().toString());
- entry.add(field);
- field = body.getField("title");
- field.setValue(study.getTitle());
- entry.add(field);
- field = body.getField("contents");
- field.setValue(study.getTitle());
- entry.add(field);
-
-// Addition of optional fields
- setActorsOf(study);
- setContextAt(study.getSteps());
- }
- private Entry (KnowledgeElement kelm) throws CorruptIndexException, LockObtainFailedException, IOException
- {
- super(index, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
-
-// Addition of mandatory fields
- entry = new org.apache.lucene.document.Document();
- Field field;
- field = body.getField("index");
- field.setValue(String.valueOf(kelm.getIndex()));
- entry.add(field);
- field = body.getField("class");
- field.setValue("KnowledgeElement");
- entry.add(field);
- field = body.getField("type");
- field.setValue(kelm.getType().getName());
- entry.add(field);
- field = body.getField("ref");
- field.setValue(kelm.getReference());
- entry.add(field);
- field = body.getField("area");
- field.setValue(kelm.getVisibility().toString());
- entry.add(field);
- field = body.getField("state");
- field.setValue(kelm.getProgressState().toString());
- entry.add(field);
- field = body.getField("author");
- field.setValue(kelm.getAuthor().toString());
- entry.add(field);
- field = body.getField("title");
- field.setValue(kelm.getTitle());
- entry.add(field);
- field = body.getField("contents");
- field.setValue(kelm.getTitle());
- entry.add(field);
-
-//TODO: Addition of optional fields
- Scenario scene = kelm.getOwnerScenario();
- Study study = scene.getOwnerStudy();
- setActorsOf(study); // For restricting the visibility of knowledges attached to private studies
- setContextAt(study.getSteps());
- setContextAt(scene.getSteps());
- }
- private void add () throws CorruptIndexException, IOException
- {
- addDocument(entry);
-// Save the new entry
- optimize(); // Should be called before committing the index
- close(); // Commits the index
- }
- private void update () throws CorruptIndexException, IOException
- {
- String value = entry.getField("ref").stringValue(); // Only field with unique value
- Term term = new Term("ref").createTerm(value);
- updateDocument(term, entry);
-// Save the updated entry
- optimize(); // Should be called before committing the index
- close(); // Commits the index
- }
- private void setContextAt (Step[] step)
- {
- for (int i=0; i<step.length; i++) {
- List<SimulationContext> contexts = step[i].getAllSimulationContexts();
- for (Iterator<SimulationContext> j=contexts.iterator(); j.hasNext();) {
- SimulationContext context = j.next();
- String type = String.valueOf(context.getType().getIndex());
- String value = context.getValue();
- entry.add( new Field(type, value, Field.Store.NO, Field.Index.NOT_ANALYZED) );
- }
- }
- }
- private void setActorsOf (Study study)
- {
- Set<User> actors = study.getActors();
- for (Iterator<User> i=actors.iterator(); i.hasNext(); ) {
- String value = i.next().toString();
- entry.add( new Field("actor", value, Field.Store.NO, Field.Index.NOT_ANALYZED) );
- }
- }
- }
- public static class ObjectProxy implements Proxy, Serializable {
-// --------------------------------------------------------------
- private int rid;
- private String sid;
- private ProgressState state;
- private String title;
- private String type;
- private String name;
- private static final long serialVersionUID = -4386494192709562221L;
-
- public ObjectProxy (org.apache.lucene.document.Document ludoc) {
- rid = Integer.valueOf(ludoc.get("index"));
- sid = ludoc.get("ref");
- state = ProgressState.valueOf(ludoc.get("state"));
- title = ludoc.get("title");
- name = ludoc.get("author");
- }
- public String getAuthorName () {
- return name;
- }
- public Integer getIndex () {
- return rid;
- }
- public ProgressState getProgressState () {
- return state;
- }
- public String getReference () {
- return sid;
- }
- public String getTitle () {
- return title;
- }
- public String getType () {
- return type;
- }
- }
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
- protected static void create () throws IOException {
-// -------------------------------
- Directory index = FSDirectory.open(Database.getRepositoryIndexDirectory());
- IndexWriter writer = new IndexWriter(index, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
- writer.close(); // ==== Creates an empty index
- }
-
- protected Index () throws IOException {
-// ------------------
- File indir = Database.getRepositoryIndexDirectory();
- index = FSDirectory.open(indir);
- body = new org.apache.lucene.document.Document();
- body.add( new Field("index", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
- body.add( new Field("class", "", Field.Store.NO, Field.Index.NOT_ANALYZED) );
- body.add( new Field("type", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
- body.add( new Field("ref", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
- body.add( new Field("area", "", Field.Store.NO, Field.Index.NOT_ANALYZED) );
- body.add( new Field("state", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
- body.add( new Field("author", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
- body.add( new Field("title", "", Field.Store.YES, Field.Index.NOT_ANALYZED) );
- body.add( new Field("contents","", Field.Store.NO, Field.Index.ANALYZED) );
- }
-
-// ==============================================================================================================================
-// Member functions
-// ==============================================================================================================================
-
- protected void add (Study study) throws IOException {
-// --------------------------------
- Index.Entry entry = new Entry(study);
- entry.add();
- if (logger.isInfoEnabled()) {
- logger.info("Study \"" + study.getIndex() + "\" indexed.");
- }
- }
-
- protected void add (KnowledgeElement kelm) throws IOException {
-// ------------------------------------------
- Index.Entry entry = new Entry(kelm);
- entry.add();
- if (logger.isInfoEnabled()) {
- logger.info("Knowledge \"" + kelm.getIndex() + "\" indexed.");
- }
- }
-
- protected boolean exists () {
-// ---------------------------
- try {
- return IndexReader.indexExists(index);
- }
- catch (IOException error) {
- error.printStackTrace();
- return false;
- }
- }
-
- protected void update (Study study) throws IOException {
-// -----------------------------------
- Index.Entry entry = new Entry(study);
- entry.update();
- if (logger.isInfoEnabled()) {
- logger.info("Study \"" + study.getIndex() + "\" re-indexed.");
- }
- }
-
- protected void update (KnowledgeElement kelm) throws IOException {
-// ---------------------------------------------
- Index.Entry entry = new Entry(kelm);
- entry.update();
- if (logger.isInfoEnabled()) {
- logger.info("Knowledge \"" + kelm.getIndex() + "\" re-indexed.");
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.KnowledgeElement" table="knowelm" lazy="false">
-
-<!-- Properties inherited Persistent
- -->
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
-
-<!-- KnowledgeElement properties
- -->
- <!-- KnowledgeElementType type -->
- <many-to-one name="type" column="type" access="field" not-null="true" />
-
- <!-- String title -->
- <property name="title" column="title" access="field" not-null="true" />
-
- <!-- String value -->
- <property name="value" type="text" column="value" access="field" not-null="true" />
-
- <!-- Scenario owner -->
- <many-to-one name="owner" column="owner" access="field" not-null="true" />
-
- <!-- ProgressState state -->
- <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
-
- <!-- User author -->
- <many-to-one name="author" column="author" access="field" not-null="true" />
-
- <!-- Date date -->
- <property name="date" column="date" access="field" not-null="true" />
-
- </class>
-
-<!-- Class KnowledgeElementType
- -->
- <class name="org.splat.som.KnowledgeElementType" table="knowtype" lazy="false">
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
- <property name="name" column="name" access="field" not-null="true" />
- <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.text.DecimalFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.Vector;
-
-import org.hibernate.Session;
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.User;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-
-
-public class KnowledgeElement extends Persistent {
-
- private KnowledgeElementType type; // User extendable types
- private Scenario owner;
- private ProgressState state;
- private String title;
- private String value;
- private User author;
- private Date date;
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Fields initialization class
- public static class Properties extends Persistent.Properties {
-// ------------------------------------------------------------
- private String kid = null; // Search criterion only
- private KnowledgeElementType type = null;
- private Scenario owner = null;
- private Visibility visibility = null; // Search criterion only
- private ProgressState state = null;
- private String title = null;
- private String value = null;
- private User author = null;
- private User actor = null; // Search criterion only
- private Date date = null;
- private List<SimulationContext> context = new Vector<SimulationContext>(); // Search criterion only
-
-// - Public services
-
- public void clear () {
- super.clear();
- kid = null;
- type = null;
- owner = null;
- visibility = null;
- state = null;
- title = null;
- value = null;
- author = null;
- actor = null;
- date = null;
- context = new Vector<SimulationContext>(); // as clear() may generate side effects
- }
- public Properties copy () {
- Properties copy = new Properties();
- copy.kid = this.kid;
- copy.type = this.type;
- copy.owner = this.owner;
- copy.visibility = this.visibility;
- copy.state = this.state;
- copy.title = this.title;
- copy.value = this.value;
- copy.author = this.author;
- copy.actor = this.actor;
- copy.date = this.date;
- copy.context = this.context;
- return copy;
- }
-// - Protected services
-
- protected User getActor () {
- return actor;
- }
- protected User getAuthor () {
- return author;
- }
- protected ProgressState getProgressState () {
- return state;
- }
- protected String getReference () {
- return kid;
- }
- protected List<SimulationContext> getSimulationContexts () {
- return context;
- }
- protected String getTitle () {
- return title;
- }
- protected KnowledgeElementType getType () {
- return type;
- }
- protected Visibility getVisibility () {
- return visibility;
- }
-// - Property setters
-
-// For building a search query
- public Properties setActor (User actor)
- {
- this.actor = actor;
- return this;
- }
- public Properties setAuthor (User user)
- {
- this.author = user;
- return this;
- }
- public Properties setDate (Date date)
- {
- this.date = date;
- return this;
- }
- protected Properties setOwnerScenario (Scenario owner)
- {
- this.owner = owner;
- return this;
- }
-// For building a search query
- public Properties setReference (String kid) throws InvalidPropertyException
- {
- if (kid.length() == 0) throw new InvalidPropertyException("reference");
- this.kid = kid;
- return this;
- }
-// For building a search query
- public Properties setSimulationContexts (List<SimulationContext> context) {
- this.context = context;
- return this;
- }
- public Properties setState (ProgressState state) throws InvalidPropertyException
- {
- if (state != ProgressState.inWORK && state != ProgressState.inDRAFT && state != ProgressState.inCHECK && state != ProgressState.APPROVED) {
- throw new InvalidPropertyException("state");
- }
- this.state = state;
- return this;
- }
- public Properties setTitle (String title) throws InvalidPropertyException
- {
- if (title.length() == 0) throw new InvalidPropertyException("title");
- this.title = title;
- return this;
- }
- public Properties setType (KnowledgeElementType type)
- {
- this.type = type;
- return this;
- }
- public Properties setValue (String value) throws InvalidPropertyException
- {
- if (value.length() == 0) throw new InvalidPropertyException("value");
- this.value = value;
- return this;
- }
-// For building a search query
- public Properties setVisibility (Visibility area)
- {
- this.visibility = area;
- return this;
- }
-// - Global validity check
-
- public void checkValidity () throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (type == null) throw new MissedPropertyException("type");
- if (owner == null) throw new MissedPropertyException("owner");
- if (title == null) throw new MissedPropertyException("title");
- if (value == null) throw new MissedPropertyException("value");
- if (author == null) throw new MissedPropertyException("author");
- }
- }
-// Database fetch constructor
- protected KnowledgeElement () {
- }
-// Internal constructor
- protected KnowledgeElement (Properties kprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
- super(kprop); // Throws one of the above exception if not valid
- type = kprop.type;
- owner = kprop.owner;
- title = kprop.title;
- author = kprop.author;
-
- date = kprop.date;
- if (date == null) {
- Calendar current = Calendar.getInstance();
- date = current.getTime(); // Today
- }
- state = kprop.state;
- if (state == null) {
- if (type.isReserved()) state = ProgressState.inWORK;
- else state = ProgressState.inDRAFT;
- }
- value = kprop.value.trim();
- if (!value.startsWith("<p>")) {
- StringBuffer text = new StringBuffer("<p>");
- int index = value.indexOf("<p>");
- if (index > 0) {
- value = text.append(value.substring(0, index)).append("</p>").append(value.substring(index)).toString();
- } else {
- value = text.append(value).append("</p>").toString();
- }
- }
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean approve () {
-// -------------------------
- if (state != ProgressState.inCHECK) return false;
- state = ProgressState.APPROVED;
- return updateMe();
- }
-
- public boolean demote () {
-// ------------------------
- if (state != ProgressState.APPROVED && state != ProgressState.inCHECK) return false;
- state = ProgressState.inDRAFT;
- return updateMe();
- }
-
- public boolean equals (KnowledgeElement given) {
-// ----------------------------------------------
- if (isSaved()) return (this.getIndex() == given.getIndex());
- if (!this.getType().getName().equals(given.getType().getName())) return false;
- if (this.getValue().equals(given.getValue())) return true;
- return false;
- }
-
- public User getAuthor () {
-// ------------------------
- return author;
- }
-
- public Date getDate () {
-// ----------------------
- return date;
- }
-
- public Scenario getOwnerScenario () {
-// -----------------------------------
- return owner;
- }
-
- public ProgressState getProgressState () {
-// ----------------------------------------
- return state;
- }
-
- public String getTitle () {
-// -------------------------
- return title;
- }
-
- public String getReference () {
-// -----------------------------
- DecimalFormat toString = new DecimalFormat("00000"); // Supports 99 999 knowledge elements
- return "KE" + toString.format(this.getIndex());
- }
-
- public KnowledgeElementType getType () {
-// --------------------------------------
- return type;
- }
-
- public String getValue () {
-// -------------------------
- return value;
- }
-
- public Visibility getVisibility () {
-// ----------------------------------
- return getOwnerScenario().getOwnerStudy().getVisibility();
- }
-
- public boolean promote () {
-// -------------------------
- if (state != ProgressState.inDRAFT) return false;
- state = ProgressState.inCHECK;
- return updateMe();
- }
-
- public void rename (String title) throws InvalidPropertyException {
-// ---------------------------------
- if (title.length() == 0) throw new InvalidPropertyException("name");
- this.title = title;
- updateMe();
- }
-
- public void update (String description) {
-// ---------------------------------------
- value = description.trim();
- if (!value.startsWith("<p>")) {
- StringBuffer text = new StringBuffer("<p>");
- int index = value.indexOf("<p>");
- if (index > 0) {
- value = text.append(value.substring(0, index)).append("</p>").append(value.substring(index)).toString();
- } else {
- value = text.append(value).append("</p>").toString();
- }
- }
- Database.getSession().update(this); // No need to update the Lucene index
- }
-
-// ==============================================================================================================================
-// Public services
-// ==============================================================================================================================
-
- public static KnowledgeElementType createType (String name) throws RuntimeException {
-// -----------------------------------------------------------
-//TODO: Check for duplicate definition
- KnowledgeElementType kelt = new KnowledgeElementType(name);
- Session session = Database.getSession();
- session.save(kelt);
-
- return kelt;
- }
-
- @SuppressWarnings("unchecked")
- public static List<KnowledgeElementType> selectAllTypes () {
-// ----------------------------------------------------------
- StringBuffer query = new StringBuffer("from KnowledgeElementType");
- query = query.append(" order by rid asc");
- return Database.getSession().createQuery(query.toString()).list();
- }
-
- @SuppressWarnings("unchecked")
- public static List<KnowledgeElementType> selectTypesWhere (ProgressState state) {
-// -------------------------------------------------------------------------------
- StringBuffer query = new StringBuffer("from KnowledgeElementType where state='").append(state).append("'");
- query = query.append(" order by rid asc");
- return Database.getSession().createQuery(query.toString()).list();
- }
-
- public static KnowledgeElementType selectType (String name) {
-// -----------------------------------------------------------
- StringBuffer query = new StringBuffer("from KnowledgeElementType where name='").append(name).append("'");
- return (KnowledgeElementType)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
- public static KnowledgeElementType selectType (int index) {
-// ---------------------------------------------------------
- StringBuffer query = new StringBuffer("from KnowledgeElementType where rid='").append(index).append("'");
- return (KnowledgeElementType)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected boolean updateMe () {
-// -----------------------------
- try {
- Database.getSession().update(this);
- Database.getIndex().update(this);
- return true;
- }
- catch (Exception error) {
-// logger.error("Unable to re-index the knowledge '" + getIndex() + "', reason:", error);
- return false;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-
-
-public class KnowledgeElementType extends Persistent {
-
- private String name;
- private ProgressState state;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected KnowledgeElementType () {
- }
-// Initialization constructor
- protected KnowledgeElementType (String name) {
-// --------------------------------------------
- super();
- this.name = name;
- this.state = ProgressState.inCHECK;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean approve () {
-// -------------------------
- if (state != ProgressState.inCHECK) return false;
- this.state = ProgressState.APPROVED; // The type name is supposed being localized
- if (this.isSaved()) Database.getSession().update(this);
- return true;
- }
-
- public boolean equals(Object entity) {
-// ------------------------------------
- if (entity == null) return false;
- if (entity instanceof String) {
- return this.name.equals((String)entity); // Names are unique
- } else
- if (entity instanceof KnowledgeElementType) {
- KnowledgeElementType object = (KnowledgeElementType)entity;
- int he = object.getIndex();
- int me = this.getIndex();
- if (me*he != 0) return (he == me);
- else return this.getName().equals(object.getName());
- } else {
- return false;
- }
- }
-
- public String getName () {
-// ------------------------
- return name;
- }
-
- public boolean isApproved () {
-// ----------------------------
- return (state == ProgressState.APPROVED);
- }
-
- public boolean isReserved () {
-// ----------------------------
- return (state == ProgressState.inWORK);
- }
-
-// ==============================================================================================================================
-// Protected service
-// ==============================================================================================================================
-/**
- * Reserves this type for the management of simulation contexts.
- * For being able to get the studies in which simulation contexts are used, all study scenarios are indexed through this
- * knowledge element type, whether they include knowledge elements or not.
- */
- protected boolean reserve () {
-// ----------------------------
- if (state != ProgressState.inCHECK) return false;
- this.state = ProgressState.inWORK;
- if (this.isSaved()) Database.getSession().update(this);
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-public enum ProgressState {
- inPROGRESS, // Represents inWORK, inDRAFT and inCHECK states for search purpose
- inWORK, inDRAFT, inCHECK, APPROVED,
- EXTERN, // Document-specific state representing documents produced outside studies
- TEMPLATE // Study-specific state qualifying typical reference studies
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of properties common to Study and Scenario
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.ProjectElement" abstract="true">
-
-<!-- Properties inherited from Entity
- -->
- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
- <generator class="org.splat.kernel.IDGenerator"/>
- </id>
- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Attribute" />
- </set>
- <set name="relations" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Relation" />
- </set>
-
-<!-- ProjectElement properties common to Study and Scenario
- -->
- <property name="title" column="title" access="field" not-null="true" />
- <property name="credate" column="credate" access="field" not-null="true" />
- <property name="lasdate" column="lasdate" access="field" not-null="true" />
- <many-to-one name="manager" column="manager" access="field" not-null="true" />
- <list name="contex" table="projext" lazy="false" access="field">
- <key column="owner" />
- <list-index column="ordex" />
- <many-to-many column="rid" class="org.splat.som.SimulationContext" />
- </list>
- <set name="docums" inverse="true" lazy="false" order-by="`rid` desc" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.som.Publication" />
- </set>
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Collections;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.Vector;
-
-import org.apache.log4j.Logger;
-
-import org.splat.kernel.ObjectProperties;
-import org.splat.kernel.User;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-
-
-public abstract class ProjectElement extends Entity {
-
-// Persistent fields
- protected String title;
- protected User manager;
- protected Date credate; // Object creation date
- protected Date lasdate; // Object Last modification date
- private List<SimulationContext> contex; // Structured by the Step transient class
- private Set<Publication> docums; // Structured by the Step transient class
-
-// Transient field
- private Step[] folders;
-
- protected final static Logger logger = Logger.getLogger(ProjectElement.class);
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected ProjectElement () {
-// ---------------------------
- folders = null;
- }
-// Initialization constructor
- protected ProjectElement (ObjectProperties oprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// -------------------------------------------------
- super(oprop); // Throws one of the above exception if not valid
- title = null; // Initialized by subclasses
- credate = null; // Initialized by subclasses
- lasdate = null; // Initialized by subclasses
- docums = new LinkedHashSet<Publication>();
- contex = new Vector<SimulationContext>();
-
- folders = null;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public User getAuthor () {
-// ------------------------
- return manager;
- }
-
-/**
- * Returns the creation date of this Project Element.
- */
- public Date getDate () {
-// ----------------------
- return credate;
- }
-
- public String getDescription () {
-// -------------------------------
- String summary = null;
- DescriptionAttribute field = (DescriptionAttribute)this.getAttribute(DescriptionAttribute.class);
- if (field != null) summary = field.getValue();
- return summary; // May be null
- }
-
- public Step getFirstStep () {
-// ---------------------------
- return this.getSteps()[0];
- }
-
- public Date getLastModificationDate () {
-// --------------------------------------
- return lasdate;
- }
-
- public Step getLastStep () {
-// --------------------------
- Step[] mystep = this.getSteps(); // For getting the folders length, if null
- return mystep[mystep.length-1];
- }
-
-/**
- * Returns the publication into this Project Element of the given document version, if exists.
- * If exists, a document publication id unique in a given ProjectElement.
- *
- * @param doc a document version published into this Project Element
- * @return the publication of the document version, or null if the given document version is not published into this Project Element
- */
- public Publication getPublication (Document doc) {
-// ------------------------------------------------
- int index = doc.getIndex();
- for (Iterator<Publication> i=docums.iterator(); i.hasNext(); ) {
- Publication found = i.next();
- if (found.value().getIndex() == index) return found; // A document publication is unique in a given ProjectElement
- }
- return null;
- }
-
- public Step[] getSteps () {
-// -------------------------
- if (folders == null) {
- List<ProjectSettings.Step> steps = ProjectSettings.getStepsOf(this.getClass());
- Iterator<ProjectSettings.Step> nstep = steps.iterator();
-
- folders = new Step[steps.size()];
- for (int i=0; i<folders.length; i++) {
- folders[i] = new Step(nstep.next(), this);
- }
- }
- return folders; // No protection against this object corruption as it would not corrupt the database
- }
-
- public String getTitle () {
-// -------------------------
- return title;
- }
-
- public boolean publishes (Document doc) {
-// ---------------------------------------
- int index = doc.getIndex();
- for (Iterator<Publication> i=docums.iterator(); i.hasNext(); ) {
- Document found = i.next().value();
- if (found.getIndex() == index) return true;
- }
- return false;
- }
-
- public Iterator<Publication> PublicationIterator () {
-// ---------------------------------------------------
- return Collections.unmodifiableSet(docums).iterator();
- }
-
- public Iterator<SimulationContext> SimulationContextIterator () {
-// ---------------------------------------------------------------
- return Collections.unmodifiableList(contex).iterator();
- }
-
-// ==============================================================================================================================
-// Protected member functions
-// ==============================================================================================================================
-
- protected boolean add (Publication newdoc) {
-// ------------------------------------------
- return docums.add(newdoc);
- }
-
- protected boolean add (SimulationContext newdoc) {
-// ------------------------------------------------
- return contex.add(newdoc);
- }
-
- protected boolean remove (Publication oldoc) {
-// --------------------------------------------
- return docums.remove(oldoc); // The removed tag becoming orphan, it is supposed automatically deleted from the data store
- }
-
- protected boolean remove (SimulationContext oldoc) {
-// --------------------------------------------------
- return contex.remove(oldoc);
- }
-
-/**
- * Refreshes the internal data potentially out-of-date.
- * This function needs to be called when Publication objects are added to this Project Element before being saved. The reason is,
- * as saving a persistent object changes its hashcode, hashed data need to be rebuilt after saving for making functions based
- * on this hashcode such as remove(), working.
- */
- protected void refresh () {
-// -------------------------
- Publication[] curdoc = docums.toArray(new Publication[docums.size()]);
-
- folders = null; // Just in case
- docums.clear();
- for (int i=0; i<curdoc.length; i++) docums.add(curdoc[i]);
-// No need to rebuild the list of SimulationContext as it does not use hashcodes
- Database.getSession().update(this);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.sql.SQLException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-import java.util.Vector;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import org.splat.manox.XDOM;
-import org.splat.som.ValidationCycle.Actor;
-
-
-public class ProjectSettings {
-
-// Non persistent configuration information
- private Properties reprop; // Repository settings
- private String pattern; // Pattern of study references
- private FileNaming naming; // Scheme of file names stored into the repository
- private String versioning; // Pattern of the presentation of version numbers
- private Vector<Step> steps; // Ordered list of (transient) study steps
- private Vector<ValidationCycle> concycles; // Configuration document validation cycles
-
-// Temporary attributes initialized from the configuration file for populating the database with object types
- private LinkedHashMap<String,String> mapuse; // Document type names and uses mapping
- private Vector<String> context; // Simulation Context type names
- private Vector<String> kname; // Knowledge Element type names
- private Vector<NamedNodeMap> flows; // Document flows
- private Vector<NamedNodeMap> sclass; // Study classifications
-
-// Other resources
- private static ProjectSettings my = null; // Singleton instance
- protected final static Logger logger = Logger.getLogger(ProjectSettings.class);
-
- protected enum FileNaming { title, encoded, asis }
- public static class Step {
-// ------------------------
- private int number;
- private Class<? extends ProjectElement> level; // Study or Scenario
- private Set<Class<?>> contents; // Set of Document and/or Knowledge
- private String path;
-
- private Step (int number, Class<? extends ProjectElement> level, String path) {
- this.initialize(number, level, path);
- }
- private Step (int number, Class<? extends ProjectElement> level, Class<?> contents, String path) {
- this.initialize(number, level, path);
- this.contents.add(contents);
- }
- private void initialize (int number, Class<? extends ProjectElement> level, String path) {
- this.number = number;
- this.level = level;
- this.path = path + "/";
- this.contents = new HashSet<Class<?>>();
- }
- public boolean appliesTo (Class<? extends ProjectElement> level) {
- return (level == this.level);
- }
- public boolean mayContain (Class<?> type) {
- return contents.contains(type);
- }
- public int getNumber () {
- return number;
- }
- public String getPath () {
- return path;
- }
- }
- public static class ValidationCycle {
-// -----------------------------------
- private String name;
- private Actor[] actor;
-
- private ValidationCycle () {
- this.name = "built-in";
- this.actor = new Actor[] { null, null, null };
- }
- private ValidationCycle (String name, Actor[] actor) {
- this.name = name;
- this.actor = actor;
- }
- public String getName () {
- return name;
- }
- public Actor[] getActorTypes () {
- return actor;
- }
- }
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
- public static ProjectSettings getMe () {
-// --------------------------------------
- if (my == null) my = new ProjectSettings();
- return my;
- }
- protected ProjectSettings () {
-// ----------------------------
- reprop = new Properties();
- steps = new Vector<Step>();
- }
-
-// ==============================================================================================================================
-// Public functions
-// ==============================================================================================================================
-
- public void configure (String filename) throws IOException, SQLException {
-// ---------------------------------------
- if (!steps.isEmpty()) return; // Project already configured
-
- Database base = Database.getMe();
- File config = new File(filename);
- if (config.exists()) {
- loadCustomization(config);
- } else {
- logger.fatal("Could not find the database configuration file \"" + config.getAbsolutePath() + "\"");
- throw new FileNotFoundException();
- }
- base.configure(reprop);
- if (!base.isInitialized()) {
- base.initialize();
-//TODO: Move the second part of loadCustomization here
- }
- }
-
- public static List<Step> getAllSteps () {
-// ---------------------------------------
- return my.steps;
- }
-
-/**
- * Return the validation cycles of result documents defined in the workflow, ordered by study activities
- * and ending by the default validation cycle, if defined.
- *
- * @return the validation cycles of the workflow
- */
- public static List<ValidationCycle> getAllValidationCycles () {
-// -------------------------------------------------------------
- return my.concycles;
- }
-
- public static FileNaming getFileNamingScheme () {
-// -----------------------------------------------
- return my.naming;
- }
-
- public static ValidationCycle getNewValidationCycle () {
-// ------------------------------------------------------
- return new ValidationCycle();
- }
-
- public static String getReferencePattern () {
-// -------------------------------------------
- return my.pattern;
- }
-
- public static String getRevisionPattern () {
-// ------------------------------------------
- return my.versioning;
- }
-
- public static Step getStep (int number) {
-// ---------------------------------------
- for (int i=0; i<my.steps.size(); i++) {
- Step step = my.steps.get(i);
- if (step.number == number) return step;
- }
- return null;
- }
-
- public static List<Step> getStepsOf (Class<? extends ProjectElement> level) {
-// ---------------------------------------------------------------------------
- Vector<Step> result = new Vector<Step>();
-
- for (int i=0; i<my.steps.size(); i++) {
- Step step = my.steps.get(i);
- if (step.appliesTo(level)) result.add(step);
- }
- return result;
- }
-
-// ==============================================================================================================================
-// Protected member function
-// ==============================================================================================================================
-
- protected void initialize () {
-// ----------------------------
- createDocumentTypes();
- createSimulationContextTypes();
- createKnowledgeElementTypes();
- }
-
-// ==============================================================================================================================
-// Private member function
-// ==============================================================================================================================
-
- private void loadCustomization (File config) {
-// --------------------------------------------
- try {
- DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
-
- org.w3c.dom.Document conf = dBuilder.parse(config.getPath());
- HashMap<String, Node> children = XDOM.getNamedChildNodes(conf.getDocumentElement());
-
-// Repository tag initializing the reprop attribute
- Node child = children.get("database");
- HashMap<String, Node> datag = XDOM.getNamedChildNodes(child);
-
- String disk = datag.get("repository").getAttributes().getNamedItem("disk").getNodeValue();
- if (!disk.endsWith("/")) disk = disk + "/";
- logger.info("Database root set to " + disk);
- reprop.setProperty("repository", disk);
-
-// Formats tag initializing the reference pattern and date attributes
- child = children.get("formats");
- datag = XDOM.getNamedChildNodes(child);
-
- NamedNodeMap natr = datag.get("references").getAttributes();
- pattern = natr.getNamedItem("study").getNodeValue();
-
- natr = datag.get("files").getAttributes();
- naming = FileNaming.valueOf(natr.getNamedItem("name").getNodeValue());
-
- natr = datag.get("versions").getAttributes();
- versioning = natr.getNamedItem("pattern").getNodeValue();
-
-// Activities tag initializing the steps and rex attributes
- child = children.get("activities");
- NodeList nlist = child.getChildNodes();
- Vector<NamedNodeMap> flist = new Vector<NamedNodeMap>();
- Vector<String> resultype = new Vector<String>();
- Vector<NamedNodeMap> clist = new Vector<NamedNodeMap>();
-
- int snum = 1; // Base number of steps
- for (int i=0; i<nlist.getLength(); i++) {
- child = nlist.item(i);
- if (child.getNodeName().equals("scenario")) {
- NodeList slist = child.getChildNodes();
- for (int j=0; j<slist.getLength(); j++) {
- child = slist.item(j);
- if (!child.getNodeName().equals("step")) continue;
- HashMap<String, Node> tags = XDOM.getNamedChildNodes(child);
-
- natr = tags.get("storage").getAttributes();
- Step step = new Step(snum, Scenario.class, natr.getNamedItem("path").getNodeValue());
-
-// Keeping flow and classification information for eventual later use
- natr = tags.get("flow").getAttributes();
- flist.add(natr);
- child = natr.getNamedItem("result");
- if (child != null) resultype.add(child.getNodeValue());
-
- child = tags.get("classification");
- if (child != null) clist.add( child.getAttributes() );
- else clist.add( null );
-
- if (natr.getNamedItem("contents").getNodeValue().equals("knowledge")) {
-//TODO In a given scenario, only one step must contain knowledges
- step.contents.add(KnowledgeElement.class);
- } else {
- step.contents.add(Document.class);
- }
- steps.add(step);
- snum += 1;
- }
- } else {
- if (!child.getNodeName().equals("step")) continue;
- HashMap<String, Node> tags = XDOM.getNamedChildNodes(child);
-
- natr = tags.get("storage").getAttributes(); // Mandatory information
- Step step = new Step(snum, Study.class, natr.getNamedItem("path").getNodeValue());
-
-// Keeping flow and classification information for eventual later use
- natr = tags.get("flow").getAttributes();
- flist.add(natr);
- child = natr.getNamedItem("result");
- if (child != null) resultype.add(child.getNodeValue());
-
- child = tags.get("classification"); // Optional information
- if (child != null) clist.add( child.getAttributes() );
- else clist.add( null );
-
- if (natr.getNamedItem("contents").getNodeValue().equals("knowledge")) {
-//TODO Error: knowledges must be attached to scenarios
- } else {
- step.contents.add(Document.class);
- }
- steps.add(step);
- snum += 1;
- }
- }
-// Validations tag
- child = children.get("validations");
- concycles = new Vector<ValidationCycle>();
- datag = XDOM.getNamedChildNodes(child);
-
- String[] step = { "review", "approval", "acceptance" };
- resultype.add("default");
- for (Iterator<String> i=resultype.iterator(); i.hasNext(); ) {
- Actor[] actor = { null, null, null };
- String name = i.next();
- child = datag.get(name);
- if (child == null) continue; // Document type not subject of any validation
- natr = child.getAttributes();
- for (int j=0; j<step.length; j++) {
- child = natr.getNamedItem(step[j]);
- if (child == null) continue; // Validation step not required
- actor[j] = Actor.valueOf(child.getNodeValue());
- }
- concycles.add( new ValidationCycle(name, actor) );
- }
- concycles.add( new ValidationCycle() ); // Adds the built-in validation cycle
-
- if (Database.getMe().isInitialized()) return; // No need to load object type definitions as they are already stored
-
-// Documents tag
- child = children.get("documents");
- nlist = child.getChildNodes();
-
- flows = flist; // Kept for later use in document type definition
- sclass = clist; // Kept for later use in simulation context type definition
- mapuse = new LinkedHashMap<String,String>();
- for (int i=0; i<nlist.getLength(); i++) {
- child = nlist.item(i);
- if (!child.getNodeName().equals("article")) continue;
-
- natr = child.getAttributes();
- String type = natr.getNamedItem("type").getNodeValue();
- String uses = null;
- child = natr.getNamedItem("uses");
- if (child != null) uses = child.getNodeValue();
- mapuse.put(type, uses); // Must be added to the map even if no (null) uses
- }
-// Simulation Contexts tag
- child = children.get("contexts");
- nlist = child.getChildNodes();
-
- context = new Vector<String>();
- for (int i=0; i<nlist.getLength(); i++) {
- child = nlist.item(i);
- if (!child.getNodeName().equals("article")) continue;
-
- context.add(child.getAttributes().getNamedItem("type").getNodeValue());
- }
-// Knowledge Elements tag
- child = children.get("knowledges");
- nlist = child.getChildNodes();
-
- kname = new Vector<String>();
- for (int i=0; i<nlist.getLength(); i++) {
- child = nlist.item(i);
- if (!child.getNodeName().equals("article")) continue;
-
- kname.add(child.getAttributes().getNamedItem("type").getNodeValue());
- }
- }
- catch (Exception error) {
- logger.info("Error in customization", error);
- }
- }
-
- private void createDocumentTypes () {
-// -----------------------------------
- DocumentType.Properties tprop = new DocumentType.Properties();
- HashMap<String,Vector<Step>> mapsteps = new HashMap<String,Vector<Step>>();
- HashMap<String,Step> mapresult = new HashMap<String,Step>();
- HashMap<String,DocumentType> maptype = new HashMap<String,DocumentType>();
-
- Vector<Step> slist = null; // List of Steps to which each document type is valid
- int snum = 0; // Step number
- String type = null;
- String uses = null;
- for (Iterator<NamedNodeMap> i=flows.iterator(); i.hasNext(); snum++) {
- NamedNodeMap flow = i.next();
- Step step = steps.get(snum);
- String[] contents = flow.getNamedItem("contents").getNodeValue().split(",");
- for (int j=0; j<contents.length; j++) {
- type = contents[j];
- if (!mapuse.containsKey(type)) {
- logger.warn("Undefined \"" + type + "\" document type.");
- continue;
- } slist = mapsteps.get(type);
- if (slist == null) slist = new Vector<Step>();
- slist.add(step);
- mapsteps.put(type, slist);
- }
- Node result = flow.getNamedItem("result");
- if (result != null) mapresult.put(result.getNodeValue(), step);
- }
- try {
- DocumentType tdoc = null;
- Set<String> tset = mapuse.keySet();
- Step step;
- for (Iterator<String> i=tset.iterator(); i.hasNext(); ) {
- type = i.next();
- slist = mapsteps.get(type);
- uses = mapuse.get(type);
- step = mapresult.get(type);
-
- tprop.clear();
- tprop.setName(type).setStep(slist.toArray(new Step[slist.size()]));
- if (uses != null) {
- tdoc = maptype.get(uses);
- if (tdoc == null) logger.warn("Undefined \"" + uses + "\" document type.");
- else tprop.setUses(tdoc);
- }
- if (step != null) tprop.setResult(step);
-
- tprop.disableCheck();
- tdoc = Document.createType(tprop); // Creation of Document Types
- tdoc.approve();
- maptype.put(type, tdoc);
- }
- } catch (Exception error) {
- logger.warn("Error creating document types, reason:", error); // Should not happen
- }
- }
-
- private void createKnowledgeElementTypes () {
-// -------------------------------------------
- try {
- KnowledgeElementType ktype = KnowledgeElement.createType("usecase"); // Internal reserved knowledge element type
- ktype.reserve();
- for (Iterator<String> i=kname.iterator(); i.hasNext(); ) {
- String type = i.next();
-
- ktype = KnowledgeElement.createType(type); // Knowledge Elements Types defined in the configuration
- ktype.approve();
- }
- } catch (Exception error) {
- logger.warn("Error creating knowledge types, reason:", error); // Should not happen
- }
- }
-
- private void createSimulationContextTypes () {
-// --------------------------------------------
- HashMap<String,Step> mapstep = new HashMap<String,Step>();
- int snum = 0;
- for (Iterator<NamedNodeMap> i=sclass.iterator(); i.hasNext(); snum++) {
- NamedNodeMap clatr = i.next();
- if (clatr == null) continue;
-
- String[] clist = clatr.getNamedItem("context").getNodeValue().split(",");
- for (int j=0; j<clist.length; j++) {
- mapstep.put(clist[j], steps.get(snum));
- }
- }
- try {
- SimulationContextType tctex = null;
- for (Iterator<String> i=context.iterator(); i.hasNext(); ) {
- String type = i.next();
- if (!mapstep.containsKey(type)) {
- logger.warn("Could not find \"" + type + "\" classification. Simulation Context type ignored.");
- continue;
- }
- tctex = SimulationContext.createType(type, mapstep.get(type)); // Creation of Simulation Context Types
- tctex.approve();
- }
- } catch (Exception error) {
- logger.warn("Error creating context types, reason:", error); // Should not happen
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- * Stand proxy for entities such as Study and Knowledge Element returned by Lucene-based searches.
- * This interface provides access to properties of searched entities which can be presented in a result search list
- * before loading the corresponding persistent objects from the database (reason for most properties to be returned as
- * strings).
- * One of these properties is the internal persistent identifier of the object represented by a proxy allowing the
- * user of this interface to load the object from the database.
- *
- * @see Database#selectStudiesWhere(Study.Properties...)
- * @see Database#selectKnowledgeElementsWhere(KnowledgeElement.Properties)
- * @see Database#selectStudy(int)
- * @see Database#selectKnowledgeElement(int)
- * @see Index
- * @see Index.ObjectProxy
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-public interface Proxy {
-
- public String getAuthorName ();
-
-/**
- * Returns the internal persistent identifier of the object represented by this proxy. The returned identifier can be used
- * for selecting the corresponding persistent object from the database.
- * @return the internal persistent identifier of the object represented by this proxy.
- */
- public Integer getIndex ();
-
- public ProgressState getProgressState ();
-
-/**
- * Returns the external reference number of the object represented by this proxy. The returned reference is formated
- * according to the format defined in the configuration file of the application.
- * @return the external reference number of the object represented by this proxy.
- */
- public String getReference ();
-
- public String getTitle ();
-
-/**
- * Returns the type of the object represented by this proxy. Depending on the implementation, the returned type may or
- * may not be localized in the current locale of final user.
- * @return the type of the object represented by this proxy.
- */
- public String getType ();
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.Publication" table="doctag" lazy="false">
-
-<!-- Properties inherited Persistent
- -->
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
-
-<!-- Publication properties
- -->
- <!-- Document mydoc -->
- <many-to-one name="mydoc" column="doc" access="field" not-null="true" />
-
- <!-- ProjectElement owner -->
- <many-to-one name="owner" column="owner" access="field" not-null="true" />
-
- <!-- char isnew -->
- <property name="isnew" column="isnew" access="field" not-null="true" />
-
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- * Publication objects are the way to reference document versions from a Project Element.
- * As such, a Document version is added (or published) to a Project Element through a Publication object.
- * This publication is done by saving the Publication object produced when creating and versioning a Document from a given
- * Project Element Step (call of the saveAs() function).<br/>
- * <br/>
- * A Publication object is homogeneous to a reference to a Document version and belongs to one Project Element, this latter
- * being either a Study Scenario or a Study itself, depending on the Study Step to which the document is published.<br/>
- * <br/>
- * The document version referenced by a Publication object is the Value of the publication.
- *
- * @see Document
- * @see ProjectElement
- * @see Step
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-
-import org.hibernate.Session;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.NotApplicableException;
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-import org.splat.kernel.User;
-import org.splat.manox.Reader;
-import org.splat.manox.Toolbox;
-
-
-public class Publication extends Persistent {
-
-// Persistent fields
- private Document mydoc;
- private ProjectElement owner; // Either Study or Scenario, depending on the step involved by the publication
- private char isnew; // True if this references a document version new for the owner project element
-
-// Transient fields
- private Step mystep;
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected Publication () {
-// ------------------------
- mystep = null;
- }
-// Internal constructors
- protected Publication (Document doc, ProjectElement publisher) {
-// --------------------------------------------------------------
- mydoc = doc;
- mystep = null;
- owner = publisher;
- isnew = 'Y';
- }
- protected Publication copy (ProjectElement publisher) {
-// -----------------------------------------------------
- Publication copy = new Publication();
- copy.mydoc = this.mydoc;
- copy.mystep = this.mystep; // May not be initialized yet
- copy.owner = publisher;
- copy.isnew = this.isnew;
- if (!copy.getOwnerStudy().equals(this.getOwnerStudy())) {
- copy.isnew = 'N'; // The referenced document is not new for the given study
- }
- return copy;
- }
-
-// ==============================================================================================================================
-// Member functions
-// ==============================================================================================================================
-
- public Relation addDependency (Publication to) {
-// ----------------------------------------------
- return this.addDependency(to.value());
- }
-
- public Relation addDependency (Document to) {
-// -------------------------------------------
- if (to == null) return null;
- else return mydoc.addRelation( new UsesRelation(mydoc, to) );
- }
-
-/**
- * Undo the out-date operation.
- *
- * @return true if the acceptance succeeds
- * @see #outdate()
- * @see DocumentRights#canAccept()
- */
- public boolean actualize () {
-// ---------------------------
- if (!this.isOutdated()) return false;
- isnew = 'Y';
- Database.getSession().update(this);
- return true;
- }
-
-/**
- * Promotes the document referenced by this publication from In-Check to Approved state, if not out-dated, and attaches the corresponding
- * time-stamp to the document.</br>
- * If the promoted document is the final result of the owner study, the study is itself is promoted as well.</br>
- * </br>
- * Limitation: the way this promotion is propagated to the study supposes that the study has only ONE final result document.
- *
- * @param adate the date of approval
- * @return true if the approval succeeded
- * @see #getProgressState()
- * @see DocumentRights#canApprove()
- * @see DocumentType#isStudyResult()
- * @see Study#getApproverOf(Publication)
- */
- public Timestamp approve (Date adate) {
-// -------------------------------------
- if (this.isOutdated()) return null;
- else if (mydoc.getProgressState() != ProgressState.inCHECK) return null; // This statement must conform to the corresponding right
-
- DocumentType type = mydoc.getType();
- Study owner = this.getOwnerStudy();
- ValidationCycle cycle = owner.getValidationCycleOf(type);
- User approver = cycle.getActor(ValidationStep.APPROVAL);
- Timestamp stamp = new Timestamp(ValidationStep.APPROVAL, mydoc, approver, adate);
- if (!mydoc.promote(stamp)) return null;
- if (type.isStudyResult() && owner.getProgressState() == ProgressState.inCHECK) owner.promote();
- return stamp; // Hoping that promotion of the study succeeded
- }
-
- public ConvertsRelation attach (String format) {
-// ----------------------------------------------
- return mydoc.attach(format);
- }
-
- public ConvertsRelation attach (String format, String description) {
-// ------------------------------------------------------------------
- return mydoc.attach(format, description);
- }
-
-/**
- * Demotes the document referenced by this publication to In-Work state, and removes the Promoter of the document, if exist.</br>
- * The In-Draft state is skipped (direct demotion to In-Work) if the validation cycle of the document does not include the review step.</br>
- * If the demoted document is the final result of the owner study, the study is itself is demoted as well.</br>
- * </br>
- * Limitation: the way this demotion is propagated to the study supposes that the study has only ONE final result document.
- *
- * @return true if the demotion succeeded
- * @see #getProgressState()
- * @see DocumentRights#canDemote()
- * @see DocumentType#isStudyResult()
- */
- public boolean demote () {
-// ------------------------
- DocumentType type = mydoc.getType();
- Study owner = this.getOwnerStudy();
-
- if (mydoc.getProgressState() == ProgressState.inCHECK) {
- ValidationCycle cycle = owner.getValidationCycleOf(type);
- if (cycle.enables(ValidationStep.REVIEW)) {
- if (!mydoc.demote()) return false;
- } else {
- if (!mydoc.demote()) return false;
- mydoc.demote();
- }
- } else
- if (mydoc.getProgressState() == ProgressState.inDRAFT) {
- if (!mydoc.demote()) return false;
- } else {
- return false;
- }
- if (type.isStudyResult() && owner.getProgressState() != ProgressState.inWORK) owner.demote();
- return true;
- }
-
-/**
- * Returns the study Step into which the document version referenced by this publication has been published.
- */
- public Step getInvolvedStep () {
-// ------------------------------
- if (mystep == null) {
- Step[] step = owner.getSteps();
- for (int i=0; i<step.length; i++) {
- mystep = step[i]; // The involved step necessarily exists
- if (mydoc.isInto(mystep)) break;
- }
- }
- return mystep;
- }
-
-/**
- * Returns either the Study Scenario or the Study itself to which this publication belongs, depending on the Study Step into
- * which the referenced document has been published.<br/>
- * If this publication belongs to a Study, the Project Element returned is the Study returned by getOwnerStudy().
- *
- * @return the Study Scenario or the Study to which this publication belongs to
- * @see #getOwnerStudy()
- */
- public ProjectElement getOwner () {
-// ---------------------------------
- return owner;
- }
-
- public Study getOwnerStudy () {
-// -----------------------------
- if (owner instanceof Study) return (Study)owner;
- else return ((Scenario)owner).getOwnerStudy();
- }
-
-/**
- * Returns the state of this published document.
- * It is the same than the state of the referenced document, unless this publication is out-of-date, in which case it is
- * In-Work state.
- *
- * @see #outdate()
- * @see #isOutdated()
- */
- public ProgressState getProgressState () {
-// ----------------------------------------
- if (this.isOutdated()) return ProgressState.inWORK; // Overrides the document state
- else return mydoc.getProgressState();
- }
-
- public List<Publication> getRelations (Class<? extends Relation> type) {
-// ----------------------------------------------------------------------
- if (type == null) return null;
-
- List<Publication> result = new ArrayList<Publication>();
- List<Relation> relist = mydoc.getRelations(type);
- for (Iterator<Relation> i=relist.iterator(); i.hasNext();) {
- Relation relation = i.next();
- Document relatedoc = (Document)relation.getTo();
- Publication related = owner.getPublication(relatedoc);
- if (related != null) {
- result.add(related);
- } else
- if (owner instanceof Scenario) { // The relation may cross steps belonging to a scenario and its owner study
- related = ((Scenario)owner).getOwnerStudy().getPublication(relatedoc);
- if (related != null) result.add(related);
- }
- }
- return result;
- }
-
- public File getSourceFile () {
-// ----------------------------
- return mydoc.getSourceFile();
- }
-
-/**
- * Undo the review operation by demoting the document referenced by this publication from In-Check to In-Draft state and
- * removing the Reviewer.</br>
- * If the demoted document is the final result of the owner study, the study is itself is demoted as well.</br>
- * </br>
- * Limitation: the way this demotion is propagated to the study supposes that the study has only ONE final result document.
- *
- * @return true if the demotion succeeded
- * @see #getProgressState()
- * @see #review()
- * @see DocumentRights#canInvalidate()
- * @see DocumentType#isStudyResult()
- */
- public boolean invalidate () {
-// ----------------------------
- if ( mydoc.getProgressState() != ProgressState.inCHECK ) return false;
- if (!mydoc.demote()) // Removes the reviewer if this document is In-Check
- return false;
- DocumentType type = this.value().getType();
- Study owner = this.getOwnerStudy();
- if (type.isStudyResult() && owner.getProgressState() == ProgressState.inCHECK) owner.demote();
- return true;
- }
-
- public boolean isNewForOwner () {
-// -------------------------------
- return (isnew == 'Y');
- }
-
- public boolean isOutdated () {
-// ----------------------------
- return (isnew == 'O');
- }
-
-/**
- * Promotes the document referenced by this publication from In-Work to In-Draft or In-Check state, if not out-dated, and attaches the corresponding
- * time-stamp to the document.</br>
- * The In-Draft state is skipped (direct promotion to In-Check) if the validation cycle of the document does not include the review step.</br>
- * Also, if the promoted document is the final result of the owner study, the study is itself promoted as well.</br>
- * This operation can be undo-ed by demote().</br>
- * </br>
- * Limitation: the way this promotion is propagated to the study supposes that the study has only ONE final result document.
- *
- * @return true if the promotion succeeded
- * @see #getProgressState()
- * @see #demote()
- * @see DocumentRights#canPromote()
- * @see DocumentType#isStudyResult()
- */
- public Timestamp promote (Date pdate) {
-// -------------------------------------
- if (this.isOutdated()) return null;
- else if (mydoc.getProgressState() != ProgressState.inWORK) return null; // This statement must conform to the corresponding right
- else {
- DocumentType type = mydoc.getType();
- Study owner = this.getOwnerStudy();
- ValidationCycle cycle = owner.getValidationCycleOf(type);
- User promoter = cycle.getActor(ValidationStep.PROMOTION);
- if (promoter == null) promoter = getInvolvedStep().getActor();
- if (promoter == null) promoter = owner.getAuthor();
- Timestamp stamp = new Timestamp(ValidationStep.PROMOTION, mydoc, promoter, pdate);
-
- if (!mydoc.promote(stamp) ) // Promotion to being reviewed
- return null;
- if (!cycle.enables(ValidationStep.REVIEW)) {
- mydoc.promote(null);
- }
- if (type.isStudyResult() && owner.getProgressState() == ProgressState.inWORK) owner.promote();
- return stamp; // Hoping that promotion of the study succeeded
- }
- }
-
- public void rename (String title) throws InvalidPropertyException {
-// ---------------------------------
- mydoc.rename(title);
- }
-
-/**
- * Promotes the document referenced by this publication from In-Draft to In-Check state, if not out-dated, and attaches the corresponding
- * time-stamp to the document.</br>
- * If the promoted document is the final result of the owner study, the study is itself is promoted as well.</br>
- * This operation can be undo-ed by invalidate().</br>
- * </br>
- * Limitation: the way this promotion is propagated to the study supposes that the study has only ONE final result document.
- *
- * @param rdate the date of review
- * @return true if the review succeeded
- * @see #getProgressState()
- * @see #invalidate()
- * @see DocumentRights#canReview()
- * @see DocumentType#isStudyResult()
- * @see Study#getReviewerOf(Publication)
- */
- public Timestamp review (Date rdate) {
-// ------------------------------------
- if (this.isOutdated()) return null;
- else if (mydoc.getProgressState() != ProgressState.inDRAFT) return null; // This statement must conform to the corresponding right
-
- DocumentType type = mydoc.getType();
- Study owner = this.getOwnerStudy();
- ValidationCycle cycle = owner.getValidationCycleOf(type);
- User reviewer = cycle.getActor(ValidationStep.REVIEW);
- Timestamp stamp = new Timestamp(ValidationStep.REVIEW, mydoc, reviewer, rdate);
- if (!mydoc.promote(stamp)) return null;
- if (type.isStudyResult() && owner.getProgressState() == ProgressState.inDRAFT) owner.promote();
- return stamp; // Hoping that promotion of the study succeeded
- }
-
-/**
- * Publishes the document referenced by this publication into the owner Project Element under the given revision number.<br/>
- * The state of the referenced document is supposed being automatically set according to the given revision number, but, due to the
- * versioning scheme, as it is not possible to differentiate In-Work and In-Draft states, this function has been deprecated (it is
- * currently used only for the need of integration of Microsoft Office which anyway has to be redesigned).
- * <br/>
- * Note: in the context of branch versioning, the given revision may be modified by an update of the branch name.
- *
- * @param newvers the required revision number
- * @throws FileNotFoundException If the referenced document is empty
- * @throws NotApplicableException If the referenced document is undefined
- * @deprecated
- */
- public void saveAs (Revision newvers) throws FileNotFoundException, NotApplicableException {
-// -------------------------------------
- if ( mydoc.isUndefined() ) throw new NotApplicableException("Cannot save a Publication object refering an undefined Document");
- if (!mydoc.getSourceFile().exists()) throw new FileNotFoundException();
-
- Database.getSession().save(this); // Must be done before updating the study in order to fix this final (rid-based) hascode
- mydoc.updateAs(newvers); // May change the branch name of given revision
- updateOwner();
- }
-
-/**
- * Publishes the document referenced by this publication into the owner Project Element under the given state,
- * the revision number of the document being automatically set accordingly.
- * If the given state is In-Draft and the document is final result of the owner study, this automatically promotes the study to In-Draft.
- *
- * @param state the required progress state
- * @throws FileNotFoundException If the referenced document is empty
- * @throws NotApplicableException If the referenced document is undefined
- */
- public void saveAs (ProgressState state) throws FileNotFoundException, NotApplicableException {
-// ----------------------------------------
- if ( mydoc.isUndefined() ) throw new NotApplicableException("Cannot save a Publication object refering an undefined Document");
- if (!mydoc.getSourceFile().exists()) throw new FileNotFoundException();
-
- if (state == ProgressState.inWORK || state == ProgressState.EXTERN) {
- Database.getSession().save(this); // Must be done before updating the study in order to fix this final (rid-based) hascode
- mydoc.updateAs(state);
- } else {
- DocumentType mytype = mydoc.getType();
- Study owner = this.getOwnerStudy();
- ValidationCycle cycle = owner.getValidationCycleOf(mytype);
- boolean review = cycle.enables(ValidationStep.REVIEW);
- if (!(state == ProgressState.inDRAFT && review) && !(state == ProgressState.inCHECK && !review)) {
- throw new NotApplicableException("Cannot save a result document in " + state.toString() + " state");
- }
- Database.getSession().save(this); // Must be done before updating the study in order to fix this final (rid-based) hascode
- mydoc.updateAs(ProgressState.inWORK);
-
- this.promote(mydoc.getLastModificationDate()); // Promotes to the appropriate state in accordance to the validation cycle
- }
- updateOwner();
- }
-
-/**
- * Out-dates this publication and recursively all publications using this one.
- * Typically, a publication is out-dated when modifying a document to which it depends.
- *
- * @see #isOutdated()
- * @see #getProgressState()
- * @see #actualize()
- */
- public void outdate () {
-// ----------------------
- if (this.isOutdated()) return;
-
- List<Publication> relist = this.getRelations(UsedByRelation.class);
- for (Iterator<Publication> i = relist.iterator(); i.hasNext(); ) {
- i.next().outdate();
- }
- isnew = 'O';
- Database.getSession().update(this);
- }
-
-/**
- * Returns the document version referenced by this Publication.
- */
- public Document value () {
-// ------------------------
- return mydoc;
- }
-
-// ==============================================================================================================================
-// Private services
-// ==============================================================================================================================
-
- private void updateOwner () {
-// ---------------------------
- Session session = Database.getSession();
- Step step = this.getInvolvedStep();
-
-// Update of involved step
- Document previous = mydoc.getPreviousVersion();
- if (previous != null) {
- Publication oldoc = step.getDocument(previous.getIndex());
- boolean done = step.remove(oldoc); // Decrements the configuration tag count of document
- if (done) session.delete(oldoc); //WARNING: Potential problem because it's not automatically done as orphan object
- }
- step.add(this); // Increments the configuration tag count of document
-
-// Import the document properties and update of the study
- forwardProperties(mydoc.getSourceFile().asFile(), step);
- session.update(getOwner());
- }
-
- private void forwardProperties (java.io.File from, Step to) {
-// -----------------------------------------------------------
- Reader tool = Toolbox.getReader(from);
- if (tool == null) return; // No properties extractor available for this type of document
-
- SimulationContextType.Properties sprop = new SimulationContextType.Properties()
- .setStep(to.getStep())
- .setState(ProgressState.APPROVED);
- List<SimulationContextType> contype = SimulationContext.selectTypesWhere(sprop);
- if (contype.isEmpty()) return; // No approved property type configured at this step
-
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- List<SimulationContext> context = to.getAllSimulationContexts();
-
- context = new ArrayList<SimulationContext>(context.size());
- context.addAll(to.getAllSimulationContexts());
- cprop.disableCheck();
- for (Iterator<SimulationContextType> i=contype.iterator(); i.hasNext(); ) {
- SimulationContextType property = i.next();
- for (Iterator<SimulationContext> j=context.iterator(); j.hasNext(); ) {
- SimulationContext existing = j.next();
- if (!existing.getType().equals(property)) continue;
- property = null; // Forget this property as it is already set
- break;
- }
- if (property != null) try {
- String value = tool.extractProperty(property.getName());
- if (value == null) continue; // Property not defined into the document
-
- cprop.setType(property).setValue(value);
- if (owner instanceof Study) ((Study)owner).addProjectContext(cprop); // Re-indexes knowledges and the study
- else to.addSimulationContext(cprop); // Re-indexes knowledges only
- } catch (Exception e) {
- break;
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- - Mapping of the Relation class hierarchy.
- - The entire hierarchy is mapped to one single table using a String discriminator.
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
-<!-- Uses relation
- -->
- <subclass name="org.splat.som.UsesRelation" extends="org.splat.kernel.Relation" discriminator-value="uses">
- <many-to-one name="refer" column="refer" access="field" not-null="true" />
- </subclass>
-
-<!-- UsedBy relation
- -->
- <subclass name="org.splat.som.UsedByRelation" extends="org.splat.kernel.Relation" discriminator-value="usedby">
- <many-to-one name="refer" column="refer" access="field" not-null="true" />
- </subclass>
-
-<!-- Versions relation
- -->
- <subclass name="org.splat.som.VersionsRelation" extends="org.splat.kernel.Relation" discriminator-value="versions">
- <many-to-one name="refer" column="refer" access="field" not-null="true" />
- </subclass>
-
-<!-- Converts relation
- -->
- <subclass name="org.splat.som.ConvertsRelation" extends="org.splat.kernel.Relation" discriminator-value="converts">
- <many-to-one name="refer" column="refer" access="field" not-null="true" />
- </subclass>
-
-<!-- Contributor actor relation
- -->
- <subclass name="org.splat.som.ContributorRelation" extends="org.splat.kernel.Relation" discriminator-value="contributor">
- <many-to-one name="refer" column="refer" access="field" not-null="true" />
- </subclass>
-
-<!-- ValidationCycle relation
- -->
- <subclass name="org.splat.som.ValidationCycleRelation" extends="org.splat.kernel.Relation" discriminator-value="cycle">
-<!-- <many-to-one name="refer" column="refer" unique="true" cascade="all-delete-orphan" access="field" not-null="true" />-->
- <many-to-one name="refer" column="refer" unique="true" access="field" not-null="true" />
- </subclass>
-
-<!-- Stamp relation
- -->
- <subclass name="org.splat.som.StampRelation" extends="org.splat.kernel.Relation" discriminator-value="stamp">
-<!-- <many-to-one name="refer" column="refer" unique="true" cascade="all-delete-orphan" access="field" not-null="true" />-->
- <many-to-one name="refer" column="refer" unique="true" access="field" not-null="true" />
- </subclass>
-
-</hibernate-mapping>
\ No newline at end of file
import java.nio.CharBuffer;
import java.text.ParseException;
+import org.splat.dal.bo.som.ProgressState;
+
public class Revision {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <union-subclass name="org.splat.som.Scenario" extends="org.splat.som.ProjectElement" table="scenario" lazy="false">
-
- <!-- Study owner -->
- <many-to-one name="owner" column="owner" insert="false" update="false" access="field" not-null="true" />
-
- <!-- int sid -->
- <property name="sid" column="sid" access="field" not-null="true" />
-
- <!-- User cuser -->
- <many-to-one name="cuser" column="cuser" access="field" />
-
- <!-- Set<KnowledgeElement> kelms -->
- <set name="kelms" inverse="true" lazy="false" order-by="`type`,`date` asc" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.som.KnowledgeElement" />
- </set>
-
- </union-subclass>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.IOException;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Vector;
-
-import org.hibernate.HibernateException;
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-import org.splat.kernel.Persistent;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.User;
-
-
-public class Scenario extends ProjectElement {
-
-// Persistent fields
- private Study owner;
- private int sid; // Identifier unique in the scope of owner study
- private User cuser; // User having checked-out the scenario, if done
- private Set<KnowledgeElement> kelms;
-
-// Transient fields
- private HashMap<Integer, List<KnowledgeElement>> known;
- private List<KnowledgeElement> knowl; // Copy of kelms excluding the internal Knowledge Element (ucase below)
- private KnowledgeElement ucase; // Internal Knowledge Element for accessing to all used simulation contexts
-
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Fields initialization class
- public static class Properties extends Persistent.Properties {
-// ------------------------------------------------------------
- private Study owner = null;
- private Scenario previous = null;
- private Step base = null;
- private String title = null;
- private String summary = null;
- private User manager = null;
- private Date date = null;
-
-// - Public services
-
- public void clear () {
- super.clear();
- owner = null;
- previous = null;
- base = null;
- title = null;
- summary = null;
- manager = null;
- date = null;
- }
-// - Protected services
-
- protected Step getBaseStep () {
- return base; // May be null
- }
- protected Scenario getInsertAfter () {
- return previous; // May be null
- }
- protected User getManager () {
- return manager;
- }
- protected Properties setOwnerStudy (Study owner)
- {
- this.owner = owner;
- return this;
- }
-// - Setters of Scenario properties
-
- public Properties setBaseStep (Step base) throws InvalidPropertyException
- {
- if (!(base.getOwner() instanceof Scenario)) throw new InvalidPropertyException("step");
- this.base = base;
- return this;
- }
- public Properties setDate (Date date)
- {
- this.date = date;
- return this;
- }
- public Properties setDescription (String summary)
- {
- if (summary.length() > 0) this.summary = summary;
- return this;
- }
- public Properties setInsertAfter (Scenario previous)
- {
- this.previous = previous;
- return this;
- }
- public Properties setManager (User user)
- {
- this.manager = user;
- return this;
- }
- public Properties setTitle (String title) throws InvalidPropertyException
- {
- if (title.length() == 0) throw new InvalidPropertyException("title");
- this.title = title;
- return this;
- }
-// - Global validity check
-
- public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (owner == null) throw new MissedPropertyException("owner");
- if (title == null) throw new MissedPropertyException("title");
- if (manager == null) throw new MissedPropertyException("manager");
- }
- }
-// Database fetch constructor
- protected Scenario () {
-// ---------------------
- known = null;
- knowl = null;
- ucase = null;
- }
-// Internal constructor
- protected Scenario (Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// -------------------------------------
- super(sprop); // Throws one of the above exception if not valid
- owner = sprop.owner;
- sid = 0;
- cuser = null;
- title = sprop.title; // Inherited attribute
- known = null;
- knowl = null; // Initialized when getting all Knowledge Elements
- ucase = null;
- kelms = new HashSet<KnowledgeElement>();
-
- manager = sprop.manager;
- if (!owner.isStaffedBy(manager)) throw new InvalidPropertyException("manager");
-
- credate = sprop.date; // Inherited attribute
- if (credate == null) {
- Calendar current = Calendar.getInstance();
- credate = current.getTime(); // Today
- }
- lasdate = credate; // Inherited attribute
-
- if (sprop.summary != null) this.setAttribute( new DescriptionAttribute(this, sprop.summary) );
-
- Scenario[] scene = owner.getScenarii();
- for (int i=0; i<scene.length; i++) if (scene[i].sid > this.sid) this.sid = scene[i].sid;
- sid += 1;
- if (sprop.base != null) copyContentsUpTo(sprop.base);
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public KnowledgeElement addKnowledgeElement (KnowledgeElement.Properties kprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// -------------------------------------------------------------------------------
- KnowledgeElement kelm = new KnowledgeElement(kprop.setOwnerScenario(this));
- Session session = Database.getSession();
- Transaction transax = session.getTransaction();
- try {
- session.save(kelm);
-// Update of my persistent data
- kelms.add(kelm);
-// Update of my transient data
- List<KnowledgeElement> known = getKnowledgeElementsOf(kelm.getType()); // Initializes this.known, if not yet done
- known.add(kelm);
- if (kelm.getType().equals("usecase")) {
- ucase = kelm;
- } else
- if (knowl != null) { // If null, knowl will be initialized when needed
- knowl.add(kelm);
- }
-// Update of the index of Knowledge Elements
- Database.getIndex().add(kelm);
- updateMe();
- return kelm;
- }
- catch (RuntimeException e) {
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException error) {
- Study.logger.debug("Error rolling back transaction", error);
- }
-// Throw again the first exception
- throw e;
- }
- return null;
- }
- catch (IOException error) {
- logger.error("Unable to index the knowedge element '" + kelm.getIndex() + "', reason:", error);
- return null;
- }
- }
-
- public void checkin () {
-// ----------------------
- cuser = null;
- lasdate = Calendar.getInstance().getTime();
- Database.getSession().update(this);
- }
-
- public boolean checkout (User user) {
-// -----------------------------------
- if (!owner.isStaffedBy(user)) return false;
-
- cuser = user;
- lasdate = Calendar.getInstance().getTime();
- Database.getSession().update(this);
- return true;
- }
-
- public List<KnowledgeElement> getAllKnowledgeElements () {
-// --------------------------------------------------------
- if (knowl == null) {
- knowl = new Vector<KnowledgeElement>(kelms.size());
- for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext(); ) {
- KnowledgeElement kelm = i.next();
- if (kelm.getType().equals("usecase")) ucase = kelm;
- else knowl.add(kelm);
- }
- }
- return Collections.unmodifiableList(knowl);
- }
-
- public KnowledgeElement getKnowledgeElement (int index) {
-// -------------------------------------------------------
- for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext();) {
- KnowledgeElement mykelm = i.next();
- if (mykelm.getIndex() == index) return mykelm;
- }
- return null;
- }
-
- public List<KnowledgeElement> getKnowledgeElementsOf (KnowledgeElementType type) {
-// --------------------------------------------------------------------------------
- if (kelms.isEmpty()) return new Vector<KnowledgeElement>(); // Smarter than returning null
- if (known == null) known = new HashMap<Integer, List<KnowledgeElement>>();
-
- int numtype = type.getIndex();
- List<KnowledgeElement> listype = known.get(numtype);
- if (listype == null) {
- listype = new Vector<KnowledgeElement>();
- for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext();) {
- KnowledgeElement kelm = i.next();
- if (kelm.getType().getIndex() == numtype) listype.add(kelm);
- }
- known.put(numtype, listype);
- }
- return listype; // No protection against this object corruption as it would not corrupt the database
- }
-
- public Study getOwnerStudy () {
-// -----------------------------
- return owner;
- }
-/**
- * Returns the local reference of this scenario. This reference is unique in the scope of the owner study.
- */
- public String getReference () {
-// -----------------------------
- return String.valueOf(sid);
- }
-
- public User getUser () {
-// ----------------------
- return cuser; // Null if the scenario has not been checked-out
- }
-
- public boolean removeKnowledgeElement (KnowledgeElement kelm) {
-// -------------------------------------------------------------
- KnowledgeElement torem = getKnowledgeElement(kelm.getIndex());
- if (torem == null) return false;
- boolean done = kelms.remove(torem);
- if (done) {
-// Update of my transient data
- List<KnowledgeElement> kelms = known.get(kelm.getType().getIndex());
- kelms.remove(torem);
- if (knowl != null) knowl.remove(torem);
- Database.getSession().update(this);
-//TODO: If the owner study is not private, remove the knowledge from the Lucene index
- return true;
- } else {
- return false;
- }
- }
-
- public boolean isCheckedout () {
-// ------------------------------
- return (cuser != null);
- }
-
- public boolean isEmpty () {
-// -------------------------
- Step[] mystep = this.getSteps();
- for (int i=0; i<mystep.length; i++) if (mystep[i].isStarted()) return false;
- return true;
- }
-
- public boolean isFinished () {
-// ----------------------------
- Step[] mystep = this.getSteps();
- boolean notempty = false; // If this is empty, this is not finished
- for (int i=0; i<mystep.length; i++) {
- if (!mystep[i].isStarted()) continue;
- if (!mystep[i].isFinished()) return false;
- notempty = true;
- }
- return notempty;
- }
-
-// ==============================================================================================================================
-// Protected member function
-// ==============================================================================================================================
-
- protected void updateMyIndex (Index lucin) throws IOException {
-// ------------------------------------------
- if (ucase == null) for (Iterator<KnowledgeElement> i=kelms.iterator(); i.hasNext(); ) {
- KnowledgeElement kelm = i.next();
- if (!kelm.getType().equals("usecase")) continue;
- ucase = kelm;
- break;
- }
- lucin.update(ucase);
- }
-
-// ==============================================================================================================================
-// Private services
-// ==============================================================================================================================
-
- private void copyContentsUpTo (Step lastep) {
-// -------------------------------------------
- Scenario base = (Scenario)lastep.getOwner();
- Step[] from = base.getSteps();
- Step[] to = this.getSteps();
- for (int i=0; i<from.length; i++) {
- Step step = from[i];
- if (step.getNumber() > lastep.getNumber()) break;
-
- List<Publication> docs = step.getAllDocuments();
- for (Iterator<Publication> j=docs.iterator(); j.hasNext(); ) {
- Publication doc = j.next().copy(this); // Creation of a new reference to the document
-// Database.getSession().save(doc); Publications MUST be saved later through cascading when saving the scenario
- to[i].add(doc);
- }
- List<SimulationContext> ctex = step.getAllSimulationContexts();
- for (Iterator<SimulationContext> j=ctex.iterator(); j.hasNext(); ) {
- to[i].addSimulationContext(j.next());
- }
- }
- }
-
- private boolean updateMe () {
-// ---------------------------
- try {
- Database.getSession().update(this); // Update of relational base
- return true;
- }
- catch (Exception error) {
- logger.error("Unable to re-index the knowledge element '" + getIndex() + "', reason:", error);
- return false;
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.SimulationContext" table="contelm">
-
-<!-- Properties inherited Persistent
- -->
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
-
-<!-- SimulationContext properties
- -->
- <!-- SimulationContextType type -->
- <many-to-one name="type" column="type" access="field" not-null="true" />
-
- <!-- int step -->
- <property name="step" column="step" access="field" not-null="true" />
-
- <!-- ProgressState state -->
- <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
-
- <!-- String value -->
- <property name="value" column="value" type="text" access="field" not-null="true" />
-
- <!-- int counter -->
- <property name="counter" column="counter" access="field" not-null="true" />
- </class>
-
-<!-- Class SimulationContextType
- -->
- <class name="org.splat.som.SimulationContextType" table="contype" lazy="false">
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
- <property name="name" column="name" access="field" not-null="true" />
- <property name="state" column="state" type="ProgressState" access="field" not-null="true" />
- <property name="step" column="step" access="field" not-null="true" />
- </class>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.Serializable;
-import java.util.List;
-
-import org.hibernate.Session;
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-
-
-public class SimulationContext extends Persistent implements Serializable {
-
- private SimulationContextType type; // User extendable types
- private int step;
- private ProgressState state;
- private String value;
- private int counter;
-
- private static final long serialVersionUID = 422889133378471949L;
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Fields initialization class
- public static class Properties extends Persistent.Properties {
-// ------------------------------------------------------------
- private SimulationContextType type = null;
- private ProjectSettings.Step step = null;
- private ProgressState state = null;
- private String value = null;
-
-// - Public services
-
- public void clear () {
- super.clear();
- type = null;
- step = null;
- state = null;
- value = null;
- }
- protected ProgressState getProgressState () {
- return state;
- }
- public SimulationContextType getType () {
- return type;
- }
- public String getValue () {
- return value;
- }
-
-// - Setters of SimulationContext properties
-
- public Properties setState (ProgressState state) throws InvalidPropertyException
- {
- if (state != ProgressState.inCHECK && state != ProgressState.APPROVED) {
- throw new InvalidPropertyException("state");
- }
- this.state = state;
- return this;
- }
- protected Properties setStep (ProjectSettings.Step step) throws InvalidPropertyException
- {
- this.step = step;
- return this;
- }
- public Properties setValue (String value) throws InvalidPropertyException
- {
- if (value.length() == 0) throw new InvalidPropertyException("value");
- this.value = value;
- return this;
- }
- public Properties setType (SimulationContextType type)
- {
- this.type = type;
- return this;
- }
-// - Global validity check
-
- public void checkValidity () throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (type == null) throw new MissedPropertyException("type");
- if (step == null) throw new MissedPropertyException("step");
- if (value == null) throw new MissedPropertyException("value");
- if (!type.isAttachedTo(step)) throw new InvalidPropertyException("step");
- }
- }
-// Database fetch constructor
- protected SimulationContext () {
- }
-// Internal constructor
- protected SimulationContext (Properties kprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
- super(kprop); // Throws one of the above exception if not valid
- type = kprop.type;
- step = kprop.step.getNumber();
- value = kprop.value;
- counter = 0;
- state = kprop.state;
- if (state == null) state = ProgressState.inCHECK;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean approve () {
-// -------------------------
- if (state != ProgressState.inCHECK) return false;
- this.state = ProgressState.APPROVED; // The type name is supposed being localized
- Database.getSession().update(this);
- return true;
- }
-
- public boolean equals (SimulationContext given) {
-// -----------------------------------------------
- if (isSaved()) return (this.getIndex() == given.getIndex());
- if (!this.getType().getName().equals(given.getType().getName())) return false;
- if (this.getValue().equals(given.getValue())) return true;
- return false;
- }
-
- public String getValue () {
-// -------------------------
- return value;
- }
-
- public ProgressState getProgressState () {
-// ----------------------------------------
- return state;
- }
-
- public SimulationContextType getType () {
-// ---------------------------------------
- return type;
- }
-
- public boolean isInto (Step container) {
-// --------------------------------------
- return (step == container.getNumber());
- }
-
- public boolean isShared () {
-// --------------------------
- return (counter > 1);
- }
-
-// ==============================================================================================================================
-// Public services
-// ==============================================================================================================================
-
- public static SimulationContextType createType (String name, ProjectSettings.Step step) throws InvalidPropertyException, RuntimeException {
-// ---------------------------------------------------------------------------------------
-//TODO: Check for duplicate definition
- SimulationContextType type = new SimulationContextType(name, step);
- Session session = Database.getSession();
- session.save(type);
-
- return type;
- }
-
- @SuppressWarnings("unchecked")
- public static List<SimulationContextType> selectAllTypes () {
-// -----------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContextType"); // Useless to order by names as the result mixes localized and non localized types
- query = query.append(" order by step asc");
- return Database.getSession().createQuery(query.toString()).list();
- }
-
- @SuppressWarnings("unchecked")
- public static List<SimulationContextType> selectTypesOf (ProjectSettings.Step... step) {
-// --------------------------------------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContextType where step='").append(step[0].getNumber()).append("'");
- for (int i=1; i<step.length; i++) { // Useless to order as the result mixes localized and non localized types
- query = query.append(" or step='").append(step[i].getNumber()).append("'");
- }
- query = query.append(" order by step asc");
- return Database.getSession().createQuery(query.toString()).list();
- }
-
- @SuppressWarnings("unchecked")
- public static List<SimulationContextType> selectTypesWhere (SimulationContextType.Properties sprop) {
-// ---------------------------------------------------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContextType");
- String separator = " where";
- ProjectSettings.Step step = sprop.getStep();
- ProgressState state = sprop.getProgressState();
- String order = " order by step asc";
-
- if (step != null) {
- query = query.append(separator).append(" step='").append(step.getNumber()).append("'");
- separator = " and";
- order = " order by state desc"; // APPROVED (upper case A) is grater than inCHECK (lower case i)
- }
- if (state != null) {
- query = query.append(separator).append(" state='").append(state.toString()).append("'");
-// separator = " and";
- if (step != null) {
- if (state != ProgressState.APPROVED) order = " order by name asc";
- else order = ""; // Approved types are localized
- }
- }
- query = query.append(order);
- return Database.getSession().createQuery(query.toString()).list();
- }
-
- public static SimulationContextType selectType (String name) {
-// ------------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContextType where name='").append(name).append("'");
- return (SimulationContextType)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
- public static SimulationContextType selectType (int index) {
-// ----------------------------------------------------------
- StringBuffer query = new StringBuffer("from SimulationContextType where rid='").append(index).append("'");
- return (SimulationContextType)Database.getSession().createQuery(query.toString()).uniqueResult();
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected void hold () {
-// ----------------------
- counter += 1;
- if (this.isSaved()) Database.getSession().update(this);
- }
-
- protected void release () {
-// -------------------------
- counter -= 1;
- if (this.isSaved()) Database.getSession().update(this);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.io.Serializable;
-
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.Persistent;
-
-
-public class SimulationContextType extends Persistent implements Serializable {
-
-// Persistent fields
- private String name;
- private ProgressState state;
- private int step;
-
-// Required by the serialization
- private static final long serialVersionUID = 4819425038576161242L;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Search properties class
- public static class Properties {
-// ------------------------------
- private ProgressState state = null;
- private ProjectSettings.Step step = null;
-
- protected ProgressState getProgressState () {
- return state;
- }
- protected ProjectSettings.Step getStep () {
- return step;
- }
- public Properties setState (ProgressState state) {
- this.state = state;
- return this;
- }
- public Properties setStep (ProjectSettings.Step step) {
- this.step = step;
- return this;
- }
- }
-// Database fetch constructor
- protected SimulationContextType () {
- }
-// Initialization constructor
- protected SimulationContextType (String name, ProjectSettings.Step step) throws InvalidPropertyException {
-// ------------------------------------------------------------------------
- super();
- this.name = name;
- this.state = ProgressState.inCHECK;
- this.step = step.getNumber();
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean approve () {
-// -------------------------
- if (state != ProgressState.inCHECK) return false;
- this.state = ProgressState.APPROVED; // The type name is supposed being localized
- Database.getSession().update(this);
- return true;
- }
-
- public boolean equals(Object entity) {
-// ------------------------------------
- if (entity == null) return false;
- if (entity instanceof String) {
- return this.name.equals((String)entity); // Names are unique
- } else
- if (entity instanceof SimulationContextType) {
- SimulationContextType object = (SimulationContextType)entity;
- int he = object.getIndex();
- int me = this.getIndex();
- if (me*he != 0) return (he == me);
- else return this.getName().equals(object.getName());
- } else {
- return false;
- }
- }
-
- public ProjectSettings.Step getAttachedStep () {
-// ----------------------------------------------
- return ProjectSettings.getStep(step);
- }
-
- public String getName () {
-// ------------------------
- return name;
- }
-
- public boolean isAttachedTo (ProjectSettings.Step step) {
-// -------------------------------------------------------
- if (this.step == step.getNumber()) return true;
- return false;
- }
-
- public boolean isApproved () {
-// ----------------------------
- return (state == ProgressState.APPROVED);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-
-
-public class StampRelation extends Relation {
-
- private Timestamp refer;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected StampRelation () {
- }
-// Internal constructor
- protected StampRelation (Document from, Timestamp to) {
-// -----------------------------------------------------
- super(from);
- this.refer = to;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Timestamp getTo () {
-// -------------------------
- return refer;
- }
-
- public ValidationStep getStampType () {
-// -------------------------------------
- return refer.getType();
- }
-
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (Timestamp)to;
- }
-}
\ No newline at end of file
import java.util.Iterator;
import org.hibernate.Session;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.ConvertsRelation;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.UsedByRelation;
+import org.splat.dal.bo.som.UsesRelation;
+import org.splat.dal.bo.som.VersionsRelation;
+import org.splat.dal.dao.som.Database;
import org.splat.kernel.InvalidPropertyException;
import org.splat.kernel.MismatchException;
import org.splat.kernel.MissedPropertyException;
import org.splat.kernel.MultiplyDefinedException;
import org.splat.kernel.NotApplicableException;
-import org.splat.kernel.Relation;
-import org.splat.kernel.User;
-import org.splat.som.Database;
+import org.splat.service.technical.IndexServiceImpl;
+import org.splat.service.technical.ProjectSettingsService;
public class Step {
- private ProjectSettings.Step step;
+ private ProjectSettingsService.Step step;
private ProjectElement owner;
private List<SimulationContext> contex;
- private List<Publication> docums;
+ private List<Publication> docums;
private User actor; // Actor involved in operations on published documents and requiring a time-stamp
// ==============================================================================================================================
// Constructor
// ==============================================================================================================================
- protected Step (ProjectSettings.Step step, ProjectElement owner) {
+ public Step (ProjectSettingsService.Step step, ProjectElement owner) {
// ----------------------------------------------------------------
this.step = step;
this.owner = owner;
return new Publication(newdoc, owner);
}
- public SimulationContext addSimulationContext (SimulationContext.Properties dprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, RuntimeException {
-// ----------------------------------------------------------------------------------
- SimulationContext context = new SimulationContext(dprop.setStep(step));
- return addSimulationContext(context);
- }
-
- public SimulationContext addSimulationContext (SimulationContext context) {
-// -------------------------------------------------------------------------
- context.hold(); // Increments the reference count of simulation context
- if (owner.isSaved()) try {
- Session session = Database.getSession();
- Index lucin = Database.getIndex();
-
- if (!context.isSaved()) session.save(context);
- owner.add(context);
- contex.add(context); // The context is also referenced from this (transient) Step
- session.update(owner);
- updateKnowledgeElementsIndex(lucin);
- }
- catch (Exception error) {
- return null;
- }
- else { // Happens when copying a scenario
- owner.add(context);
- contex.add(context); // The context is also referenced from this (transient) Step
-// In case of owner scenario, the Knowledge Element index will be updated later, when saving the scenario
- }
- return context;
- }
-
public User getActor () {
// -----------------------
return actor;
return result;
}
- public ProjectSettings.Step getStep () {
+ public ProjectSettingsService.Step getStep () {
// --------------------------------------
return step;
}
return true;
}
- public boolean removeSimulationContext (SimulationContext context) {
-// ------------------------------------------------------------------
- SimulationContext torem = getSimulationContext(context.getIndex());
- Session session = Database.getSession();
-
- if (torem == null) return false;
- if (!owner.remove(torem)) return false;
-
- contex.remove(torem);
- session.update(owner);
- if (torem.isShared()) {
- torem.release();
- session.update(torem);
- } else {
- session.delete(torem);
- }
- return true;
- }
-
public void setActor (User user) {
// --------------------------------
actor = user;
// Protected member functions
// ==============================================================================================================================
- protected boolean add (Publication newdoc) {
+ public boolean add (Publication newdoc) {
// ------------------------------------------
if (!owner.add(newdoc)) return false; // Updates the study in memory
docums.add(0, newdoc); // Updates this step
return true;
}
- protected boolean remove (Publication oldoc) {
+ public boolean remove (Publication oldoc) {
// --------------------------------------------
if (!owner.remove(oldoc)) return false; // Updates the study in memory
docums.remove(oldoc); // Updates this step
return true;
}
-// ==============================================================================================================================
-// Private services
-// ==============================================================================================================================
+ public List<SimulationContext> getContex() {
+ return contex;
+ }
- private void updateKnowledgeElementsIndex(Index lucin) {
-// ------------------------------------------------------
- Scenario[] scenarii;
- if (owner instanceof Scenario) {
- scenarii = new Scenario[1];
- scenarii[0] = (Scenario)owner;
- } else {
- scenarii = getOwnerStudy().getScenarii();
- }
- try {
- for (int i=0; i<scenarii.length; i++) {
- Scenario scene = scenarii[i];
- List<KnowledgeElement> knelm = scene.getAllKnowledgeElements();
- for (Iterator<KnowledgeElement> j=knelm.iterator(); j.hasNext(); ) {
- KnowledgeElement kelm = j.next();
- lucin.update(kelm);
- }
- scene.updateMyIndex(lucin);
- }
- }
- catch (Exception error) {
-// logger.error("Unable to re-index Knowledge Elements, reason:", error);
- }
- }
}
\ No newline at end of file
*/
//TODO: Review this rights according to the state of the owner study.
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.Study;
public class StepRights {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <typedef name="ProgressState" class="org.splat.kernel.GenericEnumType">
- <param name="enumClassName">org.splat.som.ProgressState</param>
- </typedef>
-
- <typedef name="Visibility" class="org.splat.kernel.GenericEnumType">
- <param name="enumClassName">org.splat.som.Visibility</param>
- </typedef>
-
- <union-subclass name="org.splat.som.Study" extends="org.splat.som.ProjectElement" table="study" lazy="false">
-
- <!-- String sid -->
- <property name="sid" column="sid" access="field" not-null="true" />
-
- <!-- int docount -->
- <property name="docount" column="docount" access="field" not-null="true" />
-
- <!-- ProgressState state -->
- <property name="state" type="ProgressState" column="state" access="field" not-null="true" />
-
- <!-- Visibility visibility -->
- <property name="visibility" type="Visibility" column="area" access="field" not-null="true" />
-
- <!-- List<Scenario> scenarii -->
- <list name="scenarii" lazy="false" cascade="delete-orphan" access="field">
- <key column="owner" not-null="true" />
- <list-index column="scendex"/>
- <one-to-many class="org.splat.som.Scenario" />
- </list>
-
- <!-- String version -->
- <property name="version" column="version" access="field" not-null="true" />
-
- <!-- int history -->
- <property name="history" column="history" access="field" not-null="true" />
-
- </union-subclass>
-
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.LinkedList;
-import java.util.Set;
-import java.util.Vector;
-
-import org.hibernate.Session;
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-import org.splat.kernel.User;
-import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.UserDirectory;
-
-
-public class Study extends ProjectElement {
-
-// Persistent fields
- private String sid; // External unique reference in a format conform to the configuration pattern
- private int docount; // Total number of documents of this study, including versions
- private ProgressState state;
- private Visibility visibility;
- private List<Scenario> scenarii;
- private String version;
- private int history; // Number of studies versioning this one, if any
-
-// Transient fields
- private List<User> contributor; // Shortcut to contributors
- private HashMap<String,ValidationCycle> validactor; // Shortcut to validation cycles
- private Set<User> actor; // Summary of above actors
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Fields initialization class
- public static class Properties extends Persistent.Properties {
-// ------------------------------------------------------------
- private String sid = null; // Search criterion only
- private String title = null;
- private String summary = null;
- private User manager = null;
- private User actor = null; // Search criterion only
- private Visibility visibility = null; // Search criterion only
- private ProgressState state = null; // Search criterion only
- private Date date = null;
- private List<SimulationContext> context = new Vector<SimulationContext>(); // Search criterion only
-
-// - Public services
-
- public void clear () {
- super.clear();
- sid = null;
- title = null;
- summary = null;
- manager = null;
- actor = null;
- visibility = null;
- state = null;
- date = null;
- context = new Vector<SimulationContext>(); // as clear() may generate side effects
- }
- public Properties copy () {
- Properties copy = new Properties();
- copy.sid = this.sid;
- copy.title = this.title;
- copy.summary = this.summary;
- copy.manager = this.manager;
- copy.actor = this.actor;
- copy.visibility = this.visibility;
- copy.state = this.state;
- copy.date = this.date;
- copy.context = this.context;
- return copy;
- }
-// - Protected services
-
- protected User getActor () {
- return actor;
- }
- protected User getManager () {
- return manager;
- }
- protected ProgressState getProgressState () {
- return state;
- }
- protected String getReference () {
- return sid;
- }
- protected List<SimulationContext> getSimulationContexts () {
- return context;
- }
- protected String getTitle () {
- return title;
- }
- protected Visibility getVisibility () {
- return visibility;
- }
-// - Property setters
-
-// For building a search query
- public Properties setActor (User actor)
- {
- this.actor = actor;
- return this;
- }
- public Properties setDate (Date date)
- {
- this.date = date;
- return this;
- }
- public Properties setDescription (String summary)
- {
- if (summary.length() > 0) this.summary = summary;
- return this;
- }
- public Properties setManager (User user)
- {
- this.manager = user;
- return this;
- }
-// For building a search query
- public Properties setReference (String sid) throws InvalidPropertyException
- {
- if (sid.length() == 0) throw new InvalidPropertyException("reference");
- this.sid = sid;
- return this;
- }
-// For building a search query
- public Properties setSimulationContexts (List<SimulationContext> context) {
- this.context = context;
- return this;
- }
-// For building a search query
- public Properties setState (ProgressState state)
- {
- this.state = state;
- return this;
- }
- public Properties setTitle (String title) throws InvalidPropertyException
- {
- if (title.length() == 0) throw new InvalidPropertyException("title");
- this.title = title;
- return this;
- }
-// For building a search query
- public Properties setVisibility (Visibility area)
- {
- this.visibility = area;
- return this;
- }
-// - Global validity check
-
- public void checkValidity() throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException
- {
- if (title == null) throw new MissedPropertyException("title");
- if (manager == null) throw new MissedPropertyException("manager");
- }
- }
-// Database fetch constructor
- protected Study () {
-// ------------------
- contributor = null;
- validactor = null;
- actor = null;
- }
-// Internal constructor
- protected Study (Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException {
-// ----------------------------------
- super(sprop); // Throws one of the above exception if not valid
- sid = ProjectSettings.getReferencePattern(); // Reset after save
- title = sprop.title; // Inherited attribute
- manager = sprop.manager;
- docount = 0;
- history = 0;
- scenarii = new LinkedList<Scenario>();
- visibility = Visibility.PRIVATE;
- state = ProgressState.inWORK;
-
- credate = sprop.date; // Inherited attribute
- if (credate == null) {
- Calendar current = Calendar.getInstance();
- credate = current.getTime(); // Today
- }
- lasdate = credate; // Inherited attribute
- version = new Revision().incrementAs(state).toString();
-
- if (sprop.summary != null) this.setAttribute( new DescriptionAttribute(this, sprop.summary) );
-
- contributor = null;
- validactor = null;
- actor = null;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public boolean addContributor (User user) {
-// -----------------------------------------
- if (contributor == null) this.setShortCuts(); // Initializes contributor
- for (Iterator<User> i=contributor.iterator(); i.hasNext(); ) {
- User present = i.next();
- if ( present.equals(user) ) return false;
- }
- boolean absent = actor.add(user); // User may already be a reviewer or an approver
-
- this.addRelation( new ContributorRelation(this, user) );
- if (absent) updateMe(); // Else, useless to re-index the study
- contributor.add(user);
- return true;
- }
-
- public SimulationContext addProjectContext (SimulationContext.Properties cprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, RuntimeException {
-// -------------------------------------------------------------------------------
- SimulationContext added = this.getFirstStep().addSimulationContext(cprop);
- updateMe();
- return added;
- }
-
- public SimulationContext addProjectContext (SimulationContext context) {
-// ----------------------------------------------------------------------
- SimulationContext added = this.getFirstStep().addSimulationContext(context);
- updateMe();
- return added;
- }
-
- public Scenario addScenario (Scenario.Properties sprop) throws MissedPropertyException, InvalidPropertyException, MultiplyDefinedException, RuntimeException {
-// -------------------------------------------------------
- if (sprop.getManager() == null) sprop.setManager(this.manager);
-
- Scenario scenario = new Scenario(sprop.setOwnerStudy(this));
- Scenario previous = sprop.getInsertAfter();
- Session session = Database.getSession();
-
- if (previous == null) {
- scenarii.add(scenario);
- } else {
- scenarii.add(scenarii.indexOf(previous)+1, scenario);
- }
- session.update(this); // No need to update the Lucene index
- session.save(scenario); // Must be done after updating this study because of the back reference to the study
- if (sprop.getBaseStep() != null) {
-// No need to update the Knowledge Element index as Knowledge Elements are not copied
- scenario.refresh(); // Because saving the scenario changes the hashcode of copied Publications
- }
- KnowledgeElementType ucase = KnowledgeElement.selectType("usecase");
- KnowledgeElement.Properties kprop = new KnowledgeElement.Properties();
- User admin = UserDirectory.selectUser(1); // First user created when creating the database
- kprop.setType(ucase)
- .setTitle(this.getTitle())
- .setValue(scenario.getTitle())
- .setAuthor(admin); // Internal Knowledge Element required by the validation process of knowledges
- scenario.addKnowledgeElement(kprop);
- return scenario;
- }
-
-/**
- * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
- *
- * @return the actors of this study
- * @see #hasActor(User)
- */
- public Set<User> getActors () {
-// -----------------------------
- if (actor == null) setShortCuts();
- return Collections.unmodifiableSet(actor);
- }
-
- public List<User> getContributors () {
-// ------------------------------------
- if (contributor == null) setShortCuts();
- return Collections.unmodifiableList(contributor); // May be empty
- }
-
- public ProgressState getProgressState () {
-// ----------------------------------------
- return state;
- }
-
-/**
- * Returns the global unique reference of this study.
- * The study reference is common to all versions of the study (versioning a study does not change its reference).
- * The form of this study reference is defined in the configuration of the application server - see the SOM XML customization
- * file.
- */
- public String getReference () {
-// -----------------------------
- return sid;
- }
-
- public Scenario[] getScenarii () {
-// --------------------------------
- return scenarii.toArray(new Scenario[scenarii.size()]);
- }
-
-/**
- * Returns the validation cycle of the given document type.
- *
- * @param doc the document type being subject of validation
- * @return the validation cycle of the document, or null if not defined.
- */
- public ValidationCycle getValidationCycleOf (DocumentType type) {
-// ---------------------------------------------------------------
- if (validactor == null) setShortCuts();
- ValidationCycle result = validactor.get(type.getName());
- if (result == null) {
- if (type.isStepResult()) result = validactor.get("default"); // "default" validation cycle defined in the configuration, if exist
- if (result == null) result = validactor.get("built-in");
- }
- return result;
- }
-
- public String getVersion () {
-// ---------------------------
- return version;
- }
-
- public Visibility getVisibility () {
-// ----------------------------------
- return visibility;
- }
-
-/**
- * Checks if the given user is actor of this study.
- * Actors include contributors, reviewers and approvers.
- *
- * @return true if the given user is actor of this study.
- * @see #getActors()
- */
- public boolean hasActor (User user) {
-// -----------------------------------
- if (user == null) return false;
- for (Iterator<User> i=this.getActors().iterator(); i.hasNext(); ) {
- User involved = i.next();
- if (involved.equals(user)) return true;
- }
- return false;
- }
-
-/**
- * Checks whether this study is in the Public or the Reference area of the repository.
- *
- * @return true if the study is public.
- * @see #moveToPublic()
- * @see #moveToReference()
- */
- public boolean isPublic () {
-// --------------------------
- return (visibility != Visibility.PRIVATE);
- }
-/**
- * Checks if the given user participates to this study.
- * The Study staff includes the author and contributors.
- *
- * @return true if the given user is actor of this study.
- * @see #getContributors()
- */
- public boolean isStaffedBy (User user) {
-// --------------------------------------
- if (user == null) return false;
- if (manager.equals(user)) return true;
- for (Iterator<User> i=getContributors().iterator(); i.hasNext();) {
- if (i.next().equals(user)) return true;
- }
- return false;
- }
-
- public boolean isVersioned () {
-// -----------------------------
- return (history > 0);
- }
-
-/**
- * Moves this study from the Private to the Public area of the repository.
- *
- * @return true if the move succeeded.
- * @see #isPublic()
- */
- public boolean moveToPublic () {
-// ------------------------------
- if (visibility != Visibility.PRIVATE) return false;
-
- this.visibility = Visibility.PUBLIC;
- if ( updateMe() ) {
- return updateKnowledgeElementsIndex(); // If fails, the database roll-back is under responsibility of the caller
- }
- return false;
- }
-
-/**
- * Moves this study from the Public to the Reference area of the repository.
- * For being moved to the Reference area, the study must previously be approved.
- *
- * @return true if the move succeeded.
- * @see #moveToPublic()
- * @see #isPublic()
- * @see Publication#approve(Date)
- */
- public boolean moveToReference () {
-// ---------------------------------
- if (state != ProgressState.APPROVED) return false;
- if (visibility != Visibility.PUBLIC) return false;
-
- this.visibility = Visibility.REFERENCE;
- if ( updateMe() ) {
- return updateKnowledgeElementsIndex(); // If fails, the database roll-back is under responsibility of the caller
- }
- return false;
- }
-
- public boolean publishes (Document doc) {
-// ---------------------------------------
- if (!super.publishes(doc)) {
- Scenario[] scene = this.getScenarii();
- for (int i=0; i<scene.length; i++) {
- if (scene[i].publishes(doc)) return true;
- }
- }
- return false;
- }
-
- public boolean removeContributor (User... users) {
-// ------------------------------------------------
- if (contributor == null) this.setShortCuts(); // Initializes contributor
- Boolean done = false;
- for (int i=0; i<users.length; i++) {
- User user = users[i];
- for (Iterator<User> j=contributor.iterator(); j.hasNext(); ) {
- User present = j.next();
- if (!present.equals(user)) continue;
-
- this.removeRelation(ContributorRelation.class, user);
- j.remove(); // Updates the contributor shortcut
- done = true;
- break;
- }
- }
- if (done) updateMe();
- return done;
- }
-
- public boolean removeProjectContext (SimulationContext context) {
-// ---------------------------------------------------------------
- boolean done = this.getFirstStep().removeSimulationContext(context);
- updateMe();
- return done;
- }
-
- public void setValidationCycle (DocumentType type, ValidationCycle.Properties vprop) {
-// ------------------------------------------------------------------------------------
- if (validactor == null) setShortCuts(); // Initializes validactor and actor
-
- String cname = type.getName();
- ValidationCycle cycle = validactor.get(cname);
-
- if (cycle != null && cycle.isAssigned()) {
- cycle.resetActors(vprop);
- } else
- try {
- cycle = new ValidationCycle(this, vprop.setDocumentType(type));
-
- ValidationCycleRelation link = cycle.getContext();
- this.addRelation(link);
- validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
- }
- catch (Exception error) {
- logger.error("Unable to re-index Knowledge Elements, reason:", error);
- return;
- }
- resetActorsShortCut();
- updateMe(); // Re-index the study, just in case
- }
-
- public boolean shares (Document doc) {
-// ------------------------------------
- Scenario[] scene = this.getScenarii(); // If shared from within the study, the document is shared by the scenarios
- int counter = 0;
-
- for (int i=0; i<scene.length; i++) {
- if (!scene[i].publishes(doc)) continue;
- if (counter == 1) return true;
- counter += 1;
- }
- return false;
- }
-
- public boolean update (Properties sprop) throws InvalidPropertyException {
-// ----------------------------------------
- if (sprop.title != null) this.title = sprop.title;
- if (sprop.summary != null) this.setAttribute( new DescriptionAttribute(this, sprop.summary) );
-//TODO: To be completed
- return updateMe();
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected boolean buildReference () {
-// -----------------------------------
- String pattern = getReference(); // The study being supposed just created, its reference is the reference pattern
- IDBuilder tool = Database.selectIDBuilder(credate);
- if (tool == null) {
- tool = new IDBuilder(credate);
- Database.getSession().save(tool);
- }
- this.sid = tool.buildReference(pattern, this);
- return true;
- }
-
-/**
- * Demotes this study from In-Check to In-Draft then In-Work states.
- * This function is called internally when demoting the final result document of the study.
- *
- * @return true if the demotion succeeded.
- */
- protected boolean demote () {
-// ---------------------------
- if (state == ProgressState.inCHECK) state = ProgressState.inDRAFT;
- else if (state == ProgressState.inDRAFT) state = ProgressState.inWORK;
- else return false;
- return updateMe();
- }
-
- protected int generateLocalIndex () {
-// -----------------------------------
- docount = docount + 1;
- Database.getSession().update(this);
- return docount;
- }
-
- protected int getLastLocalIndex () {
-// ----------------------------------
- return docount;
- }
-
- protected void loadWorkflow () {
-// ------------------------------
- setShortCuts();
- }
-/**
- * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states.
- * This function is called internally when promoting the final result document of the study.
- *
- * @return true if the demotion succeeded.
- */
- protected boolean promote () {
-// ----------------------------
- if (state == ProgressState.inWORK) {
- state = ProgressState.inDRAFT;
- } else
- if (state == ProgressState.inDRAFT) {
- this.state = ProgressState.inCHECK;
- Revision myvers = new Revision(version);
- if (myvers.isMinor()) {
- version = myvers.incrementAs(state).toString();
- }
- } else
- if (state == ProgressState.inCHECK) {
- state = ProgressState.APPROVED;
- }
- else return false;
-
- return updateMe();
- }
-
-// ==============================================================================================================================
-// Private member functions
-// ==============================================================================================================================
-
- private void resetActorsShortCut () {
-// -----------------------------------
- actor.clear();
-// Get all actors involved in validation cycles
- for (Iterator<ValidationCycle> i=validactor.values().iterator(); i.hasNext(); ) {
- ValidationCycle cycle = i.next();
- User[] user = cycle.getAllActors();
- for (int j=0; j<user.length; j++) actor.add(user[j]);
- }
-// Get all other actors
- for (Iterator<Relation> i=this.getAllRelations().iterator(); i.hasNext(); ) {
- Relation link = i.next();
- Class<?> kindof = link.getClass().getSuperclass();
- if (!kindof.equals(ActorRelation.class)) continue;
- actor.add( ((ActorRelation)link).getTo() );
- }
- }
-
- private void setShortCuts () {
-// ----------------------------
- contributor = new Vector<User>();
- validactor = new HashMap<String,ValidationCycle>();
- actor = new HashSet<User>();
-
-// Get the contributors
- for (Iterator<Relation> i=getRelations(ContributorRelation.class).iterator(); i.hasNext(); ) {
- ContributorRelation link = (ContributorRelation)i.next();
- contributor.add(link.getTo());
- }
-// Get the validation cycles specific to this study
- for (Iterator<Relation> i=getRelations(ValidationCycleRelation.class).iterator(); i.hasNext(); ) {
- ValidationCycleRelation link = (ValidationCycleRelation)i.next();
- validactor.put(link.getDocumentType().getName(), link.getTo()); // The associated document type is necessarily not null in this context
- }
-// Get the validation cycles coming from the configured workflow and not overridden in this study
- for (Iterator<ProjectSettings.ValidationCycle> i=ProjectSettings.getAllValidationCycles().iterator(); i.hasNext(); ) {
- ProjectSettings.ValidationCycle cycle = i.next();
- String type = cycle.getName();
- if (!validactor.containsKey(type)) validactor.put(type, new ValidationCycle(this, cycle));
- }
-// Get all corresponding actors
- for (Iterator<ValidationCycle> i=validactor.values().iterator(); i.hasNext(); ) {
- ValidationCycle cycle = i.next();
- User[] user = cycle.getAllActors();
- for (int j=0; j<user.length; j++) actor.add(user[j]);
- }
-// Get all other actors
- for (Iterator<Relation> i=this.getAllRelations().iterator(); i.hasNext(); ) {
- Relation link = i.next();
- Class<?> kindof = link.getClass().getSuperclass();
- if (!kindof.equals(ActorRelation.class)) continue;
- actor.add( ((ActorRelation)link).getTo() );
- }
- }
-
- private boolean updateKnowledgeElementsIndex() {
-// ----------------------------------------------
- try {
- Index lucin = Database.getIndex();
-
- for (Iterator<Scenario> i=scenarii.iterator(); i.hasNext(); ) {
- Scenario scene = i.next();
- for (Iterator<KnowledgeElement> j=scene.getAllKnowledgeElements().iterator(); j.hasNext(); ) {
- KnowledgeElement kelm = j.next();
- lucin.update(kelm);
- }
- }
- return true;
- }
- catch (Exception error) {
- logger.error("Unable to re-index Knowledge Elements, reason:", error);
- return false;
- }
- }
-
- private boolean updateMe () {
-// ---------------------------
- try {
- Database.getSession().update(this); // Update of relational base
- Database.getIndex().update(this); // Update of Lucene index
- return true;
- }
- catch (Exception error) {
- logger.error("Unable to re-index the study '" + getIndex() + "', reason:", error);
- return false;
- }
- }
-}
\ No newline at end of file
* @copyright OPEN CASCADE 2012
*/
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Study;
public class StudyRights {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <typedef name="StampType" class="org.splat.kernel.GenericEnumType">
- <param name="enumClassName">org.splat.som.ValidationStep</param>
- </typedef>
-
- <class name="org.splat.som.Timestamp" table="stamp" lazy="false">
-
-<!-- Properties inherited from Any
- -->
- <id name="rid" type="int" column="rid" unsaved-value="0" access="field">
- <generator class="org.splat.kernel.IDGenerator"/>
- </id>
- <set name="attributes" inverse="true" lazy="false" cascade="all-delete-orphan" access="field">
- <key column="owner" />
- <one-to-many class="org.splat.kernel.Attribute" />
- </set>
-
-<!-- Timestamp properties
- -->
- <!-- StampRelation context -->
- <one-to-one name="context" property-ref="refer" access="field" />
-
- <!-- ValidationCycle.Step mytype -->
- <property type="StampType" name="mytype" column="type" access="field" not-null="true" />
-
- <!-- User author -->
- <many-to-one name="author" column="author" access="field" not-null="true" />
-
- <!-- Date sdate, including the time section -->
- <property type="timestamp" name="sdate" column="date" access="field" not-null="true" />
-
- </class>
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.Comparator;
-import java.util.Date;
-
-import org.splat.kernel.Any;
-import org.splat.kernel.Attribute;
-import org.splat.kernel.User;
-
-
-public class Timestamp extends Any {
-
- private StampRelation context;
- private ValidationStep mytype;
- private User author;
- private Date sdate;
-
- public static class ComparatorByDate implements Comparator<Timestamp> {
-// ---------------------------------------------------------------------
- public int compare(Timestamp t1, Timestamp t2)
- {
- return t1.getDate().compareTo(t2.getDate());
- }
- }
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected Timestamp () {
- }
-// Internal constructors
- protected Timestamp (ValidationStep type, Document from, User to, Date sdate) {
-// -----------------------------------------------------------------------------
- super((Attribute)null); // For building the collection of attributes
- this.mytype = type;
- this.author = to;
- this.sdate = sdate;
- this.context = new StampRelation(from, this);
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public User getAuthor () {
-// ------------------------
- return author;
- }
-
- public String getComment () {
-// ---------------------------
- CommentAttribute field = (CommentAttribute)this.getAttribute(CommentAttribute.class);
- String result = null;
- if (field != null) result = field.getValue();
- return result;
- }
-
- public Date getDate () {
-// ----------------------
- return sdate;
- }
-
- public ValidationStep getType () {
-// --------------------------------
- return mytype;
- }
-
- public void setComment (String comment) {
-// ---------------------------------------
- if (comment != null) this.setAttribute( new CommentAttribute(this, comment) );
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected StampRelation getContext () {
-// -------------------------------------
- return context;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-
-
-public class UsedByRelation extends Relation {
-
- private Document refer;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected UsedByRelation () {
- }
-// Initialization constructors
- protected UsedByRelation (Document from, Document to) {
-// -----------------------------------------------------
- super(from);
- this.refer = to;
- this.reverse = new UsesRelation(this, to, from);
- }
-// Internal constructor
- protected UsedByRelation (Relation back, Document from, Document to) {
-// --------------------------------------------------------------------
- super(from);
- this.refer = to;
- this.reverse = back;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Class<? extends Relation> getReverseClass () {
-// ---------------------------------------------------
- return UsesRelation.class;
- }
- public Document getTo () {
-// -------------------------
- return refer;
- }
- public boolean isBidirectional () {
-// ---------------------------------
- return true;
- }
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (Document)to;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-
-
-public class UsesRelation extends Relation {
-
- private Document refer;
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected UsesRelation () {
- }
-// Initialization constructors
- protected UsesRelation (Document from, Document to) {
-// ---------------------------------------------------
- super(from);
- this.refer = to;
- this.reverse = new UsedByRelation(this, to, from);
- }
-// Internal constructor
- protected UsesRelation (Relation back, Document from, Document to) {
-// ------------------------------------------------------------------
- super(from);
- this.refer = to;
- this.reverse = back;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public Class<? extends Relation> getReverseClass () {
-// ---------------------------------------------------
- return UsedByRelation.class;
- }
-
- public Document getTo () {
-// -------------------------
- return refer;
- }
- public boolean isBidirectional () {
-// ---------------------------------
- return true;
- }
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (Document)to;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
-<!--
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
-
-<hibernate-mapping>
-
- <class name="org.splat.som.ValidationCycle" table="cycle" lazy="false">
-
-<!-- Properties inherited Persistent
- -->
- <id name="rid" column="rid" access="field">
- <generator class="increment"/>
- </id>
-
-<!-- ValidationCycle properties
- -->
- <!-- ValidationCycleRelation context -->
- <one-to-one name="context" property-ref="refer" access="field" />
-
- <!-- DocumentType mytype -->
- <many-to-one name="mytype" column="type" access="field" not-null="true" />
-
- <!-- User publisher -->
- <many-to-one name="publisher" column="publisher" access="field" />
-
- <!-- User reviewer -->
- <many-to-one name="reviewer" column="reviewer" access="field" />
-
- <!-- User approver -->
- <many-to-one name="approver" column="approver" access="field" />
-
- <!-- User signatory -->
- <many-to-one name="signatory" column="signatory" access="field" />
-
- </class>
-</hibernate-mapping>
\ No newline at end of file
+++ /dev/null
-package org.splat.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
- * involved in such validations. Once past, each validation step is written down by a time-stamp attached to the validated
- * document.<br/>
- * <br/>
- * The possible validation steps are Promotion, Review, Approval and Acceptance (or Refusal), all being optional,
- * except Promotion.<br/>
- * When enabled, Review and Approval involve one given user while Promotion and Acceptance have default actors defined by
- * the application. The default actors are:
- * <ul>
- * <li>Promotion by either the author of the document or the responsible of study</li>
- * <li>Acceptance by the customer, possibly represented by an internal user</li>
- * </ul>
- * Explicit Promotion and Acceptance actors can be defined, for example to force some documents to be published by the
- * responsible of study only.<br/>
- * <br/>
- * Default validation cycles are defined in the configuration workflow, the responsible of studies overriding them when necessary.
- * They are attached to studies at a given document type.<br/>
- *
- * @see Study#addValidationCycle(DocumentType,Properties)
- * @see Study#getValidationCycleOf(DocumentType)
- * @see Timestamp
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import java.util.List;
-import java.util.Vector;
-
-import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.Persistent;
-import org.splat.kernel.User;
-import org.splat.kernel.UserDirectory;
-
-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
-
- public void clear () {
- super.clear();
- doctype = null;
- publisher = null;
- reviewer = null;
- approver = null;
- signatory = null;
- }
-// - Protected services
-
- protected Properties setDocumentType (DocumentType type)
- {
- doctype = type;
- return this;
- }
-// - Properties setter
-
- public Properties setActor (ValidationStep step, 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");
- }
- }
-// Database fetch constructor
- protected ValidationCycle () {
- }
-// Internal constructors
- protected ValidationCycle (Study from, ProjectSettings.ValidationCycle cycle) {
-// -----------------------------------------------------------------------------
- Actor[] actype = cycle.getActorTypes();
- User.Properties uprop = new User.Properties();
-
- mytype = Document.selectType(cycle.getName()); // Null in case of default validation cycle
-// context = new ValidationCycleRelation(from, this);
- context = null; // Validation cycle defined in the workflow
- for (int i=0; i<actype.length; i++) {
- User actor = null;
- if (actype[i] != null)
- try {
- if (actype[i] == Actor.manager) {
- actor = from.getAuthor();
- } else
- if (actype[i] == Actor.Nx1) {
- List<User> manager = UserDirectory.selectUsersWhere(uprop.setOrganizationName("Nx1"));
- if (manager.size() == 1) actor = manager.get(0);
- } else
- if (actype[i] == Actor.Nx2) {
- List<User> manager = UserDirectory.selectUsersWhere(uprop.setOrganizationName("Nx2"));
- if (manager.size() == 1) actor = manager.get(0);
- } else { /* Actor.customer */
- actor = from.getAuthor();
-//TODO: Get the customer of the study, if exists
- }
- } catch (Exception e) { // Should not happen
- actor = null;
- }
- if (i == 0) reviewer = actor;
- else if (i == 1) approver = actor;
- else if (i == 2) signatory = actor;
- }
- }
- protected ValidationCycle (Study from, 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);
- }
-
-// ==============================================================================================================================
-// 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 (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);
- 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 (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 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);
- if (signatory != null) result.add(signatory);
- 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
- }
-
-/**
- * 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);
- }
-
-/**
- * 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()
- * @see ProjectSettings#getNewValidationCycle()
- */
- public boolean isDefault () {
-// ---------------------------
- return (mytype == null);
- }
-
-// ==============================================================================================================================
-// Protected services
-// ==============================================================================================================================
-
- protected ValidationCycleRelation getContext () {
-// -----------------------------------------------
- return context;
- }
-
- protected void remove (ValidationStep step) {
-// ------------------------------------------
- if (step == ValidationStep.REVIEW) reviewer = null;
- else if (step == ValidationStep.APPROVAL) approver = null;
- else if (step == ValidationStep.ACCEPTANCE || step == ValidationStep.REFUSAL) signatory = null;
- if (this.isSaved()) Database.getSession().update(this);
- }
-
- protected void resetActors (Properties vprop) {
-// ---------------------------------------------
- publisher = vprop.publisher; // May be null
- reviewer = vprop.reviewer; // May be null
- approver = vprop.approver; // May be null
- signatory = vprop.signatory; // May be null
- if (this.isSaved()) Database.getSession().update(this);
- }
-
- protected void setActor (ValidationStep step, 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;
- if (this.isSaved()) Database.getSession().update(this);
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-
-
-public class ValidationCycleRelation extends Relation {
-
- private ValidationCycle refer;
-
-// ==============================================================================================================================
-// Construction
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected ValidationCycleRelation () {
- }
-// Internal constructor
- protected ValidationCycleRelation (Study from, ValidationCycle to) {
-// ------------------------------------------------------------------
- super(from);
- this.refer = to;
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
-/**
- * Returns the document type to which the validation cycle referenced by this relation applies. If the referenced validation cycle
- * is a default one, the associated document type is not defined.
- *
- * @return the document type involved by the referenced validation cycle, or null if this latter is a default one.
- */
- public DocumentType getDocumentType () {
-// --------------------------------------
- return refer.getDocumentType();
- }
-
- public ValidationCycle getTo () {
-// -------------------------------
- return refer;
- }
-
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (ValidationCycle)to;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-public enum ValidationStep {
- PROMOTION, REVIEW, APPROVAL, ACCEPTANCE, // Validation steps subject of time stamp
- DISTRIBUTION, REFUSAL // Additional Time stamps
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-import org.splat.kernel.Persistent;
-import org.splat.kernel.Relation;
-
-
-public class VersionsRelation extends Relation {
-
-// Persistent field
- private Document refer;
-
-// Transient fields
- private boolean got; // For optimizing getDescription()
- private String description; // Null if this is not described
-
-// ==============================================================================================================================
-// Constructors
-// ==============================================================================================================================
-
-// Database fetch constructor
- protected VersionsRelation () {
-// -----------------------------
- got = false;
- description = null;
- }
-// Initialization constructors
- protected VersionsRelation (Document from, Document to) {
-// -------------------------------------------------------
- super(from);
- this.refer = to;
- this.got = true;
- this.description = null; // Conversion not described
- }
- protected VersionsRelation (Document from, Document to, String description) {
-// ---------------------------------------------------------------------------
- super(from);
- this.refer = to;
- this.got = true;
- this.description = description; // May be null
- if (description != null) this.setAttribute( new DescriptionAttribute(this, description) );
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public String getDescription () {
-// -------------------------------
- if (!got) {
- DescriptionAttribute field = (DescriptionAttribute)this.getAttribute(DescriptionAttribute.class);
- if (field != null) description = field.getValue();
- got = true; // Don't need to be modified later as set and remove attribute functions are private to this class
- }
- return description; // May be null
- }
-
- public Document getTo () {
-// -------------------------
- return refer;
- }
- protected void setTo (Persistent to) {
-// ------------------------------------
- refer = (Document)to;
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.splat.som;
-/**
- *
- * @author Daniel Brunier-Coulin
- * @copyright OPEN CASCADE 2012
- */
-
-public enum Visibility {
- PRIVATE, // Qualifies studies stored into the private area
- PUBLIC, // Qualifies studies stored into the public area
- REFERENCE // Qualifies studies stored into the reference area
-}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xsi:schemaLocation="
+http://www.springframework.org/schema/beans
+http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+http://www.springframework.org/schema/aop
+http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+http://www.springframework.org/schema/tx
+http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+ <bean id="projectElementService"
+ class="org.splat.service.ProjectElementServiceImpl">
+ <property name="projectSettings" ref="projectSettings" />
+ </bean>
+
+ <bean id="documentTypeService"
+ class="org.splat.service.DocumentTypeServiceImpl">
+ <property name="projectSettingsService"
+ ref="projectSettings" />
+ </bean>
+
+ <bean id="knowledgeElementService"
+ class="org.splat.service.KnowledgeElementServiceImpl">
+ <property name="indexService" ref="indexService" />
+ <property name="knowledgeElementDAO" ref="knowledgeElementDAO" />
+ </bean>
+
+ <bean id="publicationService"
+ class="org.splat.service.PublicationServiceImpl">
+ <property name="documentTypeService" ref="documentTypeService" />
+ <property name="projectElementService"
+ ref="projectElementService" />
+ <property name="stepService" ref="stepService" />
+ <property name="studyService" ref="studyService" />
+ </bean>
+
+ <bean id="scenarioService"
+ class="org.splat.service.ScenarioServiceImpl">
+ <property name="indexService" ref="indexService" />
+ <property name="projectElementService"
+ ref="projectElementService" />
+ <property name="publicationService" ref="publicationService" />
+ <property name="stepService" ref="stepService" />
+ </bean>
+
+ <bean id="searchService"
+ class="org.splat.service.SearchServiceImpl">
+ <property name="indexService" ref="indexService" />
+ <property name="repositoryService" ref="repositoryService" />
+ </bean>
+
+ <bean id="stepService" class="org.splat.service.StepServiceImpl">
+ <property name="indexService" ref="indexService" />
+ </bean>
+
+ <bean id="studyService"
+ class="org.splat.service.StudyServiceImpl">
+ <property name="indexService" ref="indexService" />
+ <property name="projectElementService"
+ ref="projectElementService" />
+ <property name="projectSettings" ref="projectSettings" />
+ <property name="scenarioService" ref="scenarioService" />
+ <property name="stepService" ref="stepService" />
+ </bean>
+
+</beans>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xsi:schemaLocation="
+http://www.springframework.org/schema/beans
+http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+http://www.springframework.org/schema/aop
+http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+http://www.springframework.org/schema/tx
+http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+ <bean id="genericDAO" class="org.splat.dal.dao.kernel.GenericDAOImpl"
+ abstract="true">
+ <property name="sessionFactory" ref="simanSessionFactory" />
+ </bean>
+ <bean id="knowledgeElementDAO" parent="genericDAO"
+ class="org.splat.dal.dao.som.KnowledgeElementDAOImpl">
+ </bean>
+</beans>
\ No newline at end of file
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+ <!-- <bean id="simanDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
+ <property name="jndiName" value="jdbc/ibatis"/>
+ </bean> -->
+
+ <bean id="simanDatasource"
+ class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
+ <property name="driverClassName"
+ value="org.hibernate.dialect.MySQLInnoDBDialect" />
+ <property name="url" value="jdbc:mysql://localhost/simer" />
+ <property name="username" value="simer" />
+ <property name="password" value="admin" />
+ <property name="suppressClose" value="true" />
+ <property name="autoCommit" value="false" />
+ </bean>
+
+ <bean id="p6spySimanDatasource"
+ class="com.p6spy.engine.spy.P6DataSource">
+ <constructor-arg>
+ <ref local="simanDatasource" />
+ </constructor-arg>
+ </bean>
+
+ <bean id="simanSessionFactory"
+ class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
+ <property name="dataSource" ref="p6spySimanDatasource" />
+ <property name="mappingResources">
+ <list>
+ <value>
+ org/splat/dal/bo/kernel/Persistent.hbm.xml
+ </value>
+ <value>org/splat/dal/bo/kernel/Any.hbm.xml</value>
+ <value>org/splat/dal/bo/kernel/Entity.hbm.xml</value>
+ <value>org/splat/dal/bo/kernel/Attribute.hbm.xml</value>
+ <value>org/splat/dal/bo/kernel/Relation.hbm.xml</value>
+ <value>
+ org/splat/dal/bo/kernel/TextAttribute.hbm.xml
+ </value>
+ <value>org/splat/dal/bo/kernel/User.hbm.xml</value>
+
+ <value>
+ org/splat/dal/bo/som/ProjectElement.hbm.xml
+ </value>
+ <value>org/splat/dal/bo/som/Study.hbm.xml</value>
+ <value>org/splat/dal/bo/som/Scenario.hbm.xml</value>
+ <value>org/splat/dal/bo/som/Attributes.hbm.xml</value>
+ <value>org/splat/dal/bo/som/Relations.hbm.xml</value>
+ <value>org/splat/dal/bo/som/File.hbm.xml</value>
+ <value>org/splat/dal/bo/som/Document.hbm.xml</value>
+ <value>org/splat/dal/bo/som/Publication.hbm.xml</value>
+ <value>
+ org/splat/dal/bo/som/ValidationCycle.hbm.xml
+ </value>
+ <value>org/splat/dal/bo/som/Timestamp.hbm.xml</value>
+ <value>
+ org/splat/dal/bo/som/SimulationContext.hbm.xml
+ </value>
+ <value>
+ org/splat/dal/bo/som/KnowledgeElement.hbm.xml
+ </value>
+ <value>org/splat/dal/bo/som/IDBuilder.hbm.xml</value>
+ </list>
+ </property>
+ <property name="hibernateProperties">
+ <value>
+ hibernate.dialect=org.hibernate.dialect.HSQLDialect
+ hibernate.show_sql=true hbm2ddl.auto=update
+ hibernate.current_session_context_class=thread
+ </value>
+ </property>
+ <property name="exposeTransactionAwareSessionFactory">
+ <value>false</value>
+ </property>
+ </bean>
+
+ <bean id="txManager"
+ class="org.springframework.orm.hibernate3.HibernateTransactionManager">
+ <property name="dataSource" ref="p6spySimanDatasource" />
+ <property name="sessionFactory" ref="simanSessionFactory" />
+ </bean>
+
+ <tx:annotation-driven transaction-manager="txManager" />
+
+ <bean id="database" class="org.splat.dal.dao.som.Database">
+ <property name="sessionFactory" ref="simanSessionFactory" />
+ <property name="indexService" ref="indexService"/>
+ <property name="repositoryService" ref="repositoryService"/>
+ </bean>
</beans>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xsi:schemaLocation="
+http://www.springframework.org/schema/beans
+http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+http://www.springframework.org/schema/aop
+http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+http://www.springframework.org/schema/tx
+http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+ <bean id="repositoryService"
+ class="org.splat.service.technical.RepositoryServiceImpl" />
+
+ <bean id="projectSettings"
+ class="org.splat.service.technical.ProjectSettingsServiceImpl">
+ <property name="database" ref="database" />
+ </bean>
+
+ <bean id="indexService"
+ class="org.splat.service.technical.IndexServiceImpl">
+ <property name="projectElementService"
+ ref="projectElementService" />
+ <property name="repositoryService" ref="repositoryService" />
+ </bean>
+</beans>
\ No newline at end of file
import java.util.List;
import java.util.Vector;
+import org.splat.service.SearchServiceImpl;
+import org.splat.service.dto.Proxy;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
import org.splat.som.*;
+import org.splat.dal.bo.kernel.Role;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.ConvertsRelation;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.ValidationCycle;
+import org.splat.dal.dao.som.Database;
import org.splat.kernel.Do;
import org.splat.kernel.UserDirectory;
-import org.splat.kernel.User;
-import org.splat.kernel.Role;
import org.splat.manox.Reader;
import org.splat.manox.Toolbox;
import org.splat.manox.Writer;
// Main
// ==============================================================================================================================
- public static void main(String[] args) {
+ public static void main(String[] args) {/* TODO: Create unit tests
// --------------------------------------
Session session = Database.getSession(); // Single session for multiple operations
Transaction transax = session.beginTransaction();
- ProjectSettings project = ProjectSettings.getMe();
+ ProjectSettingsServiceImpl project = ProjectSettingsServiceImpl.getMe();
String path = System.getProperty("user.dir");
try {
project.configure(path + "/src/som.xml");
try {
Study.Properties criter1 = new Study.Properties().setState(ProgressState.inPROGRESS);
Study.Properties criter2 = new Study.Properties().setState(ProgressState.inWORK).setManager(user);
- List<Proxy> result = Database.selectStudiesWhere(criter1, criter2);
+ List<Proxy> result = SearchServiceImpl.selectStudiesWhere(criter1, criter2);
if (result.size() == 0) {
logger.info("No study found.");
} else {
String words = "sercoter";
try {
Study.Properties criteria = new Study.Properties();
- List<Proxy> result = Database.selectStudiesWhere(criteria.setTitle(words));
+ List<Proxy> result = SearchServiceImpl.selectStudiesWhere(criteria.setTitle(words));
if (result.size() == 0) {
logger.info("No study found with a title including \"" + words + "\".");
} else {
context.add(reactor);
Study.Properties sprop = new Study.Properties();
- List<Proxy> result = Database.selectStudiesWhere(sprop.setSimulationContexts(context)
+ List<Proxy> result = SearchServiceImpl.selectStudiesWhere(sprop.setSimulationContexts(context)
.setState(ProgressState.inPROGRESS));
if (result.size() == 0) {
logger.info("Study on Réacteur RAPSODIE not found.");
KnowledgeElementType ktype = KnowledgeElement.selectType("Bonne pratique");
KnowledgeElement.Properties sprop = new KnowledgeElement.Properties();
- List<Proxy> result = Database.selectKnowledgeElementsWhere(sprop.setSimulationContexts(context)
+ List<Proxy> result = SearchServiceImpl.selectKnowledgeElementsWhere(sprop.setSimulationContexts(context)
.setType(ktype));
if (result.size() == 0) {
logger.info("Study on Réacteur RAPSODIE not found.");
}
catch (Exception e) {
return false;
- }
+ }*/
}
}
\ No newline at end of file
<arguments>
</arguments>
</buildCommand>
+ <buildCommand>
+ <name>org.springframework.ide.eclipse.core.springbuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
</buildSpec>
<natures>
+ <nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/SPlat/lib/xmlpublic.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
- <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/SPlat/dist/splat-kernel.jar">
+ <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/SPlat/dist/splat-manox.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
- <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/SPlat/dist/splat-manox.jar">
+ <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/Siman-Common/dist/siman-common.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
- <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/SPlat/dist/splat-som.jar">
+ <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/Siman-Common/lib/p6spy.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
- <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/Siman-Common/dist/siman-common.jar">
+ <dependent-module deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/Siman-Common/lib/aopalliance.jar">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="build/classes"/>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<beansProjectDescription>
+ <configExtensions>
+ <configExtension>xml</configExtension>
+ </configExtensions>
+ <configs>
+ <config>src/spring/applicationContext.xml</config>
+ </configs>
+ <configSets>
+ <configSet>
+ <name><![CDATA[Siman web app beans]]></name>
+ <allowBeanDefinitionOverriding>true</allowBeanDefinitionOverriding>
+ <incomplete>false</incomplete>
+ <configs>
+ <config>/Siman-Common/src/spring/businessServiceContext.xml</config>
+ <config>/Siman-Common/src/spring/daoServiceContext.xml</config>
+ <config>/Siman-Common/src/spring/globalContext.xml</config>
+ <config>/Siman-Common/src/spring/technicalServiceContext.xml</config>
+ <config>src/spring/applicationContext.xml</config>
+ </configs>
+ </configSet>
+ </configSets>
+</beansProjectDescription>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
%>
-<%@ page import="org.splat.kernel.User"%>
-<%@ page import="org.splat.som.Study"%>
-<%@ page import="org.splat.som.KnowledgeElement"%>
+<%@ page import="org.splat.dal.bo.kernel.User"%>
+<%@ page import="org.splat.dal.bo.som.Study"%>
+<%@ page import="org.splat.dal.bo.som.KnowledgeElement"%>
<%@ page import="org.splat.som.ApplicationRights"%>
<%@ page import="org.splat.simer.ApplicationSettings"%>
<%@
<%@ page import="java.io.ObjectOutputStream"%>
<%@ page import="java.io.IOException"%>
<%@ page import="java.net.URL"%>
-<%@ page import="org.splat.kernel.User"%>
+<%@ page import="org.splat.dal.bo.kernel.User"%>
<%@ page import="org.splat.som.ApplicationRights"%>
<%@ page import="org.splat.simer.OpenStudyServices"%>
<%
<%@ page import="java.util.ResourceBundle"%>
<%@ page import="org.hibernate.Session"%>
<%@ page import="org.hibernate.Transaction"%>
-<%@ page import="org.splat.som.Database"%>
-<%@ page import="org.splat.som.Scenario"%>
-<%@ page import="org.splat.som.Publication"%>
-<%@ page import="org.splat.som.Document"%>
+<%@ page import="org.splat.dal.dao.som.Database"%>
+<%@ page import="org.splat.dal.bo.som.Scenario"%>
+<%@ page import="org.splat.dal.bo.som.Publication"%>
+<%@ page import="org.splat.dal.bo.som.Document"%>
<%@ page import="org.splat.som.ApplicationRights"%>
<%@ page import="org.splat.simer.OpenStudy"%>
<%@ page import="org.splat.simer.StudyMenu"%>
for (i=0; i<scene.length; i++) {
if (scene[i].getIndex() == j) break;
}
- scene[i].checkout(rights.getUser());
+ //TODO: RKV: scene[i].checkout(rights.getUser());
name = ResourceBundle.getBundle("som").getString("type.document.geometry") + "1";
ishared = false;
Document selecdoc = edited.value();
Scenario owner = (Scenario)edited.getOwner(); // In the GEOM context, the ProjectElement is necessarilly a Scenario
- owner.checkout(rights.getUser());
+ //TODO: RKV: owner.checkout(rights.getUser());
name = selecdoc.getTitle();
ishared = simer.getStudyObject().shares(selecdoc) || selecdoc.isVersioned();
<%@ page import="java.util.ResourceBundle"%>
<%@ page import="org.hibernate.Session"%>
<%@ page import="org.hibernate.Transaction"%>
-<%@ page import="org.splat.som.Database"%>
-<%@ page import="org.splat.som.Scenario"%>
-<%@ page import="org.splat.som.Publication"%>
-<%@ page import="org.splat.som.Document"%>
+<%@ page import="org.splat.dal.dao.som.Database"%>
+<%@ page import="org.splat.dal.bo.som.Scenario"%>
+<%@ page import="org.splat.dal.bo.som.Publication"%>
+<%@ page import="org.splat.dal.bo.som.Document"%>
<%@ page import="org.splat.som.ApplicationRights"%>
<%@ page import="org.splat.simer.OpenStudy"%>
<%@ page import="org.splat.simer.StudyMenu"%>
for (i=0; i<scene.length; i++) {
if (scene[i].getIndex() == j) break;
}
- scene[i].checkout(rights.getUser());
+ //TODO: RKV: scene[i].checkout(rights.getUser());
name = ResourceBundle.getBundle("som").getString("type.document.model") + "1";
ishared = false;
Document selecdoc = edited.value();
Scenario owner = (Scenario)edited.getOwner(); // In the GEOM context, the ProjectElement is necessarilly a Scenario
- owner.checkout(rights.getUser());
+ //TODO: RKV: owner.checkout(rights.getUser());
name = selecdoc.getTitle();
ishared = simer.getStudyObject().shares(selecdoc) || selecdoc.isVersioned();
<%@ page import="com.opensymphony.xwork2.util.ValueStack"%>
<%@ page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page import="org.splat.simer.StudyPropertiesAction"%>
-<%@ page import="org.splat.kernel.User"%>
+<%@ page import="org.splat.dal.bo.kernel.User"%>
<%@
taglib prefix="s" uri="/struts-tags"
%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
%>
-<%@ page import="org.splat.som.KnowledgeElement"%>
+<%@ page import="org.splat.dal.bo.som.KnowledgeElement"%>
<%@ page import="org.splat.som.ApplicationRights"%>
<%@ page import="org.splat.simer.ApplicationSettings"%>
<%@ page import="java.util.ResourceBundle"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
%>
-<%@ page import="org.splat.som.Study"%>
+<%@ page import="org.splat.dal.bo.som.Study"%>
<%@ page import="org.splat.som.ApplicationRights"%>
<%@ page import="org.splat.simer.ApplicationSettings"%>
<%@ page import="java.util.ResourceBundle"%>
connection.url=jdbc:mysql://localhost/simer
connection.username=simer
connection.password=admin
+#connection.driver_class=com.mysql.jdbc.Driver
+connection.driver_class=com.p6spy.engine.spy.P6SpyDriver
# Hibernate config
hbm2ddl.auto=update
# Log properties
hibernate.show_sql=true
root.logger.appender=<appender-ref ref="console"/>
-root.logger.level=INFO
+root.logger.level=DEBUG
com.opensymphony.logger.level=DEBUG
org.apache.struts2.logger.level=DEBUG
org.springframework.logger.level=DEBUG
connection.url=jdbc:mysql://localhost/simer
connection.username=simer
connection.password=admin
+connection.driver_class=com.p6spy.engine.spy.P6SpyDriver
# Hibernate config
hbm2ddl.auto=validate
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
-
-<hibernate-configuration>
-
-<!-- Generated at @datesimple@ @time@ -->
-<!-- @file.header@ -->
-
- <session-factory>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">@connection.url@</property>
- <property name="connection.username">@connection.username@</property>
- <property name="connection.password">@connection.password@</property>
-
- <!-- JDBC connection pool (use the built-in) -->
- <property name="connection.pool_size">1</property>
- <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
-
- <!-- SQL dialect -->
- <property name="dialect">@hibernate.dialect@</property>
-
- <!-- Enable Hibernate's automatic session context management -->
- <property name="current_session_context_class">thread</property>
-
- <!-- Echo all executed SQL statements to stdout -->
- <property name="hibernate.show_sql">@hibernate.show_sql@</property>
-
- <!-- Hibernate automatically updates db according to the mapping -->
- <property name="hbm2ddl.auto">@hbm2ddl.auto@</property>
-
- <!-- mapping files -->
- <mapping resource="org/splat/kernel/Persistent.hbm.xml" />
- <mapping resource="org/splat/kernel/Any.hbm.xml" />
- <mapping resource="org/splat/kernel/Entity.hbm.xml" />
- <mapping resource="org/splat/kernel/Attribute.hbm.xml" />
- <mapping resource="org/splat/kernel/Relation.hbm.xml" />
- <mapping resource="org/splat/kernel/IDPool.hbm.xml" />
- <mapping resource="org/splat/kernel/TextAttribute.hbm.xml" />
- <mapping resource="org/splat/kernel/User.hbm.xml" />
-
- <mapping resource="org/splat/som/ProjectElement.hbm.xml" />
- <mapping resource="org/splat/som/Study.hbm.xml" />
- <mapping resource="org/splat/som/Scenario.hbm.xml" />
- <mapping resource="org/splat/som/Attributes.hbm.xml" />
- <mapping resource="org/splat/som/Relations.hbm.xml" />
- <mapping resource="org/splat/som/File.hbm.xml" />
- <mapping resource="org/splat/som/Document.hbm.xml" />
- <mapping resource="org/splat/som/Publication.hbm.xml" />
- <mapping resource="org/splat/som/ValidationCycle.hbm.xml" />
- <mapping resource="org/splat/som/Timestamp.hbm.xml" />
- <mapping resource="org/splat/som/SimulationContext.hbm.xml" />
- <mapping resource="org/splat/som/KnowledgeElement.hbm.xml" />
- <mapping resource="org/splat/som/IDBuilder.hbm.xml" />
-
- </session-factory>
-
-</hibernate-configuration>
\ No newline at end of file
+++ /dev/null
-
-import org.splat.launcher.FileTransfer;
-import org.splat.launcher.WindowsRegistry;
-
-
-public class Test {
-
-
-// ==============================================================================================================================
-// Main
-// ==============================================================================================================================
-
- public static void main(String[] args) {
-// --------------------------------------
-// String url = "http://localhost:8080/repository/2011/PLM110001/1.Study";
- String command = args[0];
-// String filename = args[1];
-
- String applikey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Applications\\" + command;
- String key = "";
- String module = WindowsRegistry.readValue(applikey + "\\shell\\open\\command ", key);
- if (module == null) module = WindowsRegistry.readValue(applikey + "\\shell\\edit\\command ", key);
- try {
-// FileTransfer.Download(url, filename, path);
- String[] parse = module.split("/"); // Removing eventual options
-
- Runtime.getRuntime().exec(parse[0]);
-// Runtime.getRuntime().exec(parse[0] + " \"" + path + "\\" + filename + "\"");
- }
- catch (Exception error) {
- System.out.println("Unable to start " + module);
- }
- }
-}
\ No newline at end of file
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.kernel.Do;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
+import org.splat.service.PublicationService;
+import org.splat.service.ScenarioService;
+import org.splat.service.StepService;
import org.splat.simer.Action;
import org.splat.simer.OpenStudy;
-import org.splat.som.ConvertsRelation;
-import org.splat.som.Database;
-import org.splat.som.Document;
-import org.splat.som.DocumentType;
-import org.splat.som.ProgressState;
-import org.splat.som.Publication;
-import org.splat.som.Scenario;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
+import org.splat.dal.bo.som.ConvertsRelation;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
import org.splat.som.Step;
+public class SaveDocumentAction extends Action {
-public class SaveDocumentAction extends Action {
-
- private OpenStudy mystudy = null;
- private int doctype = 0;
- private String filename = null;
- private String docname = null;
- private ProgressState state = null;
- private List<Document> defuses = null;
- private String summary = null; // Summary of changes in the new version
+ private OpenStudy mystudy = null;
+ private int doctype = 0;
+ private String filename = null;
+ private String docname = null;
+ private ProgressState state = null;
+ private List<Document> defuses = null;
+ private String summary = null; // Summary of changes in the new version
+ private ScenarioService _scenarioService;
+ private PublicationService _publicationService;
+ private StepService _stepService;
private static final long serialVersionUID = -3364960833373200115L;
-// ==============================================================================================================================
-// Action methods
-// ==============================================================================================================================
-
- public String doSave () {
-// -----------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
-// Getting user inputs
- mystudy = getOpenStudy();
- User user = getConnectedUser();
- Step step = mystudy.getSelectedStep();
- DocumentType type = Document.selectType(doctype);
-// File updir = Database.getDownloadDirectory(user);
-// File upfile = new File(updir.getPath() + "/" + filename);
- String upath = Database.getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file between users
- File upfile = new File(upath + filename);
- String[] table = filename.split("\\x2E");
- String format = table[table.length-1];
-
-// Creation of the document
- ((Scenario)step.getOwner()).checkin(); // Modules necessarily save their data in a scenario step
- connex.flush();
-
- Document.Properties dprop = new Document.Properties();
- Publication credoc = step.createDocument(dprop.setName(docname)
- .setType(type)
- .setFormat(format)
- .setAuthor(user));
-// Writing the uploaded file into the created document
- File target = credoc.getSourceFile().asFile();
- if (target.exists()) target.delete();
- Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
-// upfile.renameTo(target);
-
-// Saving the document in given state
- credoc.saveAs(state);
-
-// Creation of default uses relations
- defuses = new Vector<Document>();
- setupDefaultUses(type); // Recursive function
- for (Iterator<Document> i=defuses.iterator(); i.hasNext(); ) {
- credoc.addDependency(i.next());
- }
-
-// Execution of module specific operations
-
-// 1. Conversion of the document to internal format, if required
-//TODO: The following code is temporary, waiting for the support of converters
- if (format.equals("part")) {
- ConvertsRelation export = credoc.attach("brep");
-
- target = export.getTo().asFile();
- if (target.exists()) target.delete();
- Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
- }
-// 2. Addition of simulation contexts
- if (type.equals("model")) { // Set the characteristics of the mesh
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- SimulationContextType ctype = SimulationContext.selectType("model");
- SimulationContext context = Database.selectSimulationContext(ctype, "Éléments finis");
- if (context == null) {
- step.addSimulationContext(cprop.setType(ctype).setValue("Éléments finis"));
- } else {
- step.addSimulationContext(context);
- }
- ctype = SimulationContext.selectType("element");
- context = Database.selectSimulationContext(ctype, "Surfacique");
- if (context == null) {
- step.addSimulationContext(cprop.setType(ctype).setValue("Surfacique"));
- } else {
- step.addSimulationContext(context);
- }
- ctype = SimulationContext.selectType("shape");
- context = Database.selectSimulationContext(ctype, "Triangles");
- if (context == null) {
- step.addSimulationContext(cprop.setType(ctype).setValue("Triangles"));
- } else {
- step.addSimulationContext(context);
- }
- }
-// Update of the open study
-// mystudy.add(credoc); // Useless while the SIMER page need to be refreshed manually
- getMenu("study").selects(mystudy.getSelection()); // Updates the menu icon, in case of first added document
-
- transax.commit();
- return SUCCESS;
- }
- catch (Exception saverror) {
- logger.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- }
-
- public String doUpdate () {
-// -------------------------
- return SUCCESS;
- }
-
- public String doVersion () {
-// --------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
-// Getting user inputs
- mystudy = getOpenStudy();
- User user = getConnectedUser();
- Step step = mystudy.getSelectedStep();
-// File updir = Database.getDownloadDirectory(user);
-// File upfile = new File(updir.getPath() + "/" + filename);
- String upath = Database.getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file between users
- File upfile = new File(upath + filename);
- String[] table = filename.split("\\x2E");
- String format = table[table.length-1];
-
-// Versioning of the document
- Publication current = mystudy.getSelectedDocument();
- Document.Properties dprop = new Document.Properties();
- dprop.setAuthor(user);
- if (summary.length() > 0) dprop.setDescription(summary);
-
- Publication next = step.versionDocument(current, dprop);
-
-// Writing the uploaded file into the created document
- File target = next.getSourceFile().asFile();
- if (target.exists()) target.delete();
- Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
-// upfile.renameTo(target);
-
-// Saving the document in given state
- next.saveAs(state);
-
-// Creation of default uses relations
- defuses = new Vector<Document>();
- setupDefaultUses(next.value().getType()); // Recursive function
- for (Iterator<Document> i=defuses.iterator(); i.hasNext(); ) {
- next.addDependency(i.next());
- }
-//TODO: Outdating impacted document
-
-// Execution of module specific operations
-
-// 1. Conversion of the document to internal format, if required
-//TODO: The following code is temporary, waiting for the support of converters
- if (format.equals("part")) {
- ConvertsRelation export = next.attach("brep");
- String fname = table[0];
-
- for (int i=1; i<table.length-1; i++) fname = fname + table[i];
- upfile = new File(upath + fname + ".brep");
- upfile.renameTo(export.getTo().asFile());
- }
-
-// Update of the open study
-// mystudy.setSelection(mystudy.getSelection()); // Rebuild the presentation
-
- transax.commit();
- return SUCCESS;
- }
- catch (Exception saverror) {
- logger.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- }
-
-// ==============================================================================================================================
-// Getters and setters
-// ==============================================================================================================================
-
- public String getDescription () {
-// -------------------------------
- return summary;
- }
-
- public void setDescription (String summary) {
-// -------------------------------------------
- this.summary = summary;
- }
- public void setDocumentName (String name) {
-// -----------------------------------------
- this.docname = name;
- }
- public void setDocumentState (String state) {
-// -------------------------------------------
- this.state = ProgressState.valueOf(state);
- }
- public void setDocumentType (String value) {
-// ------------------------------------------
- this.doctype = Integer.valueOf(value);
- }
- public void setFileName (String name) {
-// -------------------------------------
- this.filename = name;
- }
-// ==============================================================================================================================
-// Private service
-// ==============================================================================================================================
-
- private void setupDefaultUses (DocumentType type) {
-// -------------------------------------------------
- Set<DocumentType> uses = type.getDefaultUses();
-
- for (Iterator<DocumentType> i=uses.iterator(); i.hasNext();) {
- DocumentType usetype = i.next();
- List<Document> usedoc = mystudy.collectInvolvedDocuments(usetype);
- if (usedoc.isEmpty()) setupDefaultUses(usetype);
- else defuses.addAll(usedoc);
- }
- }
+ // ==============================================================================================================================
+ // Action methods
+ // ==============================================================================================================================
+
+ public String doSave() {
+ // -----------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ // Getting user inputs
+ mystudy = getOpenStudy();
+ User user = getConnectedUser();
+ Step step = mystudy.getSelectedStep();
+ DocumentType type = Document.selectType(doctype);
+ // File updir = Database.getDownloadDirectory(user);
+ // File upfile = new File(updir.getPath() + "/" + filename);
+ String upath = Database.getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file between users
+ File upfile = new File(upath + filename);
+ String[] table = filename.split("\\x2E");
+ String format = table[table.length - 1];
+
+ // Creation of the document
+ getScenarioService().checkin((Scenario) step.getOwner()); // Modules necessarily save their data in a scenario step
+ connex.flush();
+
+ Document.Properties dprop = new Document.Properties();
+ Publication credoc = step.createDocument(dprop.setName(docname)
+ .setType(type).setFormat(format).setAuthor(user));
+ // Writing the uploaded file into the created document
+ File target = credoc.getSourceFile().asFile();
+ if (target.exists())
+ target.delete();
+ Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
+ // upfile.renameTo(target);
+
+ // Saving the document in given state
+ getPublicationService().saveAs(credoc, state);
+
+ // Creation of default uses relations
+ defuses = new Vector<Document>();
+ setupDefaultUses(type); // Recursive function
+ for (Iterator<Document> i = defuses.iterator(); i.hasNext();) {
+ credoc.addDependency(i.next());
+ }
+
+ // Execution of module specific operations
+
+ // 1. Conversion of the document to internal format, if required
+ // TODO: The following code is temporary, waiting for the support of converters
+ if (format.equals("part")) {
+ ConvertsRelation export = credoc.attach("brep");
+
+ target = export.getTo().asFile();
+ if (target.exists())
+ target.delete();
+ Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
+ }
+ // 2. Addition of simulation contexts
+ if (type.equals("model")) { // Set the characteristics of the mesh
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ SimulationContextType ctype = SimulationContext
+ .selectType("model");
+ SimulationContext context = Database.selectSimulationContext(
+ ctype, "Éléments finis");
+ if (context == null) {
+ getStepService().addSimulationContext(step,
+ cprop.setType(ctype).setValue("Éléments finis"));
+ } else {
+ getStepService().addSimulationContext(step, context);
+ }
+ ctype = SimulationContext.selectType("element");
+ context = Database.selectSimulationContext(ctype, "Surfacique");
+ if (context == null) {
+ getStepService().addSimulationContext(step,
+ cprop.setType(ctype).setValue("Surfacique"));
+ } else {
+ getStepService().addSimulationContext(step, context);
+ }
+ ctype = SimulationContext.selectType("shape");
+ context = Database.selectSimulationContext(ctype, "Triangles");
+ if (context == null) {
+ getStepService().addSimulationContext(step,
+ cprop.setType(ctype).setValue("Triangles"));
+ } else {
+ getStepService().addSimulationContext(step, context);
+ }
+ }
+ // Update of the open study
+ // mystudy.add(credoc); // Useless while the SIMER page need to be refreshed manually
+ getMenu("study").selects(mystudy.getSelection()); // Updates the menu icon, in case of first added document
+
+ transax.commit();
+ return SUCCESS;
+ } catch (Exception saverror) {
+ logger.error("Reason:", saverror);
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ }
+ }
+
+ /**
+ * Get the publicationService.
+ *
+ * @return publicationService
+ */
+ private PublicationService getPublicationService() {
+ return _publicationService;
+ }
+
+ /**
+ * Set the publicationService.
+ *
+ * @param publicationService
+ * the publicationService to set
+ */
+ public void setPublicationService(PublicationService publicationService) {
+ _publicationService = publicationService;
+ }
+
+ /**
+ * Get the scenarioService.
+ *
+ * @return scenarioService
+ */
+ public ScenarioService getScenarioService() {
+ return _scenarioService;
+ }
+
+ /**
+ * Set the scenarioService.
+ *
+ * @param scenarioService
+ * the scenarioService to set
+ */
+ public void setScenarioService(ScenarioService scenarioService) {
+ _scenarioService = scenarioService;
+ }
+
+ /**
+ * Get the stepService.
+ *
+ * @return the stepService
+ */
+ public StepService getStepService() {
+ return _stepService;
+ }
+
+ /**
+ * Set the stepService.
+ *
+ * @param stepService
+ * the stepService to set
+ */
+ public void setStepService(StepService stepService) {
+ _stepService = stepService;
+ }
+
+ public String doUpdate() {
+ // -------------------------
+ return SUCCESS;
+ }
+
+ public String doVersion() {
+ // --------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ // Getting user inputs
+ mystudy = getOpenStudy();
+ User user = getConnectedUser();
+ Step step = mystudy.getSelectedStep();
+ // File updir = Database.getDownloadDirectory(user);
+ // File upfile = new File(updir.getPath() + "/" + filename);
+ String upath = Database.getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file between users
+ File upfile = new File(upath + filename);
+ String[] table = filename.split("\\x2E");
+ String format = table[table.length - 1];
+
+ // Versioning of the document
+ Publication current = mystudy.getSelectedDocument();
+ Document.Properties dprop = new Document.Properties();
+ dprop.setAuthor(user);
+ if (summary.length() > 0)
+ dprop.setDescription(summary);
+
+ Publication next = step.versionDocument(current, dprop);
+
+ // Writing the uploaded file into the created document
+ File target = next.getSourceFile().asFile();
+ if (target.exists())
+ target.delete();
+ Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
+ // upfile.renameTo(target);
+
+ // Saving the document in given state
+ getPublicationService().saveAs(next, state);
+
+ // Creation of default uses relations
+ defuses = new Vector<Document>();
+ setupDefaultUses(next.value().getType()); // Recursive function
+ for (Iterator<Document> i = defuses.iterator(); i.hasNext();) {
+ next.addDependency(i.next());
+ }
+ // TODO: Outdating impacted document
+
+ // Execution of module specific operations
+
+ // 1. Conversion of the document to internal format, if required
+ // TODO: The following code is temporary, waiting for the support of converters
+ if (format.equals("part")) {
+ ConvertsRelation export = next.attach("brep");
+ String fname = table[0];
+
+ for (int i = 1; i < table.length - 1; i++)
+ fname = fname + table[i];
+ upfile = new File(upath + fname + ".brep");
+ upfile.renameTo(export.getTo().asFile());
+ }
+
+ // Update of the open study
+ // mystudy.setSelection(mystudy.getSelection()); // Rebuild the presentation
+
+ transax.commit();
+ return SUCCESS;
+ } catch (Exception saverror) {
+ logger.error("Reason:", saverror);
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ }
+ }
+
+ // ==============================================================================================================================
+ // Getters and setters
+ // ==============================================================================================================================
+
+ public String getDescription() {
+ // -------------------------------
+ return summary;
+ }
+
+ public void setDescription(String summary) {
+ // -------------------------------------------
+ this.summary = summary;
+ }
+
+ public void setDocumentName(String name) {
+ // -----------------------------------------
+ this.docname = name;
+ }
+
+ public void setDocumentState(String state) {
+ // -------------------------------------------
+ this.state = ProgressState.valueOf(state);
+ }
+
+ public void setDocumentType(String value) {
+ // ------------------------------------------
+ this.doctype = Integer.valueOf(value);
+ }
+
+ public void setFileName(String name) {
+ // -------------------------------------
+ this.filename = name;
+ }
+
+ // ==============================================================================================================================
+ // Private service
+ // ==============================================================================================================================
+
+ private void setupDefaultUses(DocumentType type) {
+ // -------------------------------------------------
+ Set<DocumentType> uses = type.getDefaultUses();
+
+ for (Iterator<DocumentType> i = uses.iterator(); i.hasNext();) {
+ DocumentType usetype = i.next();
+ List<Document> usedoc = mystudy.collectInvolvedDocuments(usetype);
+ if (usedoc.isEmpty())
+ setupDefaultUses(usetype);
+ else
+ defuses.addAll(usedoc);
+ }
+ }
}
\ No newline at end of file
import org.apache.struts2.interceptor.SessionAware;
import org.apache.log4j.Logger;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.som.ApplicationRights;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.SimulationContextType;
-import org.splat.som.Study;
-import org.splat.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.DocumentType;
import org.splat.wapp.Menu;
import org.w3c.dom.NamedNodeMap;
import org.apache.log4j.Logger;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.manox.XDOM;
-import org.splat.som.Document;
+import org.splat.dal.bo.som.Document;
import org.splat.som.DocumentRights;
-import org.splat.som.DocumentType;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.SimulationContext;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.SimulationContext;
import org.splat.som.Step;
import org.splat.som.StudyRights;
import org.splat.wapp.MenuItem;
private static ApplicationSettings my = null; // Singleton instance
protected final static Logger logger = Logger.getLogger(ApplicationSettings.class);
+ private ProjectSettingsService _projectSettingsService;
+
+ /**
+ * Get the projectSettingsService.
+ * @return the projectSettingsService
+ */
+ public ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+ /**
+ * Set the projectSettingsService.
+ * @param projectSettingsService the projectSettingsService to set
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
private static class NewMenu extends SimpleMenu {
// -----------------------------------------------------------------
// ------------------------------------------
return my; // The application is supposed being previously created below
}
- protected ApplicationSettings (String wappurl, Locale lang) throws IOException {
-// -----------------------------------------------------------
+ /**
+ * @param wappurl
+ * @param lang
+ * @return
+ */
+ public ApplicationSettings init(String wappurl, Locale lang) throws IOException {
ClassLoader cloader = getClass().getClassLoader();
String[] wurl = wappurl.split("/"); // [0]="http:", [1]="", [2]="{server}:{port}", [3]="name"
logger.info("Application root set to " + wapprops.getProperty("wapp.root"));
my = this;
+ return this;
}
// ==============================================================================================================================
// Settings based on the customization
bars = new HashMap<Integer, ToolBar>(); // May be empty if no module installed
- List<ProjectSettings.Step> steps = ProjectSettings.getAllSteps();
- for (Iterator<ProjectSettings.Step> i=steps.iterator(); i.hasNext();) {
- ProjectSettings.Step step = i.next();
+ List<ProjectSettingsService.Step> steps = getProjectSettings().getAllSteps();
+ for (Iterator<ProjectSettingsService.Step> i=steps.iterator(); i.hasNext();) {
+ ProjectSettingsService.Step step = i.next();
List<String> formats = getDefaultFormats(step);
if (formats.size() == 0) continue;
// Private services
// ==============================================================================================================================
- private List<String> getDefaultFormats (ProjectSettings.Step step) {
+ private List<String> getDefaultFormats (ProjectSettingsService.Step step) {
// ------------------------------------------------------------------
Set<String> keys = defdoctype.keySet();
int number = step.getNumber();
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.som.ApplicationRights;
-import org.splat.som.Database;
+import org.splat.dal.dao.som.Database;
import java.io.IOException;
import javax.security.auth.login.FailedLoginException;
import javax.naming.InitialContext;
import org.splat.kernel.MismatchException;
-import org.splat.som.Document;
-import org.splat.som.Publication;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.Publication;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.som.Database;
-import org.splat.som.KnowledgeElement;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.KnowledgeElement;
import org.splat.som.Step;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.som.Database;
-import org.splat.som.ProjectElement;
-import org.splat.som.Scenario;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Scenario;
import org.splat.som.StepRights;
-import org.splat.som.Study;
+import org.splat.dal.bo.som.Study;
import org.splat.wapp.PopupMenu;
import org.splat.wapp.SimpleMenu;
import java.util.ResourceBundle;
import org.splat.manox.XMLDocument;
-import org.splat.kernel.Relation;
-import org.splat.som.ConvertsRelation;
-import org.splat.som.Document;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.som.ConvertsRelation;
+import org.splat.dal.bo.som.Document;
import org.splat.som.DocumentRights;
-import org.splat.som.DocumentType;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Publication;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.PublicationService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.Publication;
import org.splat.som.Revision;
import org.splat.som.Step;
-import org.splat.som.Timestamp;
-import org.splat.som.UsesRelation;
-import org.splat.som.VersionsRelation;
+import org.splat.dal.bo.som.Timestamp;
+import org.splat.dal.bo.som.UsesRelation;
+import org.splat.dal.bo.som.VersionsRelation;
import org.splat.wapp.PopupMenu;
private List<FileFacade> exports;
private List<HistoryFacade> history;
private PopupMenu popup;
+ private ProjectSettingsService _projectSettingsService;
+ private PublicationService _publicationService;
private enum State { closed, open, deepopen }
ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
DecimalFormat sizstring = new DecimalFormat(custom.getString("size.format")); // Locale size display format
SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format")); // Locale date display format
- Revision.Format verstring = new Revision.Format(ProjectSettings.getRevisionPattern());
+ Revision.Format verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
String path = my.getSourceFile().getRelativePath();
String[] mapping = ApplicationSettings.getViewersMapping();
for (int i=0; i<mapping.length; i++) {
- org.splat.som.File export = my.getAttachedFile(mapping[i]);
+ org.splat.dal.bo.som.File export = my.getAttachedFile(mapping[i]);
if (export == null) continue;
path = export.getRelativePath();
break;
else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("approved");
else { //(state == ProgressState.inCHECK)
DocumentType mytype = me.value().getType(); // Only result documents need to be approved
- Step mystep = me.getInvolvedStep();
+ Step mystep = getPublicationService().getInvolvedStep(me);
if (mytype.isResultOf(mystep.getStep())) popup = ApplicationSettings.getPopupMenu("approvable");
else popup = ApplicationSettings.getPopupMenu("notresult");
}
history.add( new DocumentFacade(owner, given) );
if (versions != null) collectHistory(versions.getTo());
}
+
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+ /**
+ * Get the publicationService.
+ *
+ * @return the publicationService
+ */
+ public PublicationService getPublicationService() {
+ return _publicationService;
+ }
+
+ /**
+ * Set the publicationService.
+ *
+ * @param publicationService
+ * the publicationService to set
+ */
+ public void setPublicationService(PublicationService publicationService) {
+ _publicationService = publicationService;
+ }
}
\ No newline at end of file
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.User;
-import org.splat.som.Database;
-import org.splat.som.Publication;
-import org.splat.som.ConvertsRelation;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.ConvertsRelation;
+import org.splat.service.PublicationService;
import org.splat.som.Step;
private String index = null;
private String title = null;
private String filename = null;
+ private PublicationService _publicationService;
private static final long serialVersionUID = 4573036736137033679L;
mystudy.update(doc);
} else
if (todo == Execute.promote) {
- doc.promote(Calendar.getInstance().getTime());
+ getPublicationService().promote(doc, Calendar.getInstance().getTime());
mystudy.update(doc);
} else
if (todo == Execute.demote) {
- doc.demote();
+ getPublicationService().demote(doc);
mystudy.update(doc);
} else
if (todo == Execute.review) {
- doc.review(Calendar.getInstance().getTime());
+ getPublicationService().review(doc, Calendar.getInstance().getTime());
mystudy.update(doc);
} else
if (todo == Execute.invalidate) {
- doc.invalidate();
+ getPublicationService().invalidate(doc);
mystudy.update(doc);
} else
if (todo == Execute.approve) {
- doc.approve(Calendar.getInstance().getTime());
+ getPublicationService().approve(doc, Calendar.getInstance().getTime());
mystudy.update(doc);
mystudy.getMenu().refreshSelectedItem(); // Updates the menu icon, in case of other documents in approved state
}
// -----------------------------------
this.index = index;
}
+ /**
+ * Get the publicationService.
+ *
+ * @return the publicationService
+ */
+ public PublicationService getPublicationService() {
+ return _publicationService;
+ }
+
+ /**
+ * Set the publicationService.
+ *
+ * @param publicationService
+ * the publicationService to set
+ */
+ public void setPublicationService(PublicationService publicationService) {
+ _publicationService = publicationService;
+ }
}
\ No newline at end of file
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.kernel.User;
-import org.splat.som.Database;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.KnowledgeElementType;
-import org.splat.som.Scenario;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.service.KnowledgeElementService;
+import org.splat.service.ScenarioService;
import org.splat.som.Step;
private String type = null; // Edited knowledge type
private String title = null;
private String value = null;
+ private ScenarioService _scenarioService;
+ private KnowledgeElementService _knowledgeElementService;
private static final long serialVersionUID = 4636919137087687068L;
.setTitle(title)
.setValue(value)
.setAuthor(user);
- mystudy.add( scene.addKnowledgeElement(kprop) );
+ mystudy.add( getScenarioService().addKnowledgeElement(scene, kprop) );
getMenu("study").selects(mystudy.getSelection()); // Updates the menu icon, in case of first added document
} else
if (title != null) { // Renaming of an existing Knowledge Element
KnowledgeElement kelm = scene.getKnowledgeElement(Integer.valueOf(type));
- kelm.rename(title);
+ getKnowledgeElementService().rename(kelm, title);
// Useless to update the open study
} else
if (value != null) { // Edition of a knowledge
// --------------------------------------------
this.value = value;
}
+ /**
+ * Get the scenarioService.
+ * @return the scenarioService
+ */
+ public ScenarioService getScenarioService() {
+ return _scenarioService;
+ }
+
+ /**
+ * Set the scenarioService.
+ * @param scenarioService the scenarioService to set
+ */
+ public void setScenarioService(ScenarioService scenarioService) {
+ _scenarioService = scenarioService;
+ }
+
+ /**
+ * Get the knowledgeElementService.
+ * @return the knowledgeElementService
+ */
+ public KnowledgeElementService getKnowledgeElementService() {
+ return _knowledgeElementService;
+ }
+
+ /**
+ * Set the knowledgeElementService.
+ * @param knowledgeElementService the knowledgeElementService to set
+ */
+ public void setKnowledgeElementService(
+ KnowledgeElementService knowledgeElementService) {
+ _knowledgeElementService = knowledgeElementService;
+ }
}
\ No newline at end of file
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.kernel.User;
-import org.splat.som.Database;
-import org.splat.som.Scenario;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.service.ProjectElementService;
+import org.splat.service.ScenarioService;
import org.splat.som.Step;
import org.splat.som.StepRights;
-
public class EditScenarioPropertiesAction extends DisplayStudyStepAction {
- private Scenario myscenario;
- private String lasdate;
- private String subject;
+ private Scenario myscenario;
+ private String lasdate;
+ private String subject;
+ private ScenarioService _scenarioService;
+ private ProjectElementService _projectElementService;
private static final long serialVersionUID = 4964740932426016171L;
-// ==============================================================================================================================
-// Action methods
-// ==============================================================================================================================
-
- public String doInitialize () {
-// -----------------------------
- ResourceBundle label = ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale());
- ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
- SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format")); // Locale date display format
- Step step;
-
- mystudy = getOpenStudy();
- step = mystudy.getSelectedStep();
- myscenario = (Scenario)step.getOwner(); // The selected step belong to a scenario
- lasdate = datstring.format(myscenario.getLastModificationDate());
- subject = label.getString("label.study") + " " + mystudy.getTitle();
-
- return SUCCESS;
- }
-
- public String doCheckin () {
-// --------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- Step step;
-
- mystudy = getOpenStudy();
- selection = mystudy.getSelection();
- step = mystudy.getSelectedStep();
- myscenario = (Scenario)step.getOwner(); // The selected step belong to a scenario
-
- myscenario.checkin();
- transax.commit();
-
- mystudy.getMenu().refreshGivenStepItem(myscenario.getFirstStep()); // For updating the scenario icon
- return SUCCESS;
- }
-
-// ==============================================================================================================================
-// Getters
-// ==============================================================================================================================
-
- public User getAuthor () {
-// ------------------------
- if (myscenario.isCheckedout()) return myscenario.getUser();
- else return myscenario.getAuthor();
- }
-
- public String getLastModificationDate () {
-// ----------------------------------------
- return lasdate;
- }
-
- public StepRights getSelectedStep () {
-// ------------------------------------
- return mystudy.getSelectedStepRights(); // Forget about the step as only step enabling is tested
- }
-
- public String getSubject () {
-// ---------------------------
- return subject;
- }
- public String getTitle () {
-// -------------------------
- return myscenario.getTitle();
- }
-
- public boolean isCheckedout () {
-// ------------------------------
- return myscenario.isCheckedout();
- }
+ // ==============================================================================================================================
+ // Action methods
+ // ==============================================================================================================================
+
+ public String doInitialize() {
+ // -----------------------------
+ ResourceBundle label = ResourceBundle.getBundle("labels",
+ ApplicationSettings.getCurrentLocale());
+ ResourceBundle custom = ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale());
+ SimpleDateFormat datstring = new SimpleDateFormat(
+ custom.getString("date.format")); // Locale date display format
+ Step step;
+
+ mystudy = getOpenStudy();
+ step = mystudy.getSelectedStep();
+ myscenario = (Scenario) step.getOwner(); // The selected step belong to a scenario
+ lasdate = datstring.format(myscenario.getLastModificationDate());
+ subject = label.getString("label.study") + " " + mystudy.getTitle();
+
+ return SUCCESS;
+ }
+
+ public String doCheckin() {
+ // --------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ Step step;
+
+ mystudy = getOpenStudy();
+ selection = mystudy.getSelection();
+ step = mystudy.getSelectedStep();
+ myscenario = (Scenario) step.getOwner(); // The selected step belong to a scenario
+
+ getScenarioService().checkin(myscenario);
+ transax.commit();
+
+ mystudy.getMenu().refreshGivenStepItem(
+ getProjectElementService().getFirstStep(myscenario)); // For updating the scenario icon
+ return SUCCESS;
+ }
+
+ // ==============================================================================================================================
+ // Getters
+ // ==============================================================================================================================
+
+ public User getAuthor() {
+ // ------------------------
+ if (myscenario.isCheckedout())
+ return myscenario.getUser();
+ else
+ return myscenario.getAuthor();
+ }
+
+ public String getLastModificationDate() {
+ // ----------------------------------------
+ return lasdate;
+ }
+
+ public StepRights getSelectedStep() {
+ // ------------------------------------
+ return mystudy.getSelectedStepRights(); // Forget about the step as only step enabling is tested
+ }
+
+ public String getSubject() {
+ // ---------------------------
+ return subject;
+ }
+
+ public String getTitle() {
+ // -------------------------
+ return myscenario.getTitle();
+ }
+
+ public boolean isCheckedout() {
+ // ------------------------------
+ return myscenario.isCheckedout();
+ }
+
+ /**
+ * Get the scenarioService.
+ *
+ * @return the scenarioService
+ */
+ public ScenarioService getScenarioService() {
+ return _scenarioService;
+ }
+
+ /**
+ * Set the scenarioService.
+ *
+ * @param scenarioService
+ * the scenarioService to set
+ */
+ public void setScenarioService(ScenarioService scenarioService) {
+ _scenarioService = scenarioService;
+ }
+
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
}
\ No newline at end of file
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.som.Database;
-import org.splat.som.ProjectElement;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.service.StepService;
+import org.splat.service.StudyService;
import org.splat.som.Step;
-import org.splat.som.Study;
-
+import org.splat.dal.bo.som.Study;
public class EditSimulationContextAction extends DisplayStudyStepAction {
- private List<SimulationContextType> contype = null;
- private List<SimulationContext> contelm = null;
- private String selectype = null; // Context type, if selected
- private String newtype = null; // Context type, if newed
- private SimulationContextType type = null; // Corresponding context type object
- private String value = null; // Context value
-
- private static final long serialVersionUID = -641719644024601042L;
-
-// ==============================================================================================================================
-// Action methods
-// ==============================================================================================================================
-
- public String doInitialize () {
-// -----------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
-
- mystudy = getOpenStudy();
- contype = getInvolvedContexts();
-
- transax.commit();
- if (contype.isEmpty()) return "create";
- else return "select";
- }
-
- public String doSelectContext () {
-// --------------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
- mystudy = getOpenStudy();
- int typid = Integer.valueOf(selectype);
- if (typid == 0) return "create";
-
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- type = SimulationContext.selectType(typid);
- newtype = type.getName();
- contype = getInvolvedContexts();
- contelm = Database.selectSimulationContextsWhere(cprop.setType(type));
-
- return "set";
- }
- finally {
- transax.commit();
- }
- }
-
- public String doCreateContext () {
-// --------------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
- mystudy = getOpenStudy();
- if (newtype.length() == 0 || value.length() == 0) return INPUT;
-
- Step step = mystudy.getSelectedStep();
- ProjectElement owner = step.getOwner();
-
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- SimulationContext contex = null;
- type = SimulationContext.createType(newtype, step.getStep());
- cprop.setType(type).setValue(value);
- if (owner instanceof Study) contex = ((Study)owner).addProjectContext(cprop); // Re-indexes knowledges and the study
- else contex = step.addSimulationContext(cprop); // Re-indexes knowledges only
-
- mystudy.add(contex);
- transax.commit();
- return SUCCESS;
- }
- catch (RuntimeException saverror) {
- logger.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- catch (Exception error) {
- transax.commit();
- return INPUT;
- }
- }
-
- public String doDeleteContext () {
-// --------------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
- mystudy = getOpenStudy();
-
- Step step = mystudy.getSelectedStep();
- ProjectElement owner = step.getOwner();
- SimulationContext context = step.getSimulationContext(Integer.valueOf(myindex));
- if (owner instanceof Study) ((Study)owner).removeProjectContext(context); // Re-indexes knowledges and the study
- else step.removeSimulationContext(context); // Re-indexes knowledges only
-
- mystudy.remove(context);
- transax.commit();
- return SUCCESS;
- }
- catch (RuntimeException saverror) {
- logger.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- }
-
- public String doSetContext () {
-// -----------------------------
- String[] input = value.split(",");
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
+ private List<SimulationContextType> contype = null;
+ private List<SimulationContext> contelm = null;
+ private String selectype = null; // Context type, if selected
+ private String newtype = null; // Context type, if newed
+ private SimulationContextType type = null; // Corresponding context type object
+ private String value = null; // Context value
+ private StudyService _studyService;
+ private StepService _stepService;
+
+ /**
+ * Get the stepService.
+ *
+ * @return the stepService
+ */
+ public StepService getStepService() {
+ return _stepService;
+ }
+
+ /**
+ * Set the stepService.
+ *
+ * @param stepService
+ * the stepService to set
+ */
+ public void setStepService(StepService stepService) {
+ _stepService = stepService;
+ }
+
+ private static final long serialVersionUID = -641719644024601042L;
+
+ // ==============================================================================================================================
+ // Action methods
+ // ==============================================================================================================================
+
+ public String doInitialize() {
+ // -----------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+
mystudy = getOpenStudy();
+ contype = getInvolvedContexts();
+
+ transax.commit();
+ if (contype.isEmpty())
+ return "create";
+ else
+ return "select";
+ }
+
+ public String doSelectContext() {
+ // --------------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ mystudy = getOpenStudy();
+ int typid = Integer.valueOf(selectype);
+ if (typid == 0)
+ return "create";
+
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ type = SimulationContext.selectType(typid);
+ newtype = type.getName();
+ contype = getInvolvedContexts();
+ contelm = Database.selectSimulationContextsWhere(cprop
+ .setType(type));
+
+ return "set";
+ } finally {
+ transax.commit();
+ }
+ }
+
+ public String doCreateContext() {
+ // --------------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ mystudy = getOpenStudy();
+ if (newtype.length() == 0 || value.length() == 0)
+ return INPUT;
+
+ Step step = mystudy.getSelectedStep();
+ ProjectElement owner = step.getOwner();
+
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ SimulationContext contex = null;
+ type = SimulationContext.createType(newtype, step.getStep());
+ cprop.setType(type).setValue(value);
+ if (owner instanceof Study)
+ contex = getStudyService().addProjectContext(((Study) owner),
+ cprop); // Re-indexes knowledges and the study
+ else
+ contex = getStepService().addSimulationContext(step, cprop); // Re-indexes knowledges only
+
+ mystudy.add(contex);
+ transax.commit();
+ return SUCCESS;
+ } catch (RuntimeException saverror) {
+ logger.error("Reason:", saverror);
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ } catch (Exception error) {
+ transax.commit();
+ return INPUT;
+ }
+ }
+
+ public String doDeleteContext() {
+ // --------------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ mystudy = getOpenStudy();
+
+ Step step = mystudy.getSelectedStep();
+ ProjectElement owner = step.getOwner();
+ SimulationContext context = step.getSimulationContext(Integer
+ .valueOf(myindex));
+ if (owner instanceof Study)
+ getStudyService()
+ .removeProjectContext(((Study) owner), context); // Re-indexes knowledges and the study
+ else
+ getStepService().removeSimulationContext(step, context); // Re-indexes knowledges only
+
+ mystudy.remove(context);
+ transax.commit();
+ return SUCCESS;
+ } catch (RuntimeException saverror) {
+ logger.error("Reason:", saverror);
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ }
+ }
+
+ public String doSetContext() {
+ // -----------------------------
+ String[] input = value.split(",");
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ mystudy = getOpenStudy();
+
+ Step step = mystudy.getSelectedStep();
+ ProjectElement owner = step.getOwner();
+ SimulationContext contex = null;
+
+ if (input.length == 1
+ || (input.length == 2 && input[1].equals(" "))) {
+ // Setting an existing simulation context identified by value (input = rid," ")
+ int valid = Integer.valueOf(input[0]);
+ contex = Database.selectSimulationContext(valid);
+ if (owner instanceof Study)
+ getStudyService()
+ .addProjectContext(((Study) owner), contex);
+ else
+ getStepService().addSimulationContext(step, contex);
+ } else {
+ // Setting a new simulation context value (input = 0,"new context value")
+ int typid = Integer.valueOf(selectype);
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ cprop.setType(SimulationContext.selectType(typid)).setValue(
+ input[1].trim());
+ if (owner instanceof Study)
+ contex = getStudyService().addProjectContext(
+ ((Study) owner), cprop); // Re-indexes knowledges and the study
+ else
+ contex = getStepService().addSimulationContext(step, cprop); // Re-indexes knowledges only
+ }
+ mystudy.add(contex);
+ contype = getInvolvedContexts();
+
+ transax.commit();
+ return SUCCESS;
+ } catch (RuntimeException saverror) {
+ logger.error("Reason:", saverror);
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ } catch (Exception error) {
+ value = input[0];
+ transax.commit();
+ return INPUT;
+ }
+ }
+
+ // ==============================================================================================================================
+ // Getters and setters
+ // ==============================================================================================================================
+
+ public SimulationContextType getContextType() {
+ // ----------------------------------------------
+ return type;
+ }
+
+ public String getContextName() {
+ // -------------------------------
+ return newtype;
+ }
+
+ // public List<SimulationContextFacade> getSimulationContexts () {
+ // -------------------------------------------------------
+ // return mystudy.getSelectedStep().getAllSimulationContexts();
+ // }
+ public List<SimulationContextType> getSimulationContextTypes() {
+ // ---------------------------------------------------------------
+ return contype;
+ }
+
+ public List<SimulationContext> getSimulationContextValues() {
+ // ------------------------------------------------------------
+ return contelm;
+ }
+
+ public void setContextType(String type) {
+ // ----------------------------------------
+ this.selectype = type;
+ }
+
+ public void setContextValue(String value) {
+ // -----------------------------------------
+ this.value = value;
+ }
+
+ public void setNewType(String name) {
+ // ------------------------------------
+ this.newtype = name;
+ }
+
+ // ==============================================================================================================================
+ // Private service
+ // ==============================================================================================================================
+
+ private List<SimulationContextType> getInvolvedContexts() {
+ // ----------------------------------------------------------
+ SimulationContextType.Properties sprop = new SimulationContextType.Properties()
+ .setStep(mystudy.getSelectedStep().getStep());
+ List<SimulationContextType> contype = SimulationContext
+ .selectTypesWhere(sprop);
+
+ if (!contype.isEmpty()) {
+ // Ordering by alphabetical order of localized context types
+ SimulationContextType[] types = contype
+ .toArray(new SimulationContextType[contype.size()]);
+ ContextTypeComparator compare = new ContextTypeComparator();
+ boolean state = types[0].isApproved();
+ int from = 0;
+ int to = 0;
+ while (to < types.length - 1) {
+ to += 1;
+ if (types[to].isApproved() == state)
+ continue;
+
+ if (to > from + 1)
+ Arrays.sort(types, from, to, compare);
+ state = !state;
+ from = to;
+ }
+ if (to > from)
+ Arrays.sort(types, from, to + 1, compare);
+ contype = Arrays.asList(types);
+ }
+ return contype;
+ }
+
+ /**
+ * Get the studyService.
+ *
+ * @return the studyService
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
- Step step = mystudy.getSelectedStep();
- ProjectElement owner = step.getOwner();
- SimulationContext contex = null;
-
- if (input.length == 1 || (input.length == 2 && input[1].equals(" "))) {
-// Setting an existing simulation context identified by value (input = rid," ")
- int valid = Integer.valueOf(input[0]);
- contex = Database.selectSimulationContext(valid);
- if (owner instanceof Study) ((Study)owner).addProjectContext(contex);
- else step.addSimulationContext(contex);
- }
- else {
-// Setting a new simulation context value (input = 0,"new context value")
- int typid = Integer.valueOf(selectype);
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- cprop.setType(SimulationContext.selectType(typid))
- .setValue(input[1].trim());
- if (owner instanceof Study) contex = ((Study)owner).addProjectContext(cprop); // Re-indexes knowledges and the study
- else contex = step.addSimulationContext(cprop); // Re-indexes knowledges only
- }
- mystudy.add(contex);
- contype = getInvolvedContexts();
-
- transax.commit();
- return SUCCESS;
- }
- catch (RuntimeException saverror) {
- logger.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- catch (Exception error) {
- value = input[0];
- transax.commit();
- return INPUT;
- }
- }
-
-// ==============================================================================================================================
-// Getters and setters
-// ==============================================================================================================================
-
- public SimulationContextType getContextType () {
-// ----------------------------------------------
- return type;
- }
- public String getContextName () {
-// -------------------------------
- return newtype;
- }
-// public List<SimulationContextFacade> getSimulationContexts () {
-// -------------------------------------------------------
-// return mystudy.getSelectedStep().getAllSimulationContexts();
-// }
- public List<SimulationContextType> getSimulationContextTypes () {
-// ---------------------------------------------------------------
- return contype;
- }
- public List<SimulationContext> getSimulationContextValues () {
-// ------------------------------------------------------------
- return contelm;
- }
-
- public void setContextType (String type) {
-// ----------------------------------------
- this.selectype = type;
- }
- public void setContextValue (String value) {
-// -----------------------------------------
- this.value = value;
- }
- public void setNewType (String name) {
-// ------------------------------------
- this.newtype = name;
- }
-
-// ==============================================================================================================================
-// Private service
-// ==============================================================================================================================
-
- private List<SimulationContextType> getInvolvedContexts () {
-// ----------------------------------------------------------
- SimulationContextType.Properties sprop = new SimulationContextType.Properties()
- .setStep(mystudy.getSelectedStep().getStep());
- List<SimulationContextType> contype = SimulationContext.selectTypesWhere(sprop);
-
- if (!contype.isEmpty()) {
-// Ordering by alphabetical order of localized context types
- SimulationContextType[] types = contype.toArray( new SimulationContextType[contype.size()] );
- ContextTypeComparator compare = new ContextTypeComparator();
- boolean state = types[0].isApproved();
- int from = 0;
- int to = 0;
- while (to < types.length-1) {
- to += 1;
- if (types[to].isApproved() == state) continue;
-
- if (to > from+1) Arrays.sort(types, from, to, compare);
- state = !state;
- from = to;
- }
- if (to > from) Arrays.sort(types, from, to+1, compare);
- contype = Arrays.asList(types);
- }
- return contype;
+ /**
+ * Set the studyService.
+ *
+ * @param studyService
+ * the studyService to set
+ */
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
}
}
\ No newline at end of file
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.som.Database;
-import org.splat.som.Study;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Study;
+import org.splat.service.StudyService;
public class EditStudyAction extends DisplayStudyStepAction {
private enum Execute { publish, promote }
+ private StudyService _studyService;
+
// ==============================================================================================================================
// Action methods
// ==============================================================================================================================
Execute todo = Execute.valueOf(action);
Study study = mystudy.getStudyObject();
- if (todo == Execute.publish) study.moveToPublic();
- else if (todo == Execute.promote) study.moveToReference();
+ if (todo == Execute.publish) getStudyService().moveToPublic(study);
+ else if (todo == Execute.promote) getStudyService().moveToReference(study);
mystudy.getPopup().setContext("study", mystudy.getStudyRights()); // The context has changed
// Useless to update the open study
return ERROR;
}
}
+ /**
+ * Get the studyService.
+ *
+ * @return the studyService
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
+
+ /**
+ * Set the studyService.
+ *
+ * @param studyService
+ * the studyService to set
+ */
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
+ }
}
\ No newline at end of file
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;
-import org.splat.som.ConvertsRelation;
+import org.splat.dal.bo.som.ConvertsRelation;
public class FileFacade {
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.manox.Reader;
import org.splat.manox.Toolbox;
-import org.splat.som.Database;
-import org.splat.som.Document;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Publication;
-import org.splat.som.DocumentType;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.PublicationService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.DocumentType;
import org.splat.som.Revision;
import org.splat.som.Step;
-
public class ImportDocumentAction extends UploadBaseNextAction {
- private List<DocumentType> doctypes = null;
- private int doctype = 0;
- private String docref = null; // Reference extracted from the imported file, if exist
- private String docver = ""; // Version number extracted from the imported file, if exist
- private String date = ""; // Date extracted from the imported file, if exist
-
- private static final long serialVersionUID = 2587822564883588556L;
-
-// ==============================================================================================================================
-// Action methods
-// ==============================================================================================================================
-
- public String doInitialize () {
-// -----------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- User user = getConnectedUser();
- File updir = Database.getDownloadDirectory(user);
- File upfile = new File(updir.getPath() + "/" + filename);
- String[] table = filename.split("\\x2E");
- String filext = table[table.length-1].toLowerCase();
-
- mystudy = getOpenStudy();
- Step step = mystudy.getSelectedStep();
- doctypes = step.getValidDocumentTypes();
- deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
- defuses = new Vector<Document>();
- state = ProgressState.inWORK;
-
- Reader tool = Toolbox.getReader(upfile);
- if (tool != null) {
- String fileref = tool.extractProperty("reference");
- String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
- String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
- for (Iterator<DocumentType> i=doctypes.iterator(); i.hasNext(); ) {
- DocumentType type = i.next();
- if (!type.getName().equals(filetype)) continue;
- deftype = type;
- doctype = type.getIndex(); // Disables the document type field
- break;
- }
- if (fileref != null) {
- Document slot = Database.selectDocument(fileref, new Revision().toString());
- if (slot == null) {
- setErrorCode("reference.undefined");
- return ERROR;
- }
- else {
- if (!slot.isUndefined()) {
- setErrorCode("reference.duplicate");
- return ERROR;
- }
- docref = fileref; // Disables document name and state fields
- deftype = slot.getType(); // Just in case
- doctype = deftype.getIndex(); // Disables the document type field
- }
- }
- if (filever != null) try {
- Revision.Format get = new Revision.Format(ProjectSettings.getRevisionPattern());
- Revision version = get.parse(filever);
- if ( version.isNull() ) throw new ParseException(filever, filever.length()-1);
- if (!version.isMinor()) state = ProgressState.inCHECK;
- docver = version.toString();
- } catch (ParseException e) {
- setErrorCode("format.version");
- return ERROR;
- }
- docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
- date = tool.extractProperty("date");
- if (date != null) {
- ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
- SimpleDateFormat check = new SimpleDateFormat(locale.getString("date.format"));
- try {
- check.parse(date);
- } catch (ParseException e) {
- setErrorCode("format.date");
- return ERROR;
- }
- } else date = "";
- } else
- if (filext.equals("pdf")) state = ProgressState.EXTERN; //TODO: Should external extensions be configurable ?
- if (docname == null) {
- docname = table[0];
- for (int i=1; i<table.length-1; i++) docname = docname + "." + table[i];
- }
- if (deftype != null) setupDefaultUses(deftype);
-
- DocumentType[] types = doctypes.toArray( new DocumentType[doctypes.size()] );
- DocumentTypeComparator compare = new DocumentTypeComparator();
- Arrays.sort(types, compare);
- doctypes = Arrays.asList(types);
-
- transax.commit();
- return SUCCESS;
- }
-
- public String doImport () {
-// -------------------------
- if (action == ToDo.cancel) return "cancel";
- if (doctype == 0 ) {
- setErrorCode("import.type");
- return ERROR;
- }
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
-// Getting user inputs
- mystudy = getOpenStudy();
- User user = getConnectedUser();
- Step step = mystudy.getSelectedStep();
- DocumentType type = Document.selectType(doctype);
- File updir = Database.getDownloadDirectory(user);
- File upfile = new File(updir.getPath() + "/" + filename);
- String[] table = filename.split("\\x2E");
-
-// Creation of the document
- Document.Properties dprop = new Document.Properties();
- Publication addoc;
-
- if (docref.length() == 0) { // Importation of a foreign document
-//TODO: Extract property of supported documents (DOCX, ODT...)
- addoc = step.createDocument(dprop.setName(docname).setType(type).setFormat(table[table.length-1]).setAuthor(user));
- updir = addoc.getSourceFile().asFile();
- if (logger.isInfoEnabled()) logger.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\".");
- upfile.renameTo(updir);
- try {
- addoc.saveAs(state); // May throw FileNotFound if rename was not done
- } catch (FileNotFoundException saverror) {
- Thread.sleep(1000);
- logger.info("Waiting for the file.");
- upfile.renameTo(updir);
- addoc.saveAs(state); // Forget it if throw again FileNotFound
- }
- }
- else { // Importation of a previously created template-based document
- if (date.length() > 0) {
- ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
- SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
- dprop.setDate(get.parse(date));
- }
- addoc = step.assignDocument(dprop.setReference(docref).setName(docname));
- updir = addoc.getSourceFile().asFile();
- if (logger.isInfoEnabled()) logger.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\".");
- upfile.renameTo(updir);
- try {
- if (docver.length() > 0) addoc.saveAs(new Revision(docver));
- else addoc.saveAs(state);
- } catch (FileNotFoundException saverror) {
- Thread.sleep(1000);
- logger.info("Waiting for the file.");
- upfile.renameTo(updir);
- if (docver.length() > 0) addoc.saveAs(new Revision(docver));
- else addoc.saveAs(state);
- }
- mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
- }
-// Creation of uses relations
- if (docuses != null) {
- String[] list = docuses.split(",");
- for (int i=0; i<list.length; i++) {
- Integer index = Integer.valueOf(list[i].trim());
- Publication used = getPublication(index);
- addoc.addDependency(used);
- }
- }
-// Creation of derived the document formats
-// Document ndoc = addoc.value();
-// Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
-//
-// if (send != null) send.converts(addoc); // Asynchronous process
- transax.commit();
-
- mystudy.add(addoc); // Updates the presentation
- return SUCCESS;
- }
- catch (FileNotFoundException error) {
- logger.error("Reason:", error);
- setErrorCode("import.file");
- }
- catch (Exception error) {
- logger.error("Reason:", error);
- setErrorCode("internal");
- }
- if (transax != null && transax.isActive()) { // Probably useless test
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
-
-// ==============================================================================================================================
-// Getters and setters
-// ==============================================================================================================================
-
- public String getDocumentDate () {
-// --------------------------------
- return date;
- }
- public List<DocumentType> getDocumentTypes () {
-// ---------------------------------------------
- return doctypes;
- }
- public int getDocumentType () {
-// -----------------------------
- return doctype;
- }
- public String getReference () {
-// -----------------------------
- return docref;
- }
- public String getVersion () {
-// ---------------------------
- return docver;
- }
-
- public void setDocumentDate (String date) {
-// -----------------------------------------
- this.date = date;
- }
- public void setDocumentName (String name) {
-// -----------------------------------------
- this.docname = name; // Name entered by the user if enabled
- }
- public void setDocumentTitle (String name) { // Called even if DocumentName is enabled
-// -----------------------------------------
- if (this.docname == null) this.docname = name;
- }
- public void setDocumentType (String value) {
-// ------------------------------------------
- this.doctype = Integer.valueOf(value);
- }
- public void setDefaultDocumentState (String state) { // Called even if DocumentState is enabled
-// --------------------------------------------------
- if (this.state == null) this.state = ProgressState.valueOf(state);
- }
- public void setDefaultDocumentType (String value) { // Called even if DocumentType is enabled
-// --------------------------------------------------
- if (this.doctype == 0) this.doctype = Integer.valueOf(value);
- }
- public void setReference (String value) {
-// ---------------------------------------
- this.docref = value;
- }
- public void setVersion (String value) {
-// -------------------------------------
- this.docver = value;
- }
+ private List<DocumentType> doctypes = null;
+ private int doctype = 0;
+ private String docref = null; // Reference extracted from the imported file, if exist
+ private String docver = ""; // Version number extracted from the imported file, if exist
+ private String date = ""; // Date extracted from the imported file, if exist
+ private ProjectSettingsService _projectSettingsService;
+ private PublicationService _publicationService;
+
+ private static final long serialVersionUID = 2587822564883588556L;
+
+ // ==============================================================================================================================
+ // Action methods
+ // ==============================================================================================================================
+
+ public String doInitialize() {
+ // -----------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ User user = getConnectedUser();
+ File updir = Database.getDownloadDirectory(user);
+ File upfile = new File(updir.getPath() + "/" + filename);
+ String[] table = filename.split("\\x2E");
+ String filext = table[table.length - 1].toLowerCase();
+
+ mystudy = getOpenStudy();
+ Step step = mystudy.getSelectedStep();
+ doctypes = step.getValidDocumentTypes();
+ deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
+ defuses = new Vector<Document>();
+ state = ProgressState.inWORK;
+
+ Reader tool = Toolbox.getReader(upfile);
+ if (tool != null) {
+ String fileref = tool.extractProperty("reference");
+ String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
+ String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
+ for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
+ DocumentType type = i.next();
+ if (!type.getName().equals(filetype))
+ continue;
+ deftype = type;
+ doctype = type.getIndex(); // Disables the document type field
+ break;
+ }
+ if (fileref != null) {
+ Document slot = Database.selectDocument(fileref,
+ new Revision().toString());
+ if (slot == null) {
+ setErrorCode("reference.undefined");
+ return ERROR;
+ } else {
+ if (!slot.isUndefined()) {
+ setErrorCode("reference.duplicate");
+ return ERROR;
+ }
+ docref = fileref; // Disables document name and state fields
+ deftype = slot.getType(); // Just in case
+ doctype = deftype.getIndex(); // Disables the document type field
+ }
+ }
+ if (filever != null)
+ try {
+ Revision.Format get = new Revision.Format(
+ getProjectSettings().getRevisionPattern());
+ Revision version = get.parse(filever);
+ if (version.isNull())
+ throw new ParseException(filever, filever.length() - 1);
+ if (!version.isMinor())
+ state = ProgressState.inCHECK;
+ docver = version.toString();
+ } catch (ParseException e) {
+ setErrorCode("format.version");
+ return ERROR;
+ }
+ docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
+ date = tool.extractProperty("date");
+ if (date != null) {
+ ResourceBundle locale = ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale());
+ SimpleDateFormat check = new SimpleDateFormat(
+ locale.getString("date.format"));
+ try {
+ check.parse(date);
+ } catch (ParseException e) {
+ setErrorCode("format.date");
+ return ERROR;
+ }
+ } else
+ date = "";
+ } else if (filext.equals("pdf"))
+ state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
+ if (docname == null) {
+ docname = table[0];
+ for (int i = 1; i < table.length - 1; i++)
+ docname = docname + "." + table[i];
+ }
+ if (deftype != null)
+ setupDefaultUses(deftype);
+
+ DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
+ .size()]);
+ DocumentTypeComparator compare = new DocumentTypeComparator();
+ Arrays.sort(types, compare);
+ doctypes = Arrays.asList(types);
+
+ transax.commit();
+ return SUCCESS;
+ }
+
+ public String doImport() {
+ // -------------------------
+ if (action == ToDo.cancel)
+ return "cancel";
+ if (doctype == 0) {
+ setErrorCode("import.type");
+ return ERROR;
+ }
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ // Getting user inputs
+ mystudy = getOpenStudy();
+ User user = getConnectedUser();
+ Step step = mystudy.getSelectedStep();
+ DocumentType type = Document.selectType(doctype);
+ File updir = Database.getDownloadDirectory(user);
+ File upfile = new File(updir.getPath() + "/" + filename);
+ String[] table = filename.split("\\x2E");
+
+ // Creation of the document
+ Document.Properties dprop = new Document.Properties();
+ Publication addoc;
+
+ if (docref.length() == 0) { // Importation of a foreign document
+ // TODO: Extract property of supported documents (DOCX, ODT...)
+ addoc = step.createDocument(dprop.setName(docname)
+ .setType(type).setFormat(table[table.length - 1])
+ .setAuthor(user));
+ updir = addoc.getSourceFile().asFile();
+ if (logger.isInfoEnabled())
+ logger.info("Moving \"" + upfile.getName() + "\" to \""
+ + updir.getPath() + "\".");
+ upfile.renameTo(updir);
+ try {
+ getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
+ } catch (FileNotFoundException saverror) {
+ Thread.sleep(1000);
+ logger.info("Waiting for the file.");
+ upfile.renameTo(updir);
+ getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
+ }
+ } else { // Importation of a previously created template-based document
+ if (date.length() > 0) {
+ ResourceBundle locale = ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale());
+ SimpleDateFormat get = new SimpleDateFormat(
+ locale.getString("date.format"));
+ dprop.setDate(get.parse(date));
+ }
+ addoc = step.assignDocument(dprop.setReference(docref).setName(
+ docname));
+ updir = addoc.getSourceFile().asFile();
+ if (logger.isInfoEnabled())
+ logger.info("Moving \"" + upfile.getName() + "\" to \""
+ + updir.getPath() + "\".");
+ upfile.renameTo(updir);
+ try {
+ if (docver.length() > 0)
+ getPublicationService().saveAs(addoc,
+ new Revision(docver));
+ else
+ getPublicationService().saveAs(addoc, state);
+ } catch (FileNotFoundException saverror) {
+ Thread.sleep(1000);
+ logger.info("Waiting for the file.");
+ upfile.renameTo(updir);
+ if (docver.length() > 0)
+ getPublicationService().saveAs(addoc,
+ new Revision(docver));
+ else
+ getPublicationService().saveAs(addoc, state);
+ }
+ mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
+ }
+ // Creation of uses relations
+ if (docuses != null) {
+ String[] list = docuses.split(",");
+ for (int i = 0; i < list.length; i++) {
+ Integer index = Integer.valueOf(list[i].trim());
+ Publication used = getPublication(index);
+ addoc.addDependency(used);
+ }
+ }
+ // Creation of derived the document formats
+ // Document ndoc = addoc.value();
+ // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
+ //
+ // if (send != null) send.converts(addoc); // Asynchronous process
+ transax.commit();
+
+ mystudy.add(addoc); // Updates the presentation
+ return SUCCESS;
+ } catch (FileNotFoundException error) {
+ logger.error("Reason:", error);
+ setErrorCode("import.file");
+ } catch (Exception error) {
+ logger.error("Reason:", error);
+ setErrorCode("internal");
+ }
+ if (transax != null && transax.isActive()) { // Probably useless test
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ }
+
+ // ==============================================================================================================================
+ // Getters and setters
+ // ==============================================================================================================================
+
+ public String getDocumentDate() {
+ // --------------------------------
+ return date;
+ }
+
+ public List<DocumentType> getDocumentTypes() {
+ // ---------------------------------------------
+ return doctypes;
+ }
+
+ public int getDocumentType() {
+ // -----------------------------
+ return doctype;
+ }
+
+ public String getReference() {
+ // -----------------------------
+ return docref;
+ }
+
+ public String getVersion() {
+ // ---------------------------
+ return docver;
+ }
+
+ public void setDocumentDate(String date) {
+ // -----------------------------------------
+ this.date = date;
+ }
+
+ public void setDocumentName(String name) {
+ // -----------------------------------------
+ this.docname = name; // Name entered by the user if enabled
+ }
+
+ public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
+ // -----------------------------------------
+ if (this.docname == null)
+ this.docname = name;
+ }
+
+ public void setDocumentType(String value) {
+ // ------------------------------------------
+ this.doctype = Integer.valueOf(value);
+ }
+
+ public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
+ // --------------------------------------------------
+ if (this.state == null)
+ this.state = ProgressState.valueOf(state);
+ }
+
+ public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
+ // --------------------------------------------------
+ if (this.doctype == 0)
+ this.doctype = Integer.valueOf(value);
+ }
+
+ public void setReference(String value) {
+ // ---------------------------------------
+ this.docref = value;
+ }
+
+ public void setVersion(String value) {
+ // -------------------------------------
+ this.docver = value;
+ }
+
+ /**
+ * Get project settings.
+ *
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ *
+ * @param projectSettingsService
+ * project settings service
+ */
+ public void setProjectSettings(ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+ /**
+ * Get the publicationService.
+ *
+ * @return the publicationService
+ */
+ public PublicationService getPublicationService() {
+ return _publicationService;
+ }
+
+ /**
+ * Set the publicationService.
+ *
+ * @param publicationService
+ * the publicationService to set
+ */
+ public void setPublicationService(PublicationService publicationService) {
+ _publicationService = publicationService;
+ }
}
\ No newline at end of file
package org.splat.simer;
-import org.splat.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElement;
import org.splat.wapp.PopupMenu;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.som.Database;
-import org.splat.som.Publication;
-import org.splat.som.Scenario;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.service.ProjectElementService;
+import org.splat.service.StudyService;
import org.splat.som.Step;
-import org.splat.som.Study;
+import org.splat.dal.bo.som.Study;
import org.splat.wapp.Menu;
private int scindex;
private int bastep;
private ToDo action;
+ private StudyService _studyService;
+ private ProjectElementService _projectElementService;
private static final long serialVersionUID = -5586724442986956861L;
myscene = Arrays.asList(scene);
scindex = base.getIndex();
mytitle = locale.getString("label.scenario") + " " + String.valueOf(scene.length+1);
- bastep = base.getFirstStep().getNumber(); // Better use the last current step ?
+ bastep = getProjectElementService().getFirstStep(base).getNumber(); // Better use the last current step ?
selection = scindex + "." + bastep;
action = null;
Scenario[] scene = study.getScenarii();
myscene = Arrays.asList(scene);
- bastep = scene[0].getFirstStep().getNumber(); // All scenarios have the same first step number
+ bastep = getProjectElementService().getFirstStep(scene[0]).getNumber(); // All scenarios have the same first step number
action = null;
getMenu("scenario").selects(selection);
Step[] step = null;
Scenario.Properties sprop = new Scenario.Properties().setManager(getConnectedUser()).setTitle(mytitle).setInsertAfter(bascene);
- bastep = bascene.getFirstStep().getNumber();
+ bastep = getProjectElementService().getFirstStep(bascene).getNumber();
if (this.sharesStep()) {
- step = bascene.getSteps();
+ step = getProjectElementService().getSteps(bascene);
sprop.setBaseStep(step[number-bastep]);
}
- bascene = study.addScenario(sprop);
+ bascene = getStudyService().addScenario(study, sprop);
transax.commit();
// Update of the display
// ----------------------------
return (Integer.valueOf(getSharedStep()) > bastep);
}
+ /**
+ * Get the studyService.
+ *
+ * @return the studyService
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
+
+ /**
+ * Set the studyService.
+ *
+ * @param studyService
+ * the studyService to set
+ */
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
+ }
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
}
\ No newline at end of file
import java.util.Iterator;
import java.util.Vector;
-import org.splat.som.Scenario;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.service.ProjectElementService;
+import org.splat.service.ScenarioService;
import org.splat.som.Step;
-import org.splat.som.Study;
+import org.splat.dal.bo.som.Study;
import org.splat.wapp.MenuItem;
import org.splat.wapp.SlidMenu;
-
public class NewScenarioMenu extends SlidMenu {
- private Study study;
- private Scenario scopen; // Currently "open" scenario
- private Step stopen; // Currently selected step
-
-// ==============================================================================================================================
-// Constructor
-// ==============================================================================================================================
-
- public NewScenarioMenu (Study context) {
-// -----------------------------------
- super("scenarii", "study");
- study = context;
- scopen = null;
- }
-
-// ==============================================================================================================================
-// Member functions
-// ==============================================================================================================================
-
- public void selects (String name) {
-// ---------------------------------
- String[] parse = name.split("\\x2E");
- Scenario[] scenes = study.getScenarii();
- Scenario scenew = scopen;
- int askid = 0;
-
-// Initialization
- if (scenew == null && scenes.length == 1) scenew = scenes[0];
- try {
- int askdex = Integer.valueOf(parse[0]);
- if (askdex > 0) {
- while (askid < scenes.length) {
- if (scenes[askid].getIndex() == askdex) break;
- askid += 1;
- }
- scenew = scenes[askid]; // Throws an exception if the scenario does not exist (that is, if name is not correct)
- }
- } catch (Exception error) {
- return;
- }
- if (scenew == null) {
-
-// Study with several scenarii, non of them open
-
-// Collection of steps to be displayed
- Vector<Step> steps = new Vector<Step>();
- Step[] newstep = scenes[0].getSteps(); // All scenarii have the same steps
-
- for (int i=0; i<scenes.length; i++) steps.add(scenes[i].getFirstStep());
- newstep = study.getSteps();
- stopen = newstep[0]; // Default selected step
-
-// Creation of the menu
- for (Iterator<Step> i=steps.iterator(); i.hasNext(); ) {
- Step step = i.next();
- int number = step.getNumber();
- Scenario group = (Scenario)step.getOwner(); // The menu includes first scenario steps only
- int index = group.getIndex();
- String value = index + "." + number;
- String icon;
- if (group.isEmpty()) icon = "icon.empty.png";
-// else if (group.isFinished()) icon = "icon.checked.png";
- else icon = "icon.done.png";
- addGroup(value, group.getTitle(), icon, "select-step?selection=" + value + "&title=%{title}");
- }
- } else
- if (scopen == null || !scenew.equals(scopen)) {
-
-// Opening a scenario
- this.clear();
-// Collection of steps to be displayed
- Vector<Step> steps = new Vector<Step>();
- Step[] newstep = scenew.getSteps();
-
- for (int i=0; i<newstep.length; i++) {
- steps.add(newstep[i]);
- }
- for (int i=askid-1; i>-1; i--) steps.add(0, scenes[i].getFirstStep());
- newstep = study.getSteps();
- for (int i=askid+1; i<scenes.length; i++) steps.add(scenes[i].getFirstStep());
-
-// Creation of the menu
- boolean first = true; // For differentiating the first scenario step
- int askdex = Integer.valueOf(parse[1]);
- for (Iterator<Step> i=steps.iterator(); i.hasNext(); ) {
- Step step = i.next();
- int number = step.getNumber();
- String icon;
- if (!step.isStarted()) icon = "icon.empty.png";
- else if (step.isFinished()) icon = "icon.checked.png";
- else icon = "icon.done.png";
- if (number == askdex) stopen = step;
- Scenario group = (Scenario)step.getOwner();
- int index = group.getIndex();
- String value = index + "." + number;
- if (index != scenew.getIndex()) {
- if (group.isEmpty()) icon = "icon.empty.png";
-// else if (group.isFinished()) icon = "icon.checked.png";
- else icon = "icon.done.png";
- addGroup(value, group.getTitle(), icon, "select-step?selection=" + value + "&title=%{title}");
- } else if (first) {
- addGroup(value, scenew.getTitle(), icon, "select-step?selection=" + value + "&title=%{title}");
- first = false;
- } else {
- addSubItem(value, "menu.step." + number, icon, "select-step?selection=" + value + "&title=%{title}");
- }
- }
- scopen = scenew;
- }
- super.selects(name);
- }
-
- public void refreshSelectedItem () {
-// ----------------------------------
- MenuItem item = this.getSelectedItem();
- String icon;
- if (!stopen.isStarted()) icon = "icon.empty.png";
- else if (stopen.isFinished()) icon = "icon.checked.png";
- else icon = "icon.done.png";
- item.icon(icon);
- }
+ private Study study;
+ private Scenario scopen; // Currently "open" scenario
+ private Step stopen; // Currently selected step
+ private ProjectElementService _projectElementService;
+ private ScenarioService _scenarioService;
+
+ // ==============================================================================================================================
+ // Constructor
+ // ==============================================================================================================================
+
+ public NewScenarioMenu(Study context) {
+ // -----------------------------------
+ super("scenarii", "study");
+ study = context;
+ scopen = null;
+ }
+
+ // ==============================================================================================================================
+ // Member functions
+ // ==============================================================================================================================
+
+ public void selects(String name) {
+ // ---------------------------------
+ String[] parse = name.split("\\x2E");
+ Scenario[] scenes = study.getScenarii();
+ Scenario scenew = scopen;
+ int askid = 0;
+
+ // Initialization
+ if (scenew == null && scenes.length == 1)
+ scenew = scenes[0];
+ try {
+ int askdex = Integer.valueOf(parse[0]);
+ if (askdex > 0) {
+ while (askid < scenes.length) {
+ if (scenes[askid].getIndex() == askdex)
+ break;
+ askid += 1;
+ }
+ scenew = scenes[askid]; // Throws an exception if the scenario does not exist (that is, if name is not correct)
+ }
+ } catch (Exception error) {
+ return;
+ }
+ if (scenew == null) {
+
+ // Study with several scenarii, non of them open
+
+ // Collection of steps to be displayed
+ Vector<Step> steps = new Vector<Step>();
+ Step[] newstep = getProjectElementService().getSteps(scenes[0]); // All scenarii have the same steps
+
+ for (int i = 0; i < scenes.length; i++)
+ steps.add(getProjectElementService().getFirstStep(scenes[i]));
+ newstep = getProjectElementService().getSteps(study);
+ stopen = newstep[0]; // Default selected step
+
+ // Creation of the menu
+ for (Iterator<Step> i = steps.iterator(); i.hasNext();) {
+ Step step = i.next();
+ int number = step.getNumber();
+ Scenario group = (Scenario) step.getOwner(); // The menu includes first scenario steps only
+ int index = group.getIndex();
+ String value = index + "." + number;
+ String icon;
+ if (getScenarioService().isEmpty(group))
+ icon = "icon.empty.png";
+ // else if (group.isFinished()) icon = "icon.checked.png";
+ else
+ icon = "icon.done.png";
+ addGroup(value, group.getTitle(), icon,
+ "select-step?selection=" + value + "&title=%{title}");
+ }
+ } else if (scopen == null || !scenew.equals(scopen)) {
+
+ // Opening a scenario
+ this.clear();
+ // Collection of steps to be displayed
+ Vector<Step> steps = new Vector<Step>();
+ Step[] newstep = getProjectElementService().getSteps(scenew);
+
+ for (int i = 0; i < newstep.length; i++) {
+ steps.add(newstep[i]);
+ }
+ for (int i = askid - 1; i > -1; i--)
+ steps.add(0, getProjectElementService().getFirstStep(scenes[i]));
+ newstep = getProjectElementService().getSteps(study);
+ for (int i = askid + 1; i < scenes.length; i++)
+ steps.add(getProjectElementService().getFirstStep(scenes[i]));
+
+ // Creation of the menu
+ boolean first = true; // For differentiating the first scenario step
+ int askdex = Integer.valueOf(parse[1]);
+ for (Iterator<Step> i = steps.iterator(); i.hasNext();) {
+ Step step = i.next();
+ int number = step.getNumber();
+ String icon;
+ if (!step.isStarted())
+ icon = "icon.empty.png";
+ else if (step.isFinished())
+ icon = "icon.checked.png";
+ else
+ icon = "icon.done.png";
+ if (number == askdex)
+ stopen = step;
+ Scenario group = (Scenario) step.getOwner();
+ int index = group.getIndex();
+ String value = index + "." + number;
+ if (index != scenew.getIndex()) {
+ if (getScenarioService().isEmpty(group))
+ icon = "icon.empty.png";
+ // else if (group.isFinished()) icon = "icon.checked.png";
+ else
+ icon = "icon.done.png";
+ addGroup(value, group.getTitle(), icon,
+ "select-step?selection=" + value
+ + "&title=%{title}");
+ } else if (first) {
+ addGroup(value, scenew.getTitle(), icon,
+ "select-step?selection=" + value
+ + "&title=%{title}");
+ first = false;
+ } else {
+ addSubItem(value, "menu.step." + number, icon,
+ "select-step?selection=" + value
+ + "&title=%{title}");
+ }
+ }
+ scopen = scenew;
+ }
+ super.selects(name);
+ }
+
+ public void refreshSelectedItem() {
+ // ----------------------------------
+ MenuItem item = this.getSelectedItem();
+ String icon;
+ if (!stopen.isStarted())
+ icon = "icon.empty.png";
+ else if (stopen.isFinished())
+ icon = "icon.checked.png";
+ else
+ icon = "icon.done.png";
+ item.icon(icon);
+ }
+
+ /**
+ * Get the scenarioService.
+ *
+ * @return the scenarioService
+ */
+ public ScenarioService getScenarioService() {
+ return _scenarioService;
+ }
+
+ /**
+ * Set the scenarioService.
+ *
+ * @param scenarioService
+ * the scenarioService to set
+ */
+ public void setScenarioService(ScenarioService scenarioService) {
+ _scenarioService = scenarioService;
+ }
+
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
}
\ No newline at end of file
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.som.Database;
-import org.splat.som.Scenario;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
-import org.splat.som.Study;
-
+import org.splat.dal.dao.som.Database;
+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.service.StudyService;
public class NewStudyAction extends Action {
- private String title = null;
+ private String title = null;
private List<SimulationContext> contelm = null;
- private String context = null;
-
- private static int number = 0;
- private static final long serialVersionUID = 693943641800113782L;
-
-// ==============================================================================================================================
-// Action methods
-// ==============================================================================================================================
-
- public String doInitialize () {
-// -----------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
-
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- SimulationContextType product = SimulationContext.selectType("product");
- ResourceBundle locale = ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale());
-
- contelm = Database.selectSimulationContextsWhere(cprop.setType(product));
- title = locale.getString("label.study") + " " + String.valueOf(number + 1);
- transax.commit();
- return SUCCESS;
- }
-
- public String doCreate () throws Exception {
-// -------------------------
- String[] input = context.split(",");
- int valid = Integer.valueOf(input[0]);
- String value = ""; // input[1] if exists
-
- Session session = Database.getSession();
- Transaction transax = session.beginTransaction();
- Study.Properties sprop = new Study.Properties();
-
-// Check arguments and creation of the study
- try {
- if (valid == -1) throw new Exception();
- if (valid == 0) {
- value = input[1].trim();
- if (value.length() == 0) return INPUT; // No need to reinitialize the list of existing products
- }
- sprop.setTitle(title).setManager(getConnectedUser());
- sprop.checkValidity();
- sprop.disableCheck();
- }
- catch (Exception error) {
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- SimulationContextType product = SimulationContext.selectType("product");
- contelm = Database.selectSimulationContextsWhere(cprop.setType(product));
- transax.commit();
- return INPUT; // Title empty, simply wait for input without error message
- }
- try {
- Study study = Database.createStudy(sprop);
-
-// Addition of a default scenario
- ResourceBundle locale = ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale());
- Scenario.Properties oprop = new Scenario.Properties();
- oprop.setTitle(locale.getString("label.scenario") + " 1");
- study.addScenario(oprop);
-
-// Addition of the entered project context
- if (valid == 0) { // Input of new project context
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- cprop.setType(SimulationContext.selectType("product")).setValue(value);
- study.addProjectContext(cprop);
+ private String context = null;
+
+ private static int number = 0;
+ private static final long serialVersionUID = 693943641800113782L;
+
+ private StudyService _studyService;
+
+ // ==============================================================================================================================
+ // Action methods
+ // ==============================================================================================================================
+
+ public String doInitialize() {
+ // -----------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ SimulationContextType product = SimulationContext.selectType("product");
+ ResourceBundle locale = ResourceBundle.getBundle("labels",
+ ApplicationSettings.getCurrentLocale());
+
+ contelm = Database
+ .selectSimulationContextsWhere(cprop.setType(product));
+ title = locale.getString("label.study") + " "
+ + String.valueOf(number + 1);
+ transax.commit();
+ return SUCCESS;
+ }
+
+ public String doCreate() throws Exception {
+ // -------------------------
+ String[] input = context.split(",");
+ int valid = Integer.valueOf(input[0]);
+ String value = ""; // input[1] if exists
+
+ Session session = Database.getSession();
+ Transaction transax = session.beginTransaction();
+ Study.Properties sprop = new Study.Properties();
+
+ // Check arguments and creation of the study
+ try {
+ if (valid == -1)
+ throw new Exception();
+ if (valid == 0) {
+ value = input[1].trim();
+ if (value.length() == 0)
+ return INPUT; // No need to reinitialize the list of existing products
+ }
+ sprop.setTitle(title).setManager(getConnectedUser());
+ sprop.checkValidity();
+ sprop.disableCheck();
+ } catch (Exception error) {
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ SimulationContextType product = SimulationContext
+ .selectType("product");
+ contelm = Database.selectSimulationContextsWhere(cprop
+ .setType(product));
+ transax.commit();
+ return INPUT; // Title empty, simply wait for input without error message
}
- else { // Selection of existing project context
- SimulationContext context = Database.selectSimulationContext(valid);
- study.addProjectContext(context);
+ try {
+ Study study = getStudyService().createStudy(sprop);
+
+ // Addition of a default scenario
+ ResourceBundle locale = ResourceBundle.getBundle("labels",
+ ApplicationSettings.getCurrentLocale());
+ Scenario.Properties oprop = new Scenario.Properties();
+ oprop.setTitle(locale.getString("label.scenario") + " 1");
+ getStudyService().addScenario(study, oprop);
+
+ // Addition of the entered project context
+ if (valid == 0) { // Input of new project context
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ cprop.setType(SimulationContext.selectType("product"))
+ .setValue(value);
+ getStudyService().addProjectContext(study, cprop);
+ } else { // Selection of existing project context
+ SimulationContext context = Database
+ .selectSimulationContext(valid);
+ getStudyService().addProjectContext(study, context);
+ }
+ // Update of the session
+ number += 1;
+ open(study); // Opens the study,
+ transax.commit();
+ return SUCCESS;
+ } catch (Exception error) {
+ logger.error("Unable to save the study, reason:", error);
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
}
-// Update of the session
- number += 1;
- open(study); // Opens the study,
- transax.commit();
- return SUCCESS;
- }
- catch (Exception error) {
- logger.error("Unable to save the study, reason:", error);
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
}
-// ==============================================================================================================================
-// Getters and setters
-// ==============================================================================================================================
-
- public String getProjectContext () {
-// ----------------------------------
- return context;
- }
- public List<SimulationContext> getProjectContextValues () {
-// ---------------------------------------------------------
- return contelm;
- }
- public String getTitle () {
-// ----------------------------
- return title;
- }
-
- public void setProjectContext (String value) {
-// --------------------------------------------
- this.context = value;
- }
- public void setTitle (String value) {
-// -----------------------------------
- this.title = value;
- }
+ // ==============================================================================================================================
+ // Getters and setters
+ // ==============================================================================================================================
+
+ public String getProjectContext() {
+ // ----------------------------------
+ return context;
+ }
+
+ public List<SimulationContext> getProjectContextValues() {
+ // ---------------------------------------------------------
+ return contelm;
+ }
+
+ public String getTitle() {
+ // ----------------------------
+ return title;
+ }
+
+ public void setProjectContext(String value) {
+ // --------------------------------------------
+ this.context = value;
+ }
+
+ public void setTitle(String value) {
+ // -----------------------------------
+ this.title = value;
+ }
+
+ /**
+ * Get the studyService.
+ *
+ * @return the studyService
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
+
+ /**
+ * Set the studyService.
+ *
+ * @param studyService
+ * the studyService to set
+ */
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
+ }
}
\ No newline at end of file
import java.util.ResourceBundle;
import java.util.Vector;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.ProgressState;
-import org.splat.som.Scenario;
-import org.splat.som.SimulationContext;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.service.ProjectElementService;
import org.splat.som.Step;
import org.splat.wapp.SimpleMenu;
-
public class OpenKnowledge extends OpenObject {
- private KnowledgeElement myknelm ;
- private String credate;
+ private KnowledgeElement myknelm;
+ private String credate;
+ private ProjectElementService _projectElementService;
public class Menu extends SimpleMenu {
-// ------------------------------------
- public Menu (List<Step> context)
- {
- super("steps", "study");
- int i = 0;
- int j = 0;
- for (Iterator<Step> k=context.iterator(); k.hasNext(); i++) {
- Step step = k.next();
- int number = step.getNumber();
- String icon;
- if (step.mayContain(KnowledgeElement.class)) j = i + 1; // Steps are numbered from 1 to N
- if (!step.isStarted()) icon = "icon.empty.png";
- else icon = "icon.done.png";
- addItem(String.valueOf(number), "folder.step." + number, icon, "step-knowledge?selection=" + number);
- }
- this.selects(String.valueOf(j));
- }
- }
-
-// ==============================================================================================================================
-// Constructor
-// ==============================================================================================================================
-
- public OpenKnowledge (KnowledgeElement knelm) {
-// ---------------------------------------------
- ResourceBundle label = ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale());
- ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
- SimpleDateFormat convert = new SimpleDateFormat(custom.getString("date.format"));
- StringBuffer value = new StringBuffer(knelm.getValue());
- Scenario scene = knelm.getOwnerScenario();
-
- myknelm = knelm;
-
-// Preparation of the display
- credate = convert.format(myknelm.getDate());
- involving = getAllSteps(knelm.getOwnerScenario());
- context = new ArrayList<SimulationContextFacade>();
- menu = new Menu(getInvolvedSteps());
- selection = menu.getSelection(); // The default selection is set in the menu definition
- int index = Integer.valueOf(selection);
- for (Iterator<Step> i=involving.iterator(); i.hasNext();) {
- Step next = i.next();
- if (next.getNumber() == index) ustep = next;
- for (Iterator<SimulationContext> j=next.getAllSimulationContexts().iterator(); j.hasNext(); ) {
- context.add( new SimulationContextFacade(j.next()) );
- }
- }
- value.append("<p>")
- .append("<b>").append(label.getString("label.source")).append(":</b>")
- .append("<br>").append(label.getString("label.study")).append(" \"").append(scene.getOwnerStudy().getTitle()).append("\",")
- .append("<br>").append(scene.getTitle()).append(".")
- .append("</p>");
- description = value.toString();
- setupContents(); // Initializes documents and knowledge at ustep
- }
-
-// ==============================================================================================================================
-// Public member functions
-// ==============================================================================================================================
-
- public String getAuthorName() {
-// -----------------------------
- return myknelm.getAuthor().toString();
- }
- public String getDate () {
-// ------------------------
- return credate;
- }
- public Integer getIndex() {
-// -------------------------
- return myknelm.getIndex();
- }
- public Menu getMenu () {
-// ----------------------
- return (Menu)menu;
- }
- public ProgressState getProgressState() {
-// ---------------------------------------
- return myknelm.getProgressState();
- }
- public String getReference() {
-// ----------------------------
- return myknelm.getReference();
- }
- public KnowledgeElement getKnowledgeObject () {
-// ---------------------------------------------
- return myknelm;
- }
- public String getTitle() {
-// ------------------------
- return myknelm.getTitle();
- }
- public String getType () {
-// ------------------------
- return ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale()).getString("type.knowledge." + myknelm.getType().getName());
- }
-
- public void setSelection (String step) {
-// --------------------------------------
- selection = step;
- int index = Integer.valueOf(selection);
- for (Iterator<Step> i=involving.iterator(); i.hasNext();) {
- ustep = i.next();
- if (ustep.getNumber() == index) break;
- }
- menu.selects(selection);
- setupContents(); // The contents may have changed even if the selection is the same
- }
-
-// ==============================================================================================================================
-// Private services
-// ==============================================================================================================================
-
- private List<Step> getAllSteps (Scenario scenar) {
-// ------------------------------------------------
- Vector<Step> result = new Vector<Step>();
- Step[] step = scenar.getSteps();
-
- int base = step[0].getNumber();
- int last = step[step.length-1].getNumber();
- for (int i=0; i<step.length; i++) {
- result.add(step[i]);
- }
- step = scenar.getOwnerStudy().getSteps();
- for (int i=step.length-1; i>-1; i--) {
- if(step[i].getNumber() >= base) continue;
- result.add(0, step[i]);
- }
- for (int i=0; i<step.length; i++) {
- if(step[i].getNumber() <= last) continue;
- result.add(step[i]);
- }
- return result;
- }
+ // ------------------------------------
+ public Menu(List<Step> context) {
+ super("steps", "study");
+ int i = 0;
+ int j = 0;
+ for (Iterator<Step> k = context.iterator(); k.hasNext(); i++) {
+ Step step = k.next();
+ int number = step.getNumber();
+ String icon;
+ if (step.mayContain(KnowledgeElement.class))
+ j = i + 1; // Steps are numbered from 1 to N
+ if (!step.isStarted())
+ icon = "icon.empty.png";
+ else
+ icon = "icon.done.png";
+ addItem(String.valueOf(number), "folder.step." + number, icon,
+ "step-knowledge?selection=" + number);
+ }
+ this.selects(String.valueOf(j));
+ }
+ }
+
+ // ==============================================================================================================================
+ // Constructor
+ // ==============================================================================================================================
+
+ public OpenKnowledge(KnowledgeElement knelm) {
+ // ---------------------------------------------
+ ResourceBundle label = ResourceBundle.getBundle("labels",
+ ApplicationSettings.getCurrentLocale());
+ ResourceBundle custom = ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale());
+ SimpleDateFormat convert = new SimpleDateFormat(
+ custom.getString("date.format"));
+ StringBuffer value = new StringBuffer(knelm.getValue());
+ Scenario scene = knelm.getOwnerScenario();
+
+ myknelm = knelm;
+
+ // Preparation of the display
+ credate = convert.format(myknelm.getDate());
+ involving = getAllSteps(knelm.getOwnerScenario());
+ context = new ArrayList<SimulationContextFacade>();
+ menu = new Menu(getInvolvedSteps());
+ selection = menu.getSelection(); // The default selection is set in the menu definition
+ int index = Integer.valueOf(selection);
+ for (Iterator<Step> i = involving.iterator(); i.hasNext();) {
+ Step next = i.next();
+ if (next.getNumber() == index)
+ ustep = next;
+ for (Iterator<SimulationContext> j = next
+ .getAllSimulationContexts().iterator(); j.hasNext();) {
+ context.add(new SimulationContextFacade(j.next()));
+ }
+ }
+ value.append("<p>").append("<b>")
+ .append(label.getString("label.source")).append(":</b>")
+ .append("<br>").append(label.getString("label.study"))
+ .append(" \"").append(scene.getOwnerStudy().getTitle())
+ .append("\",").append("<br>").append(scene.getTitle())
+ .append(".").append("</p>");
+ description = value.toString();
+ setupContents(); // Initializes documents and knowledge at ustep
+ }
+
+ // ==============================================================================================================================
+ // Public member functions
+ // ==============================================================================================================================
+
+ public String getAuthorName() {
+ // -----------------------------
+ return myknelm.getAuthor().toString();
+ }
+
+ public String getDate() {
+ // ------------------------
+ return credate;
+ }
+
+ public Integer getIndex() {
+ // -------------------------
+ return myknelm.getIndex();
+ }
+
+ public Menu getMenu() {
+ // ----------------------
+ return (Menu) menu;
+ }
+
+ public ProgressState getProgressState() {
+ // ---------------------------------------
+ return myknelm.getProgressState();
+ }
+
+ public String getReference() {
+ // ----------------------------
+ return myknelm.getReference();
+ }
+
+ public KnowledgeElement getKnowledgeObject() {
+ // ---------------------------------------------
+ return myknelm;
+ }
+
+ public String getTitle() {
+ // ------------------------
+ return myknelm.getTitle();
+ }
+
+ public String getType() {
+ // ------------------------
+ return ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale()).getString(
+ "type.knowledge." + myknelm.getType().getName());
+ }
+
+ public void setSelection(String step) {
+ // --------------------------------------
+ selection = step;
+ int index = Integer.valueOf(selection);
+ for (Iterator<Step> i = involving.iterator(); i.hasNext();) {
+ ustep = i.next();
+ if (ustep.getNumber() == index)
+ break;
+ }
+ menu.selects(selection);
+ setupContents(); // The contents may have changed even if the selection is the same
+ }
+
+ // ==============================================================================================================================
+ // Private services
+ // ==============================================================================================================================
+
+ private List<Step> getAllSteps(Scenario scenar) {
+ // ------------------------------------------------
+ Vector<Step> result = new Vector<Step>();
+ Step[] step = getProjectElementService().getSteps(scenar);
+
+ int base = step[0].getNumber();
+ int last = step[step.length - 1].getNumber();
+ for (int i = 0; i < step.length; i++) {
+ result.add(step[i]);
+ }
+ step = getProjectElementService().getSteps(scenar.getOwnerStudy());
+ for (int i = step.length - 1; i > -1; i--) {
+ if (step[i].getNumber() >= base)
+ continue;
+ result.add(0, step[i]);
+ }
+ for (int i = 0; i < step.length; i++) {
+ if (step[i].getNumber() <= last)
+ continue;
+ result.add(step[i]);
+ }
+ return result;
+ }
+
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
}
\ No newline at end of file
import java.util.List;
import java.util.Vector;
-import org.splat.kernel.User;
-import org.splat.som.Document;
-import org.splat.som.DocumentType;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.KnowledgeElementType;
-import org.splat.som.ProgressState;
-import org.splat.som.Proxy;
-import org.splat.som.Publication;
-import org.splat.som.Scenario;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.dto.Proxy;
+import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.Scenario;
import org.splat.som.Step;
import org.splat.wapp.Menu;
import org.splat.wapp.PopupMenu;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.kernel.Do;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.manox.Toolbox;
import org.splat.manox.Writer;
-import org.splat.som.Database;
-import org.splat.som.Document;
-import org.splat.som.DocumentType;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Publication;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.ProjectElementService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.Publication;
import org.splat.som.Revision;
-import org.splat.som.Scenario;
-import org.splat.som.SimulationContext;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.SimulationContext;
import org.splat.som.Step;
import org.splat.som.StepRights;
-import org.splat.som.Study;
+import org.splat.dal.bo.som.Study;
import org.splat.som.StudyRights;
import org.splat.wapp.ToolBar;
private String credate;
private String lasdate;
private Publication selecdoc;
+ private ProjectSettingsService _projectSettingsService;
+ private ProjectElementService _projectElementService;
protected final static Logger logger = org.splat.simer.Action.logger;
// -----------------------------------------
ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format"));
- Revision.Format verstring = new Revision.Format(ProjectSettings.getRevisionPattern());
+ Revision.Format verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
cuser = user; // May be null if nobody connected
mystudy = study;
description = mystudy.getDescription();
involving = new ArrayList<Step>(1);
context = new ArrayList<SimulationContextFacade>();
- ustep = mystudy.getFirstStep();
+ ustep = getProjectElementService().getFirstStep(mystudy);
ustep.setActor(cuser);
involving.add(ustep);
for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
protected void add (KnowledgeElement kelm) {
// ------------------------------------------
KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
- KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
+//RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
// Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
- knowpres.put(kelm.getIndex(), facade);
- known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
+ //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
+ KnowledgeIterator known = null;
+ for (KnowledgeIterator aKnowledgeSection : knowledge) {
+ if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
+ known = aKnowledgeSection;
+ break;
+ }
+ }
+ if (known != null) { //RKV:End
+ knowpres.put(kelm.getIndex(), facade);
+ known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
+ }
}
protected void remove (Publication doctag) {
scenar = branch[i];
if (scenar.getIndex() == major) break; // Supposed exist
}
- step = scenar.getSteps();
+ step = getProjectElementService().getSteps(scenar);
base = step[0].getNumber() - 1;
for (int i=0; i+base<minor; i++) {
involving.add(step[i]);
}
}
- step = mystudy.getSteps();
+ step = getProjectElementService().getSteps(mystudy);
for (int i=step.length-1; i>-1; i--) {
Step firstep = step[i];
if(firstep.getNumber() > base) continue;
involving.add(0, firstep);
}
}
+
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
}
\ No newline at end of file
package org.splat.simer;
import java.net.URL;
-import org.splat.kernel.User;
-import org.splat.som.Publication;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.Publication;
public interface OpenStudyServices {
import org.hibernate.Transaction;
import org.splat.kernel.InvalidPropertyException;
import org.splat.kernel.Name;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.kernel.UserDirectory;
import org.splat.som.ApplicationRights;
-import org.splat.som.Database;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Proxy;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
+import org.splat.dal.dao.som.Database;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.dto.Proxy;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
public abstract class SearchBaseAction extends Action {
// Ordering by alphabetical order of localized context types
SimulationContextType[] types = critext.toArray( new SimulationContextType[critext.size()] );
ContextTypeComparator compare = new ContextTypeComparator();
- ProjectSettings.Step step = types[0].getAttachedStep();
+ ProjectSettingsService.Step step = types[0].getAttachedStep();
int from = 0;
int to = 0;
while (to < types.length-1) {
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.kernel.UserDirectory;
-import org.splat.som.Database;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.KnowledgeElementType;
-import org.splat.som.ProgressState;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
-import org.splat.som.Visibility;
+import org.splat.service.SearchService;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Visibility;
public class SearchKnowledgeAction extends SearchBaseAction {
private String refid = null; // Knowledge reference when among ref
private String words = null; // Full text search words
private List<KnowledgeElementType> types; // Available knowledge types filter (initialized below)
+ private SearchService _searchService;
- private static final long serialVersionUID = -3104321907432838476L;
+ private static final long serialVersionUID = -3104321907432838476L;
// ==============================================================================================================================
// Action methods
sprop.setVisibility(Visibility.PRIVATE);
sprop.setActor(user);
- result = Database.selectKnowledgeElementsWhere(sprop, other);
+ result = getSearchService().selectKnowledgeElementsWhere(sprop, other);
}
else {
Visibility reparea = null;
sprop.setVisibility(reparea);
if (reparea == Visibility.PRIVATE) sprop.setActor(user);
- result = Database.selectKnowledgeElementsWhere(sprop);
+ result = getSearchService().selectKnowledgeElementsWhere(sprop);
}
session.put("search.result", result); // For redisplaying the page without re-executing the search
return "refresh";
// Initialization required by all do functions
types = KnowledgeElement.selectTypesWhere(ProgressState.APPROVED);
}
+ /**
+ * Get the searchService.
+ * @return the searchService
+ */
+ public SearchService getSearchService() {
+ return _searchService;
+ }
+
+ /**
+ * Set the searchService.
+ * @param searchService the searchService to set
+ */
+ public void setSearchService(SearchService searchService) {
+ _searchService = searchService;
+ }
}
\ No newline at end of file
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.kernel.UserDirectory;
-import org.splat.som.Database;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
-import org.splat.som.Study;
-import org.splat.som.Visibility;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.SearchService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.Visibility;
public class SearchStudyAction extends SearchBaseAction {
private String matcontext = null; // "all" or "any"
private String refid = null; // Study reference
private String words = null; // Full text search words
+ private SearchService _searchService;
+ private ProjectSettingsService _projectSettingsService;
private static final long serialVersionUID = -1910481357051393077L;
sprop.setVisibility(Visibility.PRIVATE);
sprop.setActor(user);
- result = Database.selectStudiesWhere(sprop, other);
+ result = getSearchService().selectStudiesWhere(sprop, other);
}
else {
Visibility reparea = null;
sprop.setVisibility(reparea);
if (reparea == Visibility.PRIVATE) sprop.setActor(user);
- result = Database.selectStudiesWhere(sprop);
+ result = getSearchService().selectStudiesWhere(sprop);
}
session.put("search.result", result); // For redisplaying the page without re-executing the search
return "refresh";
protected List<SimulationContextType> getInvolvedContexts () {
// ------------------------------------------------------------
- List<ProjectSettings.Step> steps = ProjectSettings.getStepsOf(Study.class);
- ProjectSettings.Step[] number = steps.toArray(new ProjectSettings.Step[steps.size()]);
+ List<ProjectSettingsService.Step> steps = getProjectSettings().getStepsOf(Study.class);
+ ProjectSettingsService.Step[] number = steps.toArray(new ProjectSettingsService.Step[steps.size()]);
return SimulationContext.selectTypesOf(number);
}
context = (List<SimulationContext>)filter.get("context"); // Only criteria not part of the form
}
+ /**
+ * Get the searchService.
+ * @return the searchService
+ */
+ public SearchService getSearchService() {
+ return _searchService;
+ }
+
+ /**
+ * Set the searchService.
+ * @param searchService the searchService to set
+ */
+ public void setSearchService(SearchService searchService) {
+ _searchService = searchService;
+ }
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
}
\ No newline at end of file
import java.util.Iterator;
import java.util.ResourceBundle;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
import org.splat.wapp.PopupMenu;
private int step;
private ProgressState state;
private PopupMenu popup;
+ private ProjectSettingsService _projectSettingsService;
// ==============================================================================================================================
// Constructor
popup = ApplicationSettings.getPopupMenu("scontext");
SimulationContextType type = my.getType();
- for (Iterator<ProjectSettings.Step> i=ProjectSettings.getAllSteps().iterator(); i.hasNext(); ) {
- ProjectSettings.Step next = i.next();
+ for (Iterator<ProjectSettingsService.Step> i=getProjectSettings().getAllSteps().iterator(); i.hasNext(); ) {
+ ProjectSettingsService.Step next = i.next();
if (!type.isAttachedTo(next)) continue;
step = next.getNumber();
break;
// ---------------------------------------------------------
return my.equals(represented);
}
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
}
\ No newline at end of file
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;
-import org.splat.som.Timestamp;
-import org.splat.som.ValidationStep;
+import org.splat.dal.bo.som.Timestamp;
+import org.splat.dal.bo.som.ValidationStep;
public class StampFacade implements HistoryFacade {
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.som.ApplicationRights;
-import org.splat.som.Database;
-import org.splat.som.ProjectSettings;
+import org.splat.dal.dao.som.Database;
+import org.splat.service.technical.ProjectSettingsService;
public class StartAction extends Action implements ServletRequestAware {
private HttpServletRequest request = null;
+
+ private ProjectSettingsService _projectSettingsService;
+ private ApplicationSettings _ApplicationSettings;
private static final long serialVersionUID = 5875058140682652964L;
logger.info( new StringBuffer("Initializing ").append(wappurl).append("...").toString() );
try {
- ProjectSettings project = ProjectSettings.getMe();
- ApplicationSettings wapp = new ApplicationSettings(wappurl.toString(), this.getLocale());
+ ProjectSettingsService project = getProjectSettings();
+ ApplicationSettings wapp = getApplicationSettings().init(wappurl.toString(), this.getLocale());
String root = wapp.getApplicationRootPath();
// Database configuration
// ----------------------------------------------------------
this.request = request;
}
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+ /**
+ * Get the applicationSettings.
+ * @return the applicationSettings
+ */
+ public ApplicationSettings getApplicationSettings() {
+ return _ApplicationSettings;
+ }
+
+ /**
+ * Set the applicationSettings.
+ * @param applicationSettings the applicationSettings to set
+ */
+ public void setApplicationSettings(ApplicationSettings applicationSettings) {
+ _ApplicationSettings = applicationSettings;
+ }
}
\ No newline at end of file
import java.util.Iterator;
import java.util.Vector;
-import org.splat.som.ProjectElement;
-import org.splat.som.Scenario;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.service.ProjectElementService;
+import org.splat.service.ScenarioService;
import org.splat.som.Step;
-import org.splat.som.Study;
+import org.splat.dal.bo.som.Study;
import org.splat.wapp.MenuItem;
import org.splat.wapp.SlidMenu;
private Study study;
private Scenario scopen; // Currently "open" scenario
private Step stopen; // Currently selected step
+ private ScenarioService _scenarioService;
+ private ProjectElementService _projectElementService;
// ==============================================================================================================================
// Constructor
// Study with several scenarii, non of them open
// Collection of steps to be displayed
Vector<Step> steps = new Vector<Step>();
- Step[] newstep = scenes[0].getSteps(); // All scenarii have the same steps
+ Step[] newstep = getProjectElementService().getSteps(scenes[0]); // All scenarii have the same steps
int base = newstep[0].getNumber();
int last = newstep[newstep.length-1].getNumber();
- for (int i=0; i<scenes.length; i++) steps.add(scenes[i].getFirstStep());
+ for (int i=0; i<scenes.length; i++) steps.add(getProjectElementService().getFirstStep(scenes[i]));
- newstep = study.getSteps();
+ newstep = getProjectElementService().getSteps(study);
stopen = newstep[0]; // Default selected step
for (int i=newstep.length-1; i>-1; i--) {
if(newstep[i].getNumber() >= base) continue;
int index = group.getIndex();
String value = index + "." + number;
if (group.isCheckedout()) icon = "icon.checkedout.png";
- else if (group.isEmpty()) icon = "icon.empty.png";
+ else if (getScenarioService().isEmpty(group)) icon = "icon.empty.png";
// else if (group.isFinished()) icon = "icon.checked.png";
else icon = "icon.done.png";
addGroup(value, group.getTitle(), icon, "step-study?selection=" + value);
this.clear();
// Collection of steps to be displayed
Vector<Step> steps = new Vector<Step>();
- Step[] newstep = scenew.getSteps();
+ Step[] newstep = getProjectElementService().getSteps(scenew);
int base = newstep[0].getNumber();
int last = newstep[newstep.length-1].getNumber();
for (int i=0; i<newstep.length; i++) {
steps.add(newstep[i]);
}
- for (int i=askid-1; i>-1; i--) steps.add(0, scenes[i].getFirstStep());
- newstep = study.getSteps();
+ for (int i=askid-1; i>-1; i--) steps.add(0, getProjectElementService().getFirstStep(scenes[i]));
+ newstep = getProjectElementService().getSteps(study);
for (int i=newstep.length-1; i>-1; i--) {
if(newstep[i].getNumber() >= base) continue;
steps.add(0, newstep[i]);
}
- for (int i=askid+1; i<scenes.length; i++) steps.add(scenes[i].getFirstStep());
+ for (int i=askid+1; i<scenes.length; i++) steps.add(getProjectElementService().getFirstStep(scenes[i]));
for (int i=0; i<newstep.length; i++) {
if(newstep[i].getNumber() <= last) continue;
steps.add(newstep[i]);
String value = index + "." + number;
if (index != scenew.getIndex()) {
if (group.isCheckedout()) icon = "icon.checkedout.png";
- else if (group.isEmpty()) icon = "icon.empty.png";
+ else if (getScenarioService().isEmpty(group)) icon = "icon.empty.png";
// else if (group.isFinished()) icon = "icon.checked.png";
else icon = "icon.done.png";
addGroup(value, group.getTitle(), icon, "step-study?selection=" + value);
scopen = scenew;
}
else {
- Step[] step = scopen.getSteps();
+ Step[] step = getProjectElementService().getSteps(scopen);
int selected = Integer.valueOf(parse[1]);
for (int i=0; i<step.length; i++) {
if (step[i].getNumber() != selected) continue;
else icon = "icon.done.png";
item.icon(icon);
}
+ /**
+ * Get the scenarioService.
+ *
+ * @return the scenarioService
+ */
+ public ScenarioService getScenarioService() {
+ return _scenarioService;
+ }
+
+ /**
+ * Set the scenarioService.
+ *
+ * @param scenarioService
+ * the scenarioService to set
+ */
+ public void setScenarioService(ScenarioService scenarioService) {
+ _scenarioService = scenarioService;
+ }
+
+ /**
+ * Get the projectElementService.
+ *
+ * @return the projectElementService
+ */
+ public ProjectElementService getProjectElementService() {
+ return _projectElementService;
+ }
+
+ /**
+ * Set the projectElementService.
+ *
+ * @param projectElementService
+ * the projectElementService to set
+ */
+ public void setProjectElementService(
+ ProjectElementService projectElementService) {
+ _projectElementService = projectElementService;
+ }
}
\ No newline at end of file
import org.hibernate.Transaction;
import org.splat.kernel.InvalidPropertyException;
import org.splat.kernel.Name;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.kernel.UserDirectory;
+import org.splat.service.StudyService;
import org.splat.som.ApplicationRights;
-import org.splat.som.Database;
-import org.splat.som.Document;
-import org.splat.som.DocumentType;
-import org.splat.som.Study;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.Study;
import org.splat.som.StudyRights;
-import org.splat.som.ValidationCycle;
-import org.splat.som.ValidationStep;
+import org.splat.dal.bo.som.ValidationCycle;
+import org.splat.dal.bo.som.ValidationStep;
public class StudyPropertiesAction extends DisplayStudyStepAction {
private int publisher;
private int reviewer;
private int approver;
+ private StudyService _studyService;
private static final long serialVersionUID = 4210696018741092900L;
// Edition of the title
Study.Properties sprop = new Study.Properties();
try {
- study.update(sprop.setTitle(stitle));
+ getStudyService().update(study, sprop.setTitle(stitle));
}
catch (InvalidPropertyException e) {
//TODO
}
}
int size = toremove.size();
- if (size > 0) study.removeContributor(toremove.toArray(new User[size]));
+ if (size > 0) getStudyService().removeContributor(study, toremove.toArray(new User[size]));
for (int i=0; i<parsenew.length; i++) {
if (parsenew[i].length() == 0) continue; // No any new contributor
int index = Integer.valueOf(parsenew[i].trim());
User newser = UserDirectory.selectUser(index);
- study.addContributor(newser);
+ getStudyService().addContributor(study, newser);
}
} else
if (tosave == Save.cycle) {
User actor = UserDirectory.selectUser(approver);
vprop.setActor(ValidationStep.APPROVAL, actor);
}
- study.setValidationCycle(apply, vprop);
+ getStudyService().setValidationCycle(study, apply, vprop);
}
transax.commit();
// --------------------------------------
tosave = Save.cycle;
}
+ /**
+ * Get the studyService.
+ *
+ * @return the studyService
+ */
+ public StudyService getStudyService() {
+ return _studyService;
+ }
+
+ /**
+ * Set the studyService.
+ *
+ * @param studyService
+ * the studyService to set
+ */
+ public void setStudyService(StudyService studyService) {
+ _studyService = studyService;
+ }
}
\ No newline at end of file
import java.io.File;
import org.splat.kernel.Do;
-import org.splat.som.Database;
+import org.splat.dal.dao.som.Database;
public class UploadAction extends Action {
import java.util.List;
import java.util.Set;
-import org.splat.som.Document;
-import org.splat.som.DocumentType;
-import org.splat.som.ProgressState;
-import org.splat.som.Publication;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Publication;
import org.splat.som.Step;
import java.util.ResourceBundle;
import org.splat.kernel.Name;
-import org.splat.kernel.User;
-import org.splat.som.ValidationCycle;
-import org.splat.som.ValidationStep;
+import org.splat.dal.bo.kernel.User;
+import org.splat.dal.bo.som.ValidationCycle;
+import org.splat.dal.bo.som.ValidationStep;
public class ValidationFacade {
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.splat.kernel.InvalidPropertyException;
-import org.splat.kernel.Relation;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.Relation;
+import org.splat.dal.bo.kernel.User;
import org.splat.manox.Reader;
import org.splat.manox.Toolbox;
-import org.splat.som.Database;
-import org.splat.som.Document;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Publication;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.PublicationService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.Publication;
import org.splat.som.Revision;
import org.splat.som.Step;
-import org.splat.som.UsedByRelation;
-import org.splat.som.UsesRelation;
-
+import org.splat.dal.bo.som.UsedByRelation;
+import org.splat.dal.bo.som.UsesRelation;
public class VersionDocumentAction extends UploadBaseNextAction {
- private String index = null; // Versioned document index
- private List<Publication> usedby = null;
- private String docusedby = null;
- private String summary = null; // Summary of changes in the new version
- private String docver = ""; // Version number extracted from the imported file, if exist
- private String date = ""; // Date extracted from the imported file, if exist
-
- private static final long serialVersionUID = -5702264003232132168L;
-
-// ==============================================================================================================================
-// Action methods
-// ==============================================================================================================================
-
- public String doInitialize () {
-// -----------------------------
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- User user = getConnectedUser();
- File updir = Database.getDownloadDirectory(user);
- File upfile = new File(updir.getPath() + "/" + filename);
-
- mystudy = getOpenStudy();
-
- Publication tag = mystudy.getSelectedStep().getDocument(Integer.valueOf(index));
- Document doc = tag.value();
- deftype = doc.getType();
- docname = doc.getTitle();
- defuses = new Vector<Document>();
- usedby = new Vector<Publication>();
-
- Reader tool = Toolbox.getReader(upfile);
- if (tool != null) {
- String fileref = tool.extractProperty("reference");
- String filever = tool.extractProperty("version");
- if (fileref != null && !doc.getReference().equals(fileref)) {
- setErrorCode("reference.mismatch");
- return ERROR;
- }
- if (filever != null) try {
- Revision.Format get = new Revision.Format(ProjectSettings.getRevisionPattern());
- Revision newver = get.parse(filever);
- Revision oldver = new Revision(doc.getVersion());
- if (!newver.isGraterThan(oldver)) throw new InvalidPropertyException("version");
- if ( newver.isMinor() ) state = ProgressState.inWORK;
- else state = ProgressState.inDRAFT;
- docver = newver.toString();
- } catch (Exception e) {
- setErrorCode("version.mismatch");
- return ERROR;
- }
- summary = tool.extractProperty("history");
- date = tool.extractProperty("date");
- if (date != null) {
- ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
- SimpleDateFormat check = new SimpleDateFormat(locale.getString("date.format"));
- try {
- check.parse(date);
- } catch (ParseException e) {
- setErrorCode("format.date");
- return ERROR;
- }
- } else date = "";
- }
- setupDefaultUses(deftype);
-// Add additional documents used by the current version
- List<Relation> uses = doc.getRelations(UsesRelation.class);
- for (Iterator<Relation> i=uses.iterator(); i.hasNext();) {
- Document used = (Document)i.next().getTo();
- if (!defuses.contains(used)) defuses.add(used);
- }
-// Setup dependencies
- List<Publication> relist = tag.getRelations(UsedByRelation.class);
- for (Iterator<Publication> i=relist.iterator(); i.hasNext();) {
- usedby.add(i.next());
- }
- transax.commit();
- return SUCCESS;
- }
-
- public String doVersion () {
-// -------------------------
- if (action == ToDo.cancel) return "cancel";
-
- Session connex = Database.getSession();
- Transaction transax = connex.beginTransaction();
- try {
-// Getting user inputs
- mystudy = getOpenStudy();
- User user = getConnectedUser();
- Step step = mystudy.getSelectedStep();
- File updir = Database.getDownloadDirectory(user);
- File upfile = new File(updir.getPath() + "/" + filename);
-
-// Versioning of the document
- Document.Properties dprop = new Document.Properties();
- Publication current = step.getDocument(Integer.valueOf(index));
- Publication next;
-
- if (docver.length() == 0) { // Importation of a foreign document
- next = step.versionDocument(current, dprop.setAuthor(user).setDescription(summary));
- updir = next.getSourceFile().asFile();
- if (logger.isInfoEnabled()) logger.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\".");
- upfile.renameTo(updir);
- try {
- next.saveAs(state); // May throw FileNotFound if rename was not done
- } catch (FileNotFoundException saverror) {
- Thread.sleep(1000);
- logger.info("Waiting for the file.");
- upfile.renameTo(updir);
- next.saveAs(state); // Forget it if throw again FileNotFound
- }
- } else {
- if (date.length() > 0) {
- ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
- SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
- dprop.setDate(get.parse(date));
- }
- next = step.versionDocument(current, dprop.setAuthor(user).setDescription(summary));
- updir = next.getSourceFile().asFile();
- if (logger.isInfoEnabled()) logger.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\".");
- upfile.renameTo(updir);
- try {
- next.saveAs(new Revision(docver));
- } catch (FileNotFoundException saverror) {
- Thread.sleep(1000);
- logger.info("Waiting for the file.");
- upfile.renameTo(updir);
- next.saveAs(state);
- }
- }
-//TODO: Remove current document details from the contents of open study
-
-// Creation of uses relations
- if (docuses != null) {
- String[] list = docuses.split(",");
- for (int i=0; i<list.length; i++) {
- Integer index = Integer.valueOf(list[i].trim());
- Publication used = getPublication(index);
- next.addDependency(used);
- }
- }
-// Outdating impacted document
- HashSet<Integer> compatible = new HashSet<Integer>();
- if (docusedby != null) {
- String[] list = docusedby.split(",");
- for (int i=0; i<list.length; i++) compatible.add(Integer.valueOf(list[i].trim()));
- }
- List<Publication> relist = current.getRelations(UsedByRelation.class);
- for (Iterator<Publication> i=relist.iterator(); i.hasNext();) {
- Publication using = i.next();
- if (!compatible.contains(using.getIndex())) using.outdate();
- }
-// Update of the open study
- mystudy.setSelection(mystudy.getSelection()); // Rebuilds the presentation
-//TODO: Look is an optimization is possible (for example by updating the presentation of versioned document)
-
- transax.commit();
- return SUCCESS;
- }
- catch (FileNotFoundException error) {
- logger.error("Reason:", error);
- setErrorCode("import.file");
- }
- catch (Exception error) {
- logger.error("Reason:", error);
- setErrorCode("internal");
- }
- if (transax != null && transax.isActive()) {
-// Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- logger.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
-// ==============================================================================================================================
-// Getters and setters
-// ==============================================================================================================================
-
- public String getDate () {
-// ------------------------
- return date;
- }
- public List<Publication> getDependencies () {
-// -------------------------------------------
- return usedby;
- }
- public String getDescription () {
-// -------------------------------
- return summary;
- }
- public String getIndex () {
-// -------------------------
- return index;
- }
- public String getVersion () {
-// ---------------------------
- return docver;
- }
-
- public void setDate (String date) {
-// ---------------------------------
- this.date = date;
- }
- public void setDefaultDescription (String summary) {
-// --------------------------------------------------
- if (this.summary == null) this.summary = summary;
- }
- public void setDescription (String summary) {
-// -------------------------------------------
- this.summary = summary;
- }
- public void setIndex (String index) {
-// -----------------------------------
- this.index = index;
- }
- public void setUsedBy (String list) {
-// -----------------------------------
- this.docusedby = list;
- }
- public void setVersion (String value) {
-// -------------------------------------
- this.docver = value;
- }
+ private String index = null; // Versioned document index
+ private List<Publication> usedby = null;
+ private String docusedby = null;
+ private String summary = null; // Summary of changes in the new version
+ private String docver = ""; // Version number extracted from the imported file, if exist
+ private String date = ""; // Date extracted from the imported file, if exist
+ private ProjectSettingsService _projectSettingsService;
+ private PublicationService _publicationService;
+
+ private static final long serialVersionUID = -5702264003232132168L;
+
+ // ==============================================================================================================================
+ // Action methods
+ // ==============================================================================================================================
+
+ public String doInitialize() {
+ // -----------------------------
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ User user = getConnectedUser();
+ File updir = Database.getDownloadDirectory(user);
+ File upfile = new File(updir.getPath() + "/" + filename);
+
+ mystudy = getOpenStudy();
+
+ Publication tag = mystudy.getSelectedStep().getDocument(
+ Integer.valueOf(index));
+ Document doc = tag.value();
+ deftype = doc.getType();
+ docname = doc.getTitle();
+ defuses = new Vector<Document>();
+ usedby = new Vector<Publication>();
+
+ Reader tool = Toolbox.getReader(upfile);
+ if (tool != null) {
+ String fileref = tool.extractProperty("reference");
+ String filever = tool.extractProperty("version");
+ if (fileref != null && !doc.getReference().equals(fileref)) {
+ setErrorCode("reference.mismatch");
+ return ERROR;
+ }
+ if (filever != null)
+ try {
+ Revision.Format get = new Revision.Format(
+ getProjectSettings().getRevisionPattern());
+ Revision newver = get.parse(filever);
+ Revision oldver = new Revision(doc.getVersion());
+ if (!newver.isGraterThan(oldver))
+ throw new InvalidPropertyException("version");
+ if (newver.isMinor())
+ state = ProgressState.inWORK;
+ else
+ state = ProgressState.inDRAFT;
+ docver = newver.toString();
+ } catch (Exception e) {
+ setErrorCode("version.mismatch");
+ return ERROR;
+ }
+ summary = tool.extractProperty("history");
+ date = tool.extractProperty("date");
+ if (date != null) {
+ ResourceBundle locale = ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale());
+ SimpleDateFormat check = new SimpleDateFormat(
+ locale.getString("date.format"));
+ try {
+ check.parse(date);
+ } catch (ParseException e) {
+ setErrorCode("format.date");
+ return ERROR;
+ }
+ } else
+ date = "";
+ }
+ setupDefaultUses(deftype);
+ // Add additional documents used by the current version
+ List<Relation> uses = doc.getRelations(UsesRelation.class);
+ for (Iterator<Relation> i = uses.iterator(); i.hasNext();) {
+ Document used = (Document) i.next().getTo();
+ if (!defuses.contains(used))
+ defuses.add(used);
+ }
+ // Setup dependencies
+ List<Publication> relist = tag.getRelations(UsedByRelation.class);
+ for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
+ usedby.add(i.next());
+ }
+ transax.commit();
+ return SUCCESS;
+ }
+
+ public String doVersion() {
+ // -------------------------
+ if (action == ToDo.cancel)
+ return "cancel";
+
+ Session connex = Database.getSession();
+ Transaction transax = connex.beginTransaction();
+ try {
+ // Getting user inputs
+ mystudy = getOpenStudy();
+ User user = getConnectedUser();
+ Step step = mystudy.getSelectedStep();
+ File updir = Database.getDownloadDirectory(user);
+ File upfile = new File(updir.getPath() + "/" + filename);
+
+ // Versioning of the document
+ Document.Properties dprop = new Document.Properties();
+ Publication current = step.getDocument(Integer.valueOf(index));
+ Publication next;
+
+ if (docver.length() == 0) { // Importation of a foreign document
+ next = step.versionDocument(current, dprop.setAuthor(user)
+ .setDescription(summary));
+ updir = next.getSourceFile().asFile();
+ if (logger.isInfoEnabled())
+ logger.info("Moving \"" + upfile.getName() + "\" to \""
+ + updir.getPath() + "\".");
+ upfile.renameTo(updir);
+ try {
+ getPublicationService().saveAs(next, state); // May throw FileNotFound if rename was not done
+ } catch (FileNotFoundException saverror) {
+ Thread.sleep(1000);
+ logger.info("Waiting for the file.");
+ upfile.renameTo(updir);
+ getPublicationService().saveAs(next, state); // Forget it if throw again FileNotFound
+ }
+ } else {
+ if (date.length() > 0) {
+ ResourceBundle locale = ResourceBundle.getBundle("som",
+ ApplicationSettings.getCurrentLocale());
+ SimpleDateFormat get = new SimpleDateFormat(
+ locale.getString("date.format"));
+ dprop.setDate(get.parse(date));
+ }
+ next = step.versionDocument(current, dprop.setAuthor(user)
+ .setDescription(summary));
+ updir = next.getSourceFile().asFile();
+ if (logger.isInfoEnabled())
+ logger.info("Moving \"" + upfile.getName() + "\" to \""
+ + updir.getPath() + "\".");
+ upfile.renameTo(updir);
+ try {
+ getPublicationService().saveAs(next, new Revision(docver));
+ } catch (FileNotFoundException saverror) {
+ Thread.sleep(1000);
+ logger.info("Waiting for the file.");
+ upfile.renameTo(updir);
+ getPublicationService().saveAs(next, state);
+ }
+ }
+ // TODO: Remove current document details from the contents of open study
+
+ // Creation of uses relations
+ if (docuses != null) {
+ String[] list = docuses.split(",");
+ for (int i = 0; i < list.length; i++) {
+ Integer index = Integer.valueOf(list[i].trim());
+ Publication used = getPublication(index);
+ next.addDependency(used);
+ }
+ }
+ // Outdating impacted document
+ HashSet<Integer> compatible = new HashSet<Integer>();
+ if (docusedby != null) {
+ String[] list = docusedby.split(",");
+ for (int i = 0; i < list.length; i++)
+ compatible.add(Integer.valueOf(list[i].trim()));
+ }
+ List<Publication> relist = current
+ .getRelations(UsedByRelation.class);
+ for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
+ Publication using = i.next();
+ if (!compatible.contains(using.getIndex()))
+ using.outdate();
+ }
+ // Update of the open study
+ mystudy.setSelection(mystudy.getSelection()); // Rebuilds the presentation
+ // TODO: Look is an optimization is possible (for example by updating the presentation of versioned document)
+
+ transax.commit();
+ return SUCCESS;
+ } catch (FileNotFoundException error) {
+ logger.error("Reason:", error);
+ setErrorCode("import.file");
+ } catch (Exception error) {
+ logger.error("Reason:", error);
+ setErrorCode("internal");
+ }
+ if (transax != null && transax.isActive()) {
+ // Second try-catch as the rollback could fail as well
+ try {
+ transax.rollback();
+ } catch (HibernateException backerror) {
+ logger.debug("Error rolling back transaction", backerror);
+ }
+ }
+ return ERROR;
+ }
+
+ // ==============================================================================================================================
+ // Getters and setters
+ // ==============================================================================================================================
+
+ public String getDate() {
+ // ------------------------
+ return date;
+ }
+
+ public List<Publication> getDependencies() {
+ // -------------------------------------------
+ return usedby;
+ }
+
+ public String getDescription() {
+ // -------------------------------
+ return summary;
+ }
+
+ public String getIndex() {
+ // -------------------------
+ return index;
+ }
+
+ public String getVersion() {
+ // ---------------------------
+ return docver;
+ }
+
+ public void setDate(String date) {
+ // ---------------------------------
+ this.date = date;
+ }
+
+ public void setDefaultDescription(String summary) {
+ // --------------------------------------------------
+ if (this.summary == null)
+ this.summary = summary;
+ }
+
+ public void setDescription(String summary) {
+ // -------------------------------------------
+ this.summary = summary;
+ }
+
+ public void setIndex(String index) {
+ // -----------------------------------
+ this.index = index;
+ }
+
+ public void setUsedBy(String list) {
+ // -----------------------------------
+ this.docusedby = list;
+ }
+
+ public void setVersion(String value) {
+ // -------------------------------------
+ this.docver = value;
+ }
+
+ /**
+ * Get project settings.
+ *
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ *
+ * @param projectSettingsService
+ * project settings service
+ */
+ public void setProjectSettings(ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+ /**
+ * Get the publicationService.
+ *
+ * @return the publicationService
+ */
+ public PublicationService getPublicationService() {
+ return _publicationService;
+ }
+
+ /**
+ * Set the publicationService.
+ *
+ * @param publicationService
+ * the publicationService to set
+ */
+ public void setPublicationService(PublicationService publicationService) {
+ _publicationService = publicationService;
+ }
}
\ No newline at end of file
import org.hibernate.Session;
import org.hibernate.Transaction;
+import org.splat.service.SearchService;
+import org.splat.service.SearchServiceImpl;
import org.splat.simer.Action;
-import org.splat.som.Database;
-import org.splat.som.Study;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Study;
public class DatabaseIndexingAction extends Action {
private List<ImportedStudy> newstudies;
private String indices;
+ private SearchService _searchService;
+ private ImportedStudy _importedStudy;
private static final long serialVersionUID = 4194268823457749655L;
Session connex = Database.getSession();
Transaction transax = connex.beginTransaction();
- newstudies = ImportedStudy.selectAll();
+ newstudies = getImportedStudy().selectAll();
indices = "";
transax.commit();
for (int i=0; i<ridlist.length; i++) {
int index = Integer.valueOf(ridlist[i].trim());
Study study = Database.selectStudy(index);
- Database.indexStudy(study);
+ getSearchService().indexStudy(study);
}
filter.put("owner", "all"); // Just in case of 1st study search
// ---------------------------------------
this.indices = indices;
}
+
+ /**
+ * Get the searchService.
+ * @return the searchService
+ */
+ public SearchService getSearchService() {
+ return _searchService;
+ }
+
+ /**
+ * Set the searchService.
+ * @param searchService the searchService to set
+ */
+ public void setSearchService(SearchService searchService) {
+ _searchService = searchService;
+ }
+
+ /**
+ * Get the importedStudy.
+ * @return the importedStudy
+ */
+ public ImportedStudy getImportedStudy() {
+ return _importedStudy;
+ }
+
+ /**
+ * Set the importedStudy.
+ * @param importedStudy the importedStudy to set
+ */
+ public void setImportedStudy(ImportedStudy importedStudy) {
+ _importedStudy = importedStudy;
+ }
}
\ No newline at end of file
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.splat.kernel.User;
+import org.splat.dal.bo.kernel.User;
import org.splat.kernel.UserDirectory;
import org.splat.simer.UploadBaseNextAction;
-import org.splat.som.Database;
+import org.splat.dal.dao.som.Database;
public class ImportUserAction extends UploadBaseNextAction {
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
-import org.splat.som.Database;
-import org.splat.som.Study;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.Study;
+import org.splat.service.SearchService;
public class ImportedStudy {
- private int rid;
+ private SearchService _searchService;
+ private int rid;
private String sid;
private String title;
- protected static class SelectStudies implements Work {
+ protected class SelectStudies implements Work {
// ----------------------------------------------------
private List<ImportedStudy> table = new ArrayList<ImportedStudy>();
+ protected SelectStudies(SearchService searchService) {
+ }
+
public void execute (Connection connex) throws SQLException
{
Statement request = connex.createStatement();
String title = result.getString("title");
try {
sprop.clear();
- if (Database.selectStudiesWhere(sprop.setReference(sid)).size() != 0) continue;
+ if (getSearchService().selectStudiesWhere(sprop.setReference(sid)).size() != 0) continue;
} catch (Exception error) {
continue;
}
table.add( new ImportedStudy(rid, sid, title) );
}
}
+
public List<ImportedStudy> getResult ()
{
return table;
// Constructor
// ==============================================================================================================================
- public ImportedStudy (int rid, String sid, String title) {
-// --------------------------------------------------------
- this.rid = rid;
- this.sid = sid;
- this.title = title;
+ public ImportedStudy () {
}
+ public ImportedStudy (int rid, String sid, String title) {
+ // --------------------------------------------------------
+ this.rid = rid;
+ this.sid = sid;
+ this.title = title;
+ }
+
// ==============================================================================================================================
// Public member functions
// ==============================================================================================================================
// Public services
// ==============================================================================================================================
- public static List<ImportedStudy> selectAll () {
+ public List<ImportedStudy> selectAll () {
// ----------------------------------------------
Session session = Database.getSession();
- SelectStudies query = new SelectStudies();
+ SelectStudies query = new SelectStudies(getSearchService());
session.doWork(query);
return query.getResult();
}
+
+ public org.splat.service.SearchService getSearchService() {
+ return _searchService;
+ }
+
+ public void setSearchService(SearchService searchService) {
+ _searchService = searchService;
+ }
}
\ No newline at end of file
package org.splat.simer.admin;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Scenario;
-import org.splat.som.Study;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.dal.bo.som.Scenario;
+import org.splat.dal.bo.som.Study;
public class ProjectElementFacade {
// Constructor
// ==============================================================================================================================
- public ProjectElementFacade (Study represented, ProjectSettings.Step at) {
+ public ProjectElementFacade (Study represented, ProjectSettingsService.Step at) {
// ------------------------------------------------------------------------
index = represented.getIndex(); // The index of scenarios AND studies are unique
my = represented;
subtitle = "";
step = "0." + at.getNumber();
}
- public ProjectElementFacade (Scenario represented, ProjectSettings.Step at) {
+ public ProjectElementFacade (Scenario represented, ProjectSettingsService.Step at) {
// ---------------------------------------------------------------------------
index = represented.getIndex(); // The index of scenarios AND studies are unique
my = represented.getOwnerStudy();
import org.splat.simer.Action;
import org.splat.simer.ApplicationSettings;
-import org.splat.som.Database;
-import org.splat.som.KnowledgeElement;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.Proxy;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
-import org.splat.som.Study;
+import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.KnowledgeElement;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.service.SearchService;
+import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.dto.Proxy;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
+import org.splat.dal.bo.som.Study;
public class SimulationContextAction extends Action {
private List<SimulationContextFacade> tocheck; // Simulation contexts to be approved
private int selection; // Index of the selected simulation context presented in the approval form
private SimulationContext edition; // Corresponding simulation context object
- private ProjectSettings.Step step; // Study step to which the selected simulation context is attached
+ private ProjectSettingsService.Step step; // Study step to which the selected simulation context is attached
private Set<ProjectElementFacade> owner; // Study scenarios indexed by this simulation context
private List<LocalizedContextTypes> existype; // Existing approved simulation context types ordered by localized names
private List<SimulationContextType> exisname; // Existing approved simulation context types ordered by internal codes
private List<SimulationContext> existing; // Existing simulation contexts of selected type
+ private SearchService _searchService;
+ private ProjectSettingsService _projectSettingsService;
private static final long serialVersionUID = 7083323229359094699L;
tocheck.add( new SimulationContextFacade(next) );
}
KnowledgeElement.Properties kprop = new KnowledgeElement.Properties();
- List<Proxy> kelm = Database.selectKnowledgeElementsWhere(kprop.setSimulationContexts(selected).setState(ProgressState.inWORK));
+ List<Proxy> kelm = getSearchService().selectKnowledgeElementsWhere(kprop.setSimulationContexts(selected).setState(ProgressState.inWORK));
step = edition.getType().getAttachedStep();
owner = new HashSet<ProjectElementFacade>();
// Getters and setters
// ==============================================================================================================================
- public List<ProjectSettings.Step> getAllStudySteps () {
+ /**
+ * @return
+ */
+ public SearchService getSearchService() {
+ // TODO Auto-generated method stub
+ return _searchService;
+ }
+
+ public void setSearchService(SearchService searchService) {
+ _searchService = searchService;
+ }
+
+ public List<ProjectSettingsService.Step> getAllStudySteps () {
// -----------------------------------------------------
- return ProjectSettings.getAllSteps();
+ return getProjectSettings().getAllSteps();
}
- public ProjectSettings.Step getAttachedStep () {
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
+
+ public ProjectSettingsService.Step getAttachedStep () {
// ----------------------------------------------
return step;
}
import java.util.List;
import java.util.ResourceBundle;
+import org.splat.service.technical.ProjectSettingsService;
import org.splat.simer.ApplicationSettings;
-import org.splat.som.ProgressState;
-import org.splat.som.ProjectSettings;
-import org.splat.som.SimulationContext;
-import org.splat.som.SimulationContextType;
+import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.SimulationContext;
+import org.splat.dal.bo.som.SimulationContextType;
public class SimulationContextFacade {
private String name;
private int at;
private ProgressState state;
+ private ProjectSettingsService _projectSettingsService;
// ==============================================================================================================================
// Constructor
public SimulationContextFacade (SimulationContext represented) {
// --------------------------------------------------------------
- List<ProjectSettings.Step> steps = ProjectSettings.getAllSteps();
+ List<ProjectSettingsService.Step> steps = getProjectSettings().getAllSteps();
SimulationContextType mytype;
my = represented;
mytype = my.getType();
- for (Iterator<ProjectSettings.Step> i=steps.iterator(); i.hasNext(); ) {
- ProjectSettings.Step step = i.next();
+ for (Iterator<ProjectSettingsService.Step> i=steps.iterator(); i.hasNext(); ) {
+ ProjectSettingsService.Step step = i.next();
if (!mytype.isAttachedTo(step)) continue;
at = step.getNumber(); // There is no direct service for getting the step number
break;
// -------------------------
return my.getValue();
}
+ /**
+ * Get project settings.
+ * @return Project settings service
+ */
+ private ProjectSettingsService getProjectSettings() {
+ return _projectSettingsService;
+ }
+
+ /**
+ * Set project settings service.
+ * @param projectSettingsService project settings service
+ */
+ public void setProjectSettings(
+ ProjectSettingsService projectSettingsService) {
+ _projectSettingsService = projectSettingsService;
+ }
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+
+ <bean id="applicationSettings"
+ class="org.splat.simer.ApplicationSettings">
+ <property name="projectSettings" ref="projectSettings" />
+ </bean>
+
+ <bean id="importedStudy" class="org.splat.simer.admin.ImportedStudy"
+ scope="prototype" />
+
+ <bean id="startAction" class="org.splat.simer.StartAction"
+ scope="prototype">
+ <property name="applicationSettings" ref="applicationSettings" />
+ <property name="projectSettings" ref="projectSettings" />
+ </bean>
+ <bean id="connectionAction" class="org.splat.simer.ConnectionAction"
+ scope="prototype">
+ </bean>
+
+ <bean id="menuAction" class="org.splat.simer.MenuAction"
+ scope="prototype">
+ </bean>
+
+ <bean id="notYetImplementedAction"
+ class="org.splat.simer.NotYetImplementedAction" scope="prototype">
+ </bean>
+
+ <bean id="searchStudyAction"
+ class="org.splat.simer.SearchStudyAction" scope="prototype">
+ <property name="projectSettings" ref="projectSettings" />
+ <property name="searchService" ref="searchService" />
+ </bean>
+
+ <bean id="searchKnowledgeAction"
+ class="org.splat.simer.SearchKnowledgeAction" scope="prototype">
+ <property name="searchService" ref="searchService" />
+ </bean>
+
+ <bean id="searchDocumentAction"
+ class="org.splat.simer.SearchDocumentAction" scope="prototype">
+ </bean>
+
+ <bean id="displayStudyStepAction"
+ class="org.splat.simer.DisplayStudyStepAction" scope="prototype">
+ </bean>
+
+ <bean id="studyPropertiesAction"
+ class="org.splat.simer.StudyPropertiesAction" scope="prototype">
+ <property name="studyService" ref="studyService" />
+ </bean>
+
+ <bean id="displayKnowledgeAction"
+ class="org.splat.simer.DisplayKnowledgeAction" scope="prototype">
+ </bean>
+
+ <bean id="editStudyAction" class="org.splat.simer.EditStudyAction"
+ scope="prototype">
+ <property name="studyService" ref="studyService" />
+ </bean>
+
+ <bean id="newScenarioAction"
+ class="org.splat.simer.NewScenarioAction" scope="prototype">
+ <property name="projectElementService"
+ ref="projectElementService" />
+ <property name="studyService" ref="studyService" />
+ </bean>
+
+ <bean id="editScenarioPropertiesAction"
+ class="org.splat.simer.EditScenarioPropertiesAction"
+ scope="prototype">
+ <property name="projectElementService"
+ ref="projectElementService" />
+ <property name="scenarioService" ref="scenarioService" />
+ </bean>
+
+ <bean id="editSimulationContextAction"
+ class="org.splat.simer.EditSimulationContextAction"
+ scope="prototype">
+ <property name="stepService" ref="stepService" />
+ <property name="studyService" ref="studyService" />
+ </bean>
+
+ <bean id="uploadAction" class="org.splat.simer.UploadAction"
+ scope="prototype">
+ </bean>
+
+ <bean id="importDocumentAction"
+ class="org.splat.simer.ImportDocumentAction" scope="prototype">
+ <property name="projectSettings" ref="projectSettings" />
+ <property name="publicationService" ref="publicationService" />
+ </bean>
+
+ <bean id="versionDocumentAction"
+ class="org.splat.simer.VersionDocumentAction" scope="prototype">
+ <property name="projectSettings" ref="projectSettings" />
+ <property name="publicationService" ref="publicationService" />
+ </bean>
+
+ <bean id="editDocumentAction"
+ class="org.splat.simer.EditDocumentAction" scope="prototype">
+ <property name="publicationService" ref="publicationService" />
+ </bean>
+
+ <bean id="editKnowledgeElementAction"
+ class="org.splat.simer.EditKnowledgeElementAction"
+ scope="prototype">
+ <property name="knowledgeElementService"
+ ref="knowledgeElementService" />
+ <property name="scenarioService" ref="scenarioService" />
+ </bean>
+
+ <bean id="databaseIndexingAction"
+ class="org.splat.simer.admin.DatabaseIndexingAction"
+ scope="prototype">
+ <property name="importedStudy" ref="importedStudy" />
+ <property name="searchService" ref="searchService" />
+ </bean>
+
+ <bean id="importUserAction"
+ class="org.splat.simer.admin.ImportUserAction" scope="prototype">
+ </bean>
+
+ <bean id="simulationContextAction"
+ class="org.splat.simer.admin.SimulationContextAction"
+ scope="prototype">
+ <property name="searchService" ref="searchService" />
+ <property name="projectSettings" ref="projectSettings" />
+ </bean>
+
+ <bean id="knowledgeElementAction"
+ class="org.splat.simer.admin.KnowledgeElementAction"
+ scope="prototype">
+ </bean>
+
+ <bean id="saveDocumentAction"
+ class="org.splat.module.SaveDocumentAction" scope="prototype">
+ <property name="publicationService" ref="publicationService" />
+ <property name="scenarioService" ref="scenarioService" />
+ <property name="stepService" ref="stepService" />
+ </bean>
+
</beans>
-
\ No newline at end of file
--- /dev/null
+#################################################################
+# P6Spy Options File #
+# See documentation for detailed instructions #
+#################################################################
+
+#################################################################
+# MODULES #
+# #
+# Modules provide the P6Spy functionality. If a module, such #
+# as module_log is commented out, that functionality will not #
+# be available. If it is not commented out (if it is active), #
+# the functionality will be active. #
+# #
+# Values set in Modules cannot be reloaded using the #
+# reloadproperties variable. Once they are loaded, they remain #
+# in memory until the application is restarted. #
+# #
+#################################################################
+
+module.log=com.p6spy.engine.logging.P6LogFactory
+#module.outage=com.p6spy.engine.outage.P6OutageFactory
+
+#################################################################
+# REALDRIVER(s) #
+# #
+# In your application server configuration file you replace the #
+# "real driver" name with com.p6spy.engine.P6SpyDriver. This is #
+# where you put the name of your real driver P6Spy can find and #
+# register your real driver to do the database work. #
+# #
+# If your application uses several drivers specify them in #
+# realdriver2, realdriver3. See the documentation for more #
+# details. #
+# #
+# Values set in REALDRIVER(s) cannot be reloaded using the #
+# reloadproperties variable. Once they are loaded, they remain #
+# in memory until the application is restarted. #
+# #
+#################################################################
+
+# oracle driver
+# realdriver=oracle.jdbc.driver.OracleDriver
+
+# mysql Connector/J driver
+realdriver=com.mysql.jdbc.Driver
+
+# informix driver
+# realdriver=com.informix.jdbc.IfxDriver
+
+# ibm db2 driver
+# realdriver=COM.ibm.db2.jdbc.net.DB2Driver
+
+# the mysql open source driver
+#realdriver=org.gjt.mm.mysql.Driver
+
+#specifies another driver to use
+realdriver2=
+#specifies a third driver to use
+realdriver3=
+
+
+#the DriverManager class sequentially tries every driver that is
+#registered to find the right driver. In some instances, it's possible to
+#load up the realdriver before the p6spy driver, in which case your connections
+#will not get wrapped as the realdriver will "steal" the connection before
+#p6spy sees it. Set the following property to "true" to cause p6spy to
+#explicitily deregister the realdrivers
+deregisterdrivers=false
+
+################################################################
+# P6LOG SPECIFIC PROPERTIES #
+################################################################
+# no properties currently available
+
+################################################################
+# EXECUTION THRESHOLD PROPERTIES #
+################################################################
+# This feature applies to the standard logging of P6Spy. #
+# While the standard logging logs out every statement #
+# regardless of its execution time, this feature puts a time #
+# condition on that logging. Only statements that have taken #
+# longer than the time specified (in milliseconds) will be #
+# logged. This way it is possible to see only statements that #
+# have exceeded some high water mark. #
+# This time is reloadable. #
+#
+# executionthreshold=integer time (milliseconds)
+#
+executionthreshold=
+
+################################################################
+# P6OUTAGE SPECIFIC PROPERTIES #
+################################################################
+# Outage Detection
+#
+# This feature detects long-running statements that may be indicative of
+# a database outage problem. If this feature is turned on, it will log any
+# statement that surpasses the configurable time boundary during its execution.
+# When this feature is enabled, no other statements are logged except the long
+# running statements. The interval property is the boundary time set in seconds.
+# For example, if this is set to 2, then any statement requiring at least 2
+# seconds will be logged. Note that the same statement will continue to be logged
+# for as long as it executes. So if the interval is set to 2, and the query takes
+# 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).
+#
+# outagedetection=true|false
+# outagedetectioninterval=integer time (seconds)
+#
+outagedetection=false
+outagedetectioninterval=
+
+################################################################
+# COMMON PROPERTIES #
+################################################################
+
+# filter what is logged
+filter=false
+
+# comma separated list of tables to include when filtering
+include =
+# comma separated list of tables to exclude when filtering
+exclude =
+
+# sql expression to evaluate if using regex filtering
+sqlexpression =
+
+
+# turn on tracing
+autoflush = true
+
+# sets the date format using Java's SimpleDateFormat routine
+dateformat=
+
+#list of categories to explicitly include
+includecategories=
+
+#list of categories to exclude: error, info, batch, debug, statement,
+#commit, rollback and result are valid values
+excludecategories=info,debug,result,batch
+
+
+#allows you to use a regex engine or your own matching engine to determine
+#which statements to log
+#
+#stringmatcher=com.p6spy.engine.common.GnuRegexMatcher
+#stringmatcher=com.p6spy.engine.common.JakartaRegexMatcher
+stringmatcher=
+
+# prints a stack trace for every statement logged
+stacktrace=false
+# if stacktrace=true, specifies the stack trace to print
+stacktraceclass=
+
+# determines if property file should be reloaded
+reloadproperties=false
+# determines how often should be reloaded in seconds
+reloadpropertiesinterval=60
+
+#if=true then url must be prefixed with p6spy:
+useprefix=false
+
+#specifies the appender to use for logging
+#appender=com.p6spy.engine.logging.appender.Log4jLogger
+#appender=com.p6spy.engine.logging.appender.StdoutLogger
+appender=com.p6spy.engine.logging.appender.FileLogger
+
+# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log) (used for file logger only)
+logfile = spy.log
+
+# append to the p6spy log file. if this is set to false the
+# log file is truncated every time. (file logger only)
+append=true
+
+#The following are for log4j logging only
+log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
+log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
+log4j.appender.STDOUT.layout.ConversionPattern=p6spy - %m%n
+
+#log4j.appender.CHAINSAW_CLIENT=org.apache.log4j.net.SocketAppender
+#log4j.appender.CHAINSAW_CLIENT.RemoteHost=localhost
+#log4j.appender.CHAINSAW_CLIENT.Port=4445
+#log4j.appender.CHAINSAW_CLIENT.LocationInfo=true
+
+log4j.logger.p6spy=INFO,STDOUT
+
+
+#################################################################
+# DataSource replacement #
+# #
+# Replace the real DataSource class in your application server #
+# configuration with the name com.p6spy.engine.spy.P6DataSource,#
+# then add the JNDI name and class name of the real #
+# DataSource here #
+# #
+# Values set in this item cannot be reloaded using the #
+# reloadproperties variable. Once it is loaded, it remains #
+# in memory until the application is restarted. #
+# #
+#################################################################
+#realdatasource=/RealMySqlDS
+#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
+
+#################################################################
+# DataSource properties #
+# #
+# If you are using the DataSource support to intercept calls #
+# to a DataSource that requires properties for proper setup, #
+# define those properties here. Use name value pairs, separate #
+# the name and value with a semicolon, and separate the #
+# pairs with commas. #
+# #
+# The example shown here is for mysql #
+# #
+#################################################################
+#realdatasourceproperties=port;3306,serverName;ibmhost,databaseName;mydb
+
+
+#################################################################
+# JNDI DataSource lookup #
+# #
+# If you are using the DataSource support outside of an app #
+# server, you will probably need to define the JNDI Context #
+# environment. #
+# #
+# If the P6Spy code will be executing inside an app server then #
+# do not use these properties, and the DataSource lookup will #
+# use the naming context defined by the app server. #
+# #
+# The two standard elements of the naming environment are #
+# jndicontextfactory and jndicontextproviderurl. If you need #
+# additional elements, use the jndicontextcustom property. #
+# You can define multiple properties in jndicontextcustom, #
+# in name value pairs. Separate the name and value with a #
+# semicolon, and separate the pairs with commas. #
+# #
+# The example shown here is for a standalone program running on #
+# a machine that is also running JBoss, so the JDNI context #
+# is configured for JBoss (3.0.4). #
+# #
+#################################################################
+#jndicontextfactory=org.jnp.interfaces.NamingContextFactory
+#jndicontextproviderurl=localhost:1099
+#jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.nameing:org.jnp.interfaces
+
+#jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory
+#jndicontextproviderurl=iiop://localhost:900
--- /dev/null
+package test;
+
+import org.splat.launcher.FileTransfer;
+import org.splat.launcher.WindowsRegistry;
+
+
+public class Test {
+
+
+// ==============================================================================================================================
+// Main
+// ==============================================================================================================================
+
+ public static void main(String[] args) {
+// --------------------------------------
+// String url = "http://localhost:8080/repository/2011/PLM110001/1.Study";
+ String command = args[0];
+// String filename = args[1];
+
+ String applikey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Applications\\" + command;
+ String key = "";
+ String module = WindowsRegistry.readValue(applikey + "\\shell\\open\\command ", key);
+ if (module == null) module = WindowsRegistry.readValue(applikey + "\\shell\\edit\\command ", key);
+ try {
+// FileTransfer.Download(url, filename, path);
+ String[] parse = module.split("/"); // Removing eventual options
+
+ Runtime.getRuntime().exec(parse[0]);
+// Runtime.getRuntime().exec(parse[0] + " \"" + path + "\\" + filename + "\"");
+ }
+ catch (Exception error) {
+ System.out.println("Unable to start " + module);
+ }
+ }
+}
\ No newline at end of file