1   // ========================================================================
2   // Copyright 2006 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // Licensed under the Apache License, Version 2.0 (the "License");
5   // you may not use this file except in compliance with the License.
6   // You may obtain a copy of the License at 
7   // http://www.apache.org/licenses/LICENSE-2.0
8   // Unless required by applicable law or agreed to in writing, software
9   // distributed under the License is distributed on an "AS IS" BASIS,
10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  // See the License for the specific language governing permissions and
12  // limitations under the License.
13  // ========================================================================
14  
15  package org.mortbay.cometd.ext;
16  
17  import java.util.HashMap;
18  import java.util.Map;
19  
20  import dojox.cometd.Bayeux;
21  import dojox.cometd.Extension;
22  import dojox.cometd.Message;
23  
24  public class TimesyncExtension implements Extension
25  {
26      public TimesyncExtension()
27      {
28      }
29      
30      public Message rcv(Message message)
31      {
32          return message;
33      }
34  
35      public Message rcvMeta(Message message)
36      {
37          Map<String,Object> ext=(Map<String,Object>)message.get(Bayeux.EXT_FIELD);
38          if (ext!=null)
39          {
40              Map<String,Object> sync=(Map<String,Object>)ext.get("timesync");
41              if (sync!=null)
42                  sync.put("ts",new Long(System.currentTimeMillis()));
43          }
44          return message;
45      }
46  
47      public Message send(Message message)
48      {
49          return message;
50      }
51  
52      public Message sendMeta(Message message)
53      {
54          Message associated = message.getAssociated();
55          if (associated!=null)
56          {
57              Map<String,Object> ext=(Map<String,Object>)associated.get(Bayeux.EXT_FIELD);
58              if (ext!=null)
59              {
60                  Map<String,Object> sync=(Map<String,Object>)ext.get("timesync");
61  
62                  if (sync!=null)
63                  {
64                      final long ts=((Long)sync.get("ts")).longValue();
65                      final long p=System.currentTimeMillis()-ts;
66                      sync.put("p",new Long(p));
67  
68                      ext=(Map<String,Object>)message.get(Bayeux.EXT_FIELD);
69                      if (ext==null)
70                      {
71                          ext=new HashMap<String, Object>();
72                          message.put(Bayeux.EXT_FIELD,ext);
73                      }
74                      ext.put("timesync",sync);
75                  }
76              }
77          }
78          return message;
79      }
80  }