View Javadoc

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 org.cometd.Bayeux;
21  import org.cometd.Extension;
22  import org.cometd.Message;
23  
24  
25  public class TimesyncExtension implements Extension
26  {
27      public TimesyncExtension()
28      {
29      }
30      
31      public Message rcv(Message message)
32      {
33          return message;
34      }
35  
36      public Message rcvMeta(Message message)
37      {
38          Map<String,Object> ext=(Map<String,Object>)message.get(Bayeux.EXT_FIELD);
39          if (ext!=null)
40          {
41              Map<String,Object> sync=(Map<String,Object>)ext.get("timesync");
42              if (sync!=null)
43                  sync.put("ts",new Long(System.currentTimeMillis()));
44          }
45          return message;
46      }
47  
48      public Message send(Message message)
49      {
50          return message;
51      }
52  
53      public Message sendMeta(Message message)
54      {
55          Message associated = message.getAssociated();
56          if (associated!=null)
57          {
58              Map<String,Object> ext=(Map<String,Object>)associated.get(Bayeux.EXT_FIELD);
59              if (ext!=null)
60              {
61                  Map<String,Object> sync=(Map<String,Object>)ext.get("timesync");
62  
63                  if (sync!=null)
64                  {
65                      final long ts=((Long)sync.get("ts")).longValue();
66                      final long p=System.currentTimeMillis()-ts;
67                      sync.put("p",new Long(p));
68  
69                      ext=(Map<String,Object>)message.get(Bayeux.EXT_FIELD);
70                      if (ext==null)
71                      {
72                          ext=new HashMap<String, Object>();
73                          message.put(Bayeux.EXT_FIELD,ext);
74                      }
75                      ext.put("timesync",sync);
76                  }
77              }
78          }
79          return message;
80      }
81  }