KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > impl > MuleSession


1 /*
2  * $Id: MuleSession.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.impl;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.mule.MuleManager;
16 import org.mule.config.MuleProperties;
17 import org.mule.config.i18n.Message;
18 import org.mule.config.i18n.Messages;
19 import org.mule.impl.endpoint.MuleEndpoint;
20 import org.mule.providers.AbstractConnector;
21 import org.mule.umo.UMOComponent;
22 import org.mule.umo.UMOEvent;
23 import org.mule.umo.UMOException;
24 import org.mule.umo.UMOMessage;
25 import org.mule.umo.UMOSession;
26 import org.mule.umo.endpoint.EndpointNotFoundException;
27 import org.mule.umo.endpoint.UMOEndpoint;
28 import org.mule.umo.endpoint.UMOImmutableEndpoint;
29 import org.mule.umo.provider.DispatchException;
30 import org.mule.umo.provider.ReceiveException;
31 import org.mule.umo.provider.UMOConnector;
32 import org.mule.umo.provider.UMOMessageDispatcher;
33 import org.mule.umo.provider.UMOSessionHandler;
34 import org.mule.umo.routing.UMOOutboundMessageRouter;
35 import org.mule.umo.security.UMOSecurityContext;
36 import org.mule.util.UUID;
37
38 import java.util.HashMap JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.Map JavaDoc;
41
42 /**
43  * <code>MuleSession</code> manages the interaction and distribution of events for
44  * Mule UMOs.
45  */

46
47 public final class MuleSession implements UMOSession
48 {
49     /**
50      * Serial version
51      */

52     private static final long serialVersionUID = 3380926585676521866L;
53
54     /**
55      * logger used by this class
56      */

57     private static Log logger = LogFactory.getLog(MuleSession.class);
58
59     /**
60      * The Mule component associated with the session
61      */

62     private UMOComponent component = null;
63
64     /**
65      * Determines if the component is valid
66      */

67     private boolean valid = true;
68
69     private String JavaDoc id;
70
71     private UMOSecurityContext securityContext;
72
73     private Map JavaDoc properties = null;
74
75     public MuleSession(UMOComponent component)
76     {
77         properties = new HashMap JavaDoc();
78         id = UUID.getUUID();
79         this.component = component;
80     }
81
82     public MuleSession(UMOMessage message, UMOSessionHandler requestSessionHandler, UMOComponent component)
83         throws UMOException
84     {
85         this(message, requestSessionHandler);
86         if (component == null)
87         {
88             throw new IllegalArgumentException JavaDoc(
89                 new Message(Messages.PROPERTIES_X_NOT_SET, "component").toString());
90         }
91         this.component = component;
92     }
93
94     public MuleSession(UMOMessage message, UMOSessionHandler requestSessionHandler) throws UMOException
95     {
96
97         if (requestSessionHandler == null)
98         {
99             throw new IllegalArgumentException JavaDoc(new Message(Messages.PROPERTIES_X_NOT_SET,
100                 "requestSessionHandler").toString());
101         }
102
103         if (message == null)
104         {
105             throw new IllegalArgumentException JavaDoc(
106                 new Message(Messages.PROPERTIES_X_NOT_SET, "message").toString());
107         }
108
109         properties = new HashMap JavaDoc();
110         requestSessionHandler.retrieveSessionInfoFromMessage(message, this);
111         id = (String JavaDoc)getProperty(requestSessionHandler.getSessionIDKey());
112         if (id == null)
113         {
114             id = UUID.getUUID();
115             if (logger.isDebugEnabled())
116             {
117                 logger.debug("There is no session id on the request using key: "
118                              + requestSessionHandler.getSessionIDKey() + ". Generating new session id: " + id);
119             }
120         }
121         else if (logger.isDebugEnabled())
122         {
123             logger.debug("Got session with id: " + id);
124         }
125     }
126
127     public void dispatchEvent(UMOMessage message) throws UMOException
128     {
129         if (component == null)
130         {
131             throw new IllegalStateException JavaDoc(new Message(Messages.X_IS_NULL, "Component").getMessage());
132         }
133
134         UMOOutboundMessageRouter router = component.getDescriptor().getOutboundRouter();
135         if (router == null)
136         {
137             throw new EndpointNotFoundException(new Message(Messages.NO_OUTBOUND_ROUTER_SET_ON_X,
138                 component.getDescriptor().getName()));
139         }
140         router.route(message, this, false);
141     }
142
143     public void dispatchEvent(UMOMessage message, String JavaDoc endpointName) throws UMOException
144     {
145         dispatchEvent(message, MuleManager.getInstance().lookupEndpoint(endpointName));
146     }
147
148     public void dispatchEvent(UMOMessage message, UMOImmutableEndpoint endpoint) throws UMOException
149     {
150         if (endpoint == null)
151         {
152             logger.warn("Endpoint argument is null, using outbound router to determine endpoint.");
153             dispatchEvent(message);
154         }
155
156         if (logger.isDebugEnabled())
157         {
158             logger.debug("Session has received asynchronous event on: " + endpoint);
159         }
160
161         UMOEvent event = createOutboundEvent(message, endpoint, null);
162
163         dispatchEvent(event);
164         RequestContext.writeResponse(event.getMessage());
165         processResponse(event.getMessage());
166     }
167
168     public UMOMessage sendEvent(UMOMessage message, String JavaDoc endpointName) throws UMOException
169     {
170         return sendEvent(message, MuleManager.getInstance().lookupEndpoint(endpointName));
171     }
172
173     public UMOMessage sendEvent(UMOMessage message) throws UMOException
174     {
175         if (component == null)
176         {
177             throw new IllegalStateException JavaDoc(new Message(Messages.X_IS_NULL, "Component").getMessage());
178         }
179         UMOOutboundMessageRouter router = component.getDescriptor().getOutboundRouter();
180         if (router == null)
181         {
182             throw new EndpointNotFoundException(new Message(Messages.NO_OUTBOUND_ROUTER_SET_ON_X,
183                 component.getDescriptor().getName()));
184         }
185         UMOMessage result = router.route(message, this, true);
186         if (result != null)
187         {
188             RequestContext.writeResponse(result);
189             processResponse(result);
190         }
191
192         return result;
193     }
194
195     public UMOMessage sendEvent(UMOMessage message, UMOImmutableEndpoint endpoint) throws UMOException
196     {
197         if (endpoint == null)
198         {
199             logger.warn("Endpoint argument is null, using outbound router to determine endpoint.");
200             return sendEvent(message);
201         }
202
203         if (logger.isDebugEnabled())
204         {
205             logger.debug("Session has received synchronous event on endpoint: " + endpoint);
206         }
207
208         UMOEvent event = createOutboundEvent(message, endpoint, null);
209         UMOMessage result = sendEvent(event);
210
211         // Handles the situation where a response has been received via a remote
212
// ReplyTo channel.
213
if (endpoint.isRemoteSync() && endpoint.getResponseTransformer() != null && result != null)
214         {
215             Object JavaDoc response = endpoint.getResponseTransformer().transform(result.getPayload());
216             result = new MuleMessage(response, result);
217         }
218
219         if (result != null)
220         {
221             RequestContext.writeResponse(result);
222             processResponse(result);
223         }
224
225         return result;
226     }
227
228     /*
229      * (non-Javadoc)
230      *
231      * @see org.mule.umo.UMOSession#dispatchEvent(org.mule.umo.UMOEvent)
232      */

233     public void dispatchEvent(UMOEvent event) throws UMOException
234     {
235         if (event.getEndpoint().canSend())
236         {
237             try
238             {
239                 if (logger.isDebugEnabled())
240                 {
241                     logger.debug("dispatching event: " + event);
242                 }
243
244                 UMOConnector connector = event.getEndpoint().getConnector();
245                 UMOMessageDispatcher dispatcher = connector.getDispatcher(event.getEndpoint());
246
247                 if (connector instanceof AbstractConnector)
248                 {
249                     ((AbstractConnector)connector).getSessionHandler().storeSessionInfoToMessage(this,
250                         event.getMessage());
251                 }
252                 else
253                 {
254                     // TODO in Mule 2.0 we'll flatten the Connector hierachy
255
logger.warn("A session handler could not be obtained, using default");
256                     new MuleSessionHandler().storeSessionInfoToMessage(this, event.getMessage());
257                 }
258                 dispatcher.dispatch(event);
259
260             }
261             catch (Exception JavaDoc e)
262             {
263                 throw new DispatchException(event.getMessage(), event.getEndpoint(), e);
264             }
265         }
266         else if (component != null)
267         {
268             if (logger.isDebugEnabled())
269             {
270                 logger.debug("dispatching event to component: " + component.getDescriptor().getName()
271                              + ", event is: " + event);
272             }
273             component.dispatchEvent(event);
274             RequestContext.writeResponse(event.getMessage());
275             processResponse(event.getMessage());
276
277         }
278         else
279         {
280             throw new DispatchException(new Message(Messages.NO_COMPONENT_FOR_ENDPOINT), event.getMessage(),
281                 event.getEndpoint());
282         }
283     }
284
285     public String JavaDoc getId()
286     {
287         return id;
288     }
289
290     /*
291      * (non-Javadoc)
292      *
293      * @see org.mule.umo.UMOSession#sendEvent(org.mule.umo.UMOEvent)
294      */

295     // TODO This method is practically the same as dispatchEvent(UMOEvent event),
296
// so we could use some refactoring here.
297
public UMOMessage sendEvent(UMOEvent event) throws UMOException
298     {
299         int timeout = event.getMessage().getIntProperty(MuleProperties.MULE_EVENT_TIMEOUT_PROPERTY, -1);
300         if (timeout >= 0)
301         {
302             event.setTimeout(timeout);
303         }
304
305         if (event.getEndpoint().canSend())
306         {
307             try
308             {
309                 if (logger.isDebugEnabled())
310                 {
311                     logger.debug("sending event: " + event);
312                 }
313
314                 UMOConnector connector = event.getEndpoint().getConnector();
315                 UMOMessageDispatcher dispatcher = connector.getDispatcher(event.getEndpoint());
316
317                 if (connector instanceof AbstractConnector)
318                 {
319                     ((AbstractConnector)connector).getSessionHandler().storeSessionInfoToMessage(this,
320                         event.getMessage());
321                 }
322                 else
323                 {
324                     // TODO in Mule 2.0 we'll flatten the Connector hierachy
325
logger.warn("A session handler could not be obtained, using default.");
326                     new MuleSessionHandler().storeSessionInfoToMessage(this, event.getMessage());
327                 }
328                 UMOMessage response = dispatcher.send(event);
329                 RequestContext.writeResponse(response);
330                 processResponse(response);
331
332                 return response;
333
334             }
335             catch (UMOException e)
336             {
337                 throw e;
338             }
339             catch (Exception JavaDoc e)
340             {
341                 throw new DispatchException(event.getMessage(), event.getEndpoint(), e);
342             }
343
344         }
345         else if (component != null)
346         {
347             if (logger.isDebugEnabled())
348             {
349                 logger.debug("dispatching event to component: " + component.getDescriptor().getName()
350                              + " event is: " + event);
351             }
352             return component.sendEvent(event);
353
354         }
355         else
356         {
357             throw new DispatchException(new Message(Messages.NO_COMPONENT_FOR_ENDPOINT), event.getMessage(),
358                 event.getEndpoint());
359         }
360     }
361
362     /**
363      * Once an event has been processed we need to romove certain properties so that
364      * they not propagated to the next request
365      *
366      * @param response The response from the previous request
367      */

368     protected void processResponse(UMOMessage response)
369     {
370         if (response == null) return;
371         response.removeProperty(MuleProperties.MULE_METHOD_PROPERTY);
372         response.removeProperty(MuleProperties.MULE_REMOTE_SYNC_PROPERTY);
373     }
374
375     /*
376      * (non-Javadoc)
377      *
378      * @see org.mule.umo.UMOSession#isValid()
379      */

380     public boolean isValid()
381     {
382         return valid;
383     }
384
385     /*
386      * (non-Javadoc)
387      *
388      * @see org.mule.umo.UMOSession#setValid(boolean)
389      */

390     public void setValid(boolean value)
391     {
392         valid = value;
393     }
394
395     /*
396      * (non-Javadoc)
397      *
398      * @see org.mule.umo.UMOSession#receiveEvent(org.mule.umo.endpoint.UMOEndpoint,
399      * long, org.mule.umo.UMOEvent)
400      */

401     public UMOMessage receiveEvent(String JavaDoc endpointName, long timeout) throws UMOException
402     {
403         UMOEndpoint endpoint = MuleEndpoint.getOrCreateEndpointForUri(endpointName,
404             UMOEndpoint.ENDPOINT_TYPE_RECEIVER);
405         return receiveEvent(endpoint, timeout);
406     }
407
408     /*
409      * (non-Javadoc)
410      *
411      * @see org.mule.umo.UMOSession#receiveEvent(org.mule.umo.endpoint.UMOEndpoint,
412      * long, org.mule.umo.UMOEvent)
413      */

414     public UMOMessage receiveEvent(UMOImmutableEndpoint endpoint, long timeout) throws UMOException
415     {
416         try
417         {
418             UMOMessageDispatcher dispatcher = endpoint.getConnector().getDispatcher(endpoint);
419             return dispatcher.receive(endpoint, timeout);
420         }
421         catch (Exception JavaDoc e)
422         {
423             throw new ReceiveException(endpoint, timeout, e);
424         }
425     }
426
427     public UMOEvent createOutboundEvent(UMOMessage message,
428                                         UMOImmutableEndpoint endpoint,
429                                         UMOEvent previousEvent) throws UMOException
430     {
431         if (endpoint == null)
432         {
433             throw new DispatchException(new Message(Messages.X_IS_NULL, "Outbound Endpoint"), message,
434                 endpoint);
435         }
436
437         if (logger.isDebugEnabled())
438         {
439             logger.debug("Creating event with data: " + message.getPayload().getClass().getName()
440                          + ", for endpoint: " + endpoint);
441         }
442
443         // Use default transformer if none is set
444
if (endpoint.getTransformer() == null && endpoint instanceof UMOEndpoint)
445         {
446             if (endpoint.getConnector() instanceof AbstractConnector)
447             {
448                 ((UMOEndpoint)endpoint).setTransformer(((AbstractConnector)endpoint.getConnector()).getDefaultOutboundTransformer());
449                 logger.debug("Using default connector outbound transformer: " + endpoint.getTransformer());
450             }
451         }
452         try
453         {
454             UMOEvent event;
455             if (previousEvent != null)
456             {
457                 event = new MuleEvent(message, endpoint, component, previousEvent);
458             }
459             else
460             {
461                 event = new MuleEvent(message, endpoint, this, false, null);
462             }
463             return event;
464         }
465         catch (Exception JavaDoc e)
466         {
467             throw new DispatchException(new Message(Messages.FAILED_TO_CREATE_X, "Event"), message, endpoint,
468                 e);
469         }
470     }
471
472     /**
473      * @return Returns the component.
474      */

475     public UMOComponent getComponent()
476     {
477         return component;
478     }
479
480     void setComponent(UMOComponent component)
481     {
482         this.component = component;
483     }
484
485     /**
486      * The security context for this session. If not null outbound, inbound and/or
487      * method invocations will be authenticated using this context
488      *
489      * @param context the context for this session or null if the request is not
490      * secure.
491      */

492     public void setSecurityContext(UMOSecurityContext context)
493     {
494         securityContext = context;
495     }
496
497     /**
498      * The security context for this session. If not null outbound, inbound and/or
499      * method invocations will be authenticated using this context
500      *
501      * @return the context for this session or null if the request is not secure.
502      */

503     public UMOSecurityContext getSecurityContext()
504     {
505         return securityContext;
506     }
507
508     /**
509      * Will set a session level property. These will either be stored and retrieved
510      * using the underlying transport mechanism of stored using a default mechanism
511      *
512      * @param key the key for the object data being stored on the session
513      * @param value the value of the session data
514      */

515     public void setProperty(Object JavaDoc key, Object JavaDoc value)
516     {
517         properties.put(key, value);
518     }
519
520     /**
521      * Will retrieve a session level property.
522      *
523      * @param key the key for the object data being stored on the session
524      * @return the value of the session data or null if the property does not exist
525      */

526     public Object JavaDoc getProperty(Object JavaDoc key)
527     {
528         return properties.get(key);
529     }
530
531     /**
532      * Will retrieve a session level property and remove it from the session
533      *
534      * @param key the key for the object data being stored on the session
535      * @return the value of the session data or null if the property does not exist
536      */

537     public Object JavaDoc removeProperty(Object JavaDoc key)
538     {
539         return properties.remove(key);
540     }
541
542     /**
543      * Returns an iterater of property keys for the session properties on this
544      * session
545      *
546      * @return an iterater of property keys for the session properties on this
547      * session
548      */

549     public Iterator JavaDoc getPropertyNames()
550     {
551         return properties.keySet().iterator();
552     }
553
554 }
555
Popular Tags