summaryrefslogtreecommitdiff
path: root/source/com/c2kernel/entity/TraceableEntity.java
blob: 49bbe47af6ba781390a4b98c76614c555674888e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**************************************************************************
 * TraceableEntity
 *
 * $Workfile$
 * $Revision: 1.108 $
 * $Date: 2005/10/06 14:46:22 $
 *
 * Copyright (C) 2001 CERN - European Organization for Nuclear Research
 * All rights reserved.
 **************************************************************************/

package com.c2kernel.entity;

import java.util.Iterator;

import com.c2kernel.common.AccessRightsException;
import com.c2kernel.common.InvalidDataException;
import com.c2kernel.common.InvalidTransitionException;
import com.c2kernel.common.ObjectAlreadyExistsException;
import com.c2kernel.common.ObjectNotFoundException;
import com.c2kernel.common.PersistencyException;
import com.c2kernel.entity.agent.JobArrayList;
import com.c2kernel.lifecycle.instance.CompositeActivity;
import com.c2kernel.lifecycle.instance.Workflow;
import com.c2kernel.lifecycle.instance.stateMachine.Transitions;
import com.c2kernel.lookup.AgentPath;
import com.c2kernel.lookup.InvalidEntityPathException;
import com.c2kernel.persistency.ClusterStorage;
import com.c2kernel.persistency.ClusterStorageException;
import com.c2kernel.persistency.TransactionManager;
import com.c2kernel.process.Gateway;
import com.c2kernel.property.Property;
import com.c2kernel.property.PropertyArrayList;
import com.c2kernel.utils.CastorXMLUtility;
import com.c2kernel.utils.Logger;

/**************************************************************************
*
* @author $Author: abranson $ $Date: 2005/10/06 14:46:22 $
* @version $Revision: 1.108 $
* <pre>
*                                ,.   '\'\    ,---.
*                            .  | \\  l\\l_ //    |
*        _              _       |  \\/ `/  `.|    |
*      /~\\   \        //~\     | Y |   |   ||  Y |
*      |  \\   \      //  |     |  \|   |   |\ /  |
*      [   ||        ||   ]     \   |  o|o  | >  /
*     ] Y  ||        ||  Y [     \___\_--_ /_/__/
*     |  \_|l,------.l|_/  |     /.-\(____) /--.\
*     |   >'          `<   |     `--(______)----'
*     \  (/~`--____--'~\)  /         u// u / \
*      `-_>-__________-<_-'          / \  / /|
*          /(_#(__)#_)\             ( .) / / ]
*          \___/__\___/              `.`' /   [
*           /__`--'__\                |`-'    |
*        /\(__,>-~~ __)               |       |_
*     /\//\\(  `--~~ )               _l       |-:.
*     '\/  <^\      /^>             |  `   (  <  \\
*          _\ >-__-< /_           ,-\  ,-~~->. \  `:._,/
*        (___\    /___)         (____/    (____)   `-'
*             Kovax            and, paradoxically, Kovax
* </pre>
***************************************************************************/

public class TraceableEntity extends ItemPOA
{

    private int                         mSystemKey;
    private org.omg.PortableServer.POA  mPoa;
    private TransactionManager          mStorage;


   /**************************************************************************
    * Constructor used by the Locator only
    **************************************************************************/
    public TraceableEntity( int                  key,
                            org.omg.PortableServer.POA poa )
    {
        Logger.msg(5,"TraceableEntity::constructor() - SystemKey:" + key );

        mSystemKey   = key;
        mPoa         = poa;
        mStorage     = Gateway.getStorage();
    }


   /**************************************************************************
    *
    **************************************************************************/
    public org.omg.PortableServer.POA _default_POA()
    {
        if(mPoa != null)
            return mPoa;
        else
            return super._default_POA();
    }


   /**************************************************************************
    *
    **************************************************************************/
    public int getSystemKey()
    {
        Logger.msg(8, "TraceableEntity::getSystemKey() - " + mSystemKey);
        return mSystemKey;
    }

   /**************************************************************************
    *
    **************************************************************************/
    public void initialise( int agentId,
                            String  propString,
                            String  initWfString
                            )
        throws AccessRightsException,
               InvalidDataException,
               PersistencyException
    {
        Logger.msg(1, "TraceableEntity::initialise("+mSystemKey+") - agent:"+agentId);
        synchronized (this) {
            Workflow lc   = null;
            PropertyArrayList props = null;
            
            AgentPath agentPath;
            try {
                agentPath = new AgentPath(agentId);
            } catch (InvalidEntityPathException e) {
                throw new AccessRightsException("Invalid Agent Id:" + agentId);
            }
            
            //unmarshalling checks the validity of the received strings
    
            // create properties
            if (!propString.equals("")) {
                try {
                    props = (PropertyArrayList)CastorXMLUtility.unmarshall(propString);
                    for (Iterator i = props.list.iterator(); i.hasNext();) {
                        Property thisProp = (Property)i.next();
                        mStorage.put(mSystemKey, thisProp, props);
                    }
                } catch (Throwable ex) {
                    Logger.msg(8, "TraceableEntity::initialise("+mSystemKey+  ") - Properties were invalid: "+propString);
                    Logger.error(ex);
                    mStorage.abort(props);
                }
    			mStorage.commit(props);
            }
            
            // create wf
            try {
            	if (initWfString == null || initWfString.equals("")) 
            		lc = new Workflow(new CompositeActivity());
            	else
            		lc = new Workflow((CompositeActivity)CastorXMLUtility.unmarshall(initWfString));
                lc.initialise(mSystemKey, agentPath);
                mStorage.put(mSystemKey, lc, null);
            } catch (Throwable ex) {
                Logger.msg(8, "TraceableEntity::initialise("+mSystemKey+") - Workflow was invalid: "+initWfString);
                Logger.error(ex);
            }
        }    
    }

    /**************************************************************************
     *
     **************************************************************************/
	//requestdata is xmlstring
    public void requestAction( int agentId,
                               String stepPath,
                               int transitionID,
                               String requestData
                              )
        throws AccessRightsException,
               InvalidTransitionException,
               ObjectNotFoundException,
               InvalidDataException,
               PersistencyException,
               ObjectAlreadyExistsException
    {
        synchronized (this) {
            try {

                Logger.msg(1, "TraceableEntity::request("+mSystemKey+") - " + 
                    Transitions.getTransitionName(transitionID) + " "+stepPath + " by " +agentId );

                AgentPath agent = new AgentPath(agentId);            
                Workflow lifeCycle = (Workflow)mStorage.get(mSystemKey, ClusterStorage.LIFECYCLE+"/workflow", null);
    
                lifeCycle.requestAction( agent,
                                         stepPath,
                                         transitionID,
                                         requestData );
                                         
                // store the workflow if we've changed the state of the domain wf
                if (!(stepPath.startsWith("workflow/predefined")))                                      
                    mStorage.put(mSystemKey, lifeCycle, null);
            
            // Normal operation exceptions
            } catch (AccessRightsException ex) {
                Logger.msg("Propagating AccessRightsException back to the calling agent"); 
                throw ex;
            } catch (InvalidTransitionException ex) {
                Logger.msg("Propagating InvalidTransitionException back to the calling agent"); 
                throw ex;
            } catch (ObjectNotFoundException ex) {
                Logger.msg("Propagating ObjectNotFoundException back to the calling agent");  
                throw ex;                
            // errors
            } catch (ClusterStorageException ex) {
                Logger.error(ex);
                throw new PersistencyException("Error on storage: "+ex.getMessage(), "");
            } catch (InvalidEntityPathException ex) {
                Logger.error(ex);
                throw new AccessRightsException("Invalid Agent Id: "+agentId, "");
            } catch (InvalidDataException ex) { 
                Logger.error(ex);
                Logger.msg("Propagating InvalidDataException back to the calling agent"); 
                throw ex;
            } catch (ObjectAlreadyExistsException ex) { 
                Logger.error(ex);
                Logger.msg("Propagating ObjectAlreadyExistsException back to the calling agent"); 
                throw ex;
            // non-CORBA exception hasn't been caught!
            } catch (Throwable ex) {
                Logger.error("Unknown Error: requestAction on "+mSystemKey+" by "+agentId+" executing "+stepPath);
                Logger.error(ex);
                throw new InvalidDataException("Extraordinary Exception during execution:"+ex.getClass().getName()+" - "+ex.getMessage(), "");
            }
        }            
    }

   /**************************************************************************
    *
    **************************************************************************/
    public String queryLifeCycle( int agentId, 
                                  boolean     filter
                                )
        throws AccessRightsException,
               ObjectNotFoundException,
               PersistencyException
    {
        synchronized (this) {
            Logger.msg(1, "TraceableEntity::queryLifeCycle("+mSystemKey+") - agent: " + agentId);
    
            try
            {
                AgentPath agent = new AgentPath(agentId);
                Workflow wf = (Workflow)mStorage.get(mSystemKey, ClusterStorage.LIFECYCLE+"/workflow", null);
                JobArrayList jobBag = new JobArrayList();
                CompositeActivity domainWf = (CompositeActivity)wf.search("workflow/domain");
                jobBag.list = filter?domainWf.calculateJobs(agent, true):domainWf.calculateAllJobs(agent, true);
                Logger.msg(1, "TraceableEntity::queryLifeCycle("+mSystemKey+") - Returning "+jobBag.list.size()+" jobs.");
                return CastorXMLUtility.marshall( jobBag );
            }
            catch( Throwable ex )
            {
                Logger.error(ex);
                return "<ERROR/>";
            }
        }
    }

   /**************************************************************************
    * The description for operation getData.
    *
    * @param path - the path to the object required
    * 		  the suffix 'all' retrieves a listing of all keys on that level
    *
    * @return The result string in xml format 
	*		   except 'all' which returns a comma sep list
    *
    * @exception ObjectNotFoundException
    * ************************************************************************/
    public String queryData(String path)
        throws AccessRightsException,
               ObjectNotFoundException,
               PersistencyException
    {
        synchronized (this) {
            String  result = "";
    
            Logger.msg(1, "TraceableEntity::queryData("+mSystemKey+") - " + path );
    
            try
            {	// check for cluster contents query

                if (path.endsWith("/all"))
                {
                    int allPos = path.lastIndexOf("all");
                    String   query = path.substring(0,allPos);
                    String[] ids   = mStorage.getClusterContents( mSystemKey, query );
    
                    for( int i=0; i<ids.length; i++ )
                    {
                        result += ids[i];
    
                        if( i != ids.length-1 )
                            result += ",";
                    }
                }
                //****************************************************************
                else
                {	// retrieve the object instead
                    C2KLocalObject obj = mStorage.get( mSystemKey, path, null );
                    
                    // marshall it, or in the case of an outcome get the data.
                    result = CastorXMLUtility.marshall(obj);
                }
            }
            catch (ObjectNotFoundException ex) {
                throw ex;
            }
            catch(Throwable ex)
            {
                Logger.warning("TraceableEntity::queryData("+mSystemKey+") - "+
                              path + " Failed: "+ex.getClass().getName());
                throw new PersistencyException("Server exception: "+ex.getClass().getName(), "");
            }
    
            if( Logger.doLog(9) )
                Logger.msg(9, "TraceableEntity::queryData("+mSystemKey+") - result:" + result );
    
            return result;
        }
    }
    /**
     *
     */
    protected void finalize() throws Throwable {
        Logger.msg(7, "Item "+mSystemKey+" reaped");
        Gateway.getStorage().clearCache(mSystemKey, null);
        super.finalize();
    }

}