summaryrefslogtreecommitdiff
path: root/java/newclient/src/main/java/org/apache/qpid/nclient/amqp/AMQPCallBackSupport.java
blob: 890b0dd6ebd49f76e792df8d3c2b27c8b686d390 (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
package org.apache.qpid.nclient.amqp;

import java.security.SecureRandom;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.nclient.core.QpidConstants;
import org.apache.qpid.nclient.model.AMQPMethodEvent;

public abstract class AMQPCallBackSupport 
{
	private SecureRandom _localCorrelationIdGenerator = new SecureRandom();
	protected ConcurrentHashMap<Long,AMQPCallBack> _cbMap = new ConcurrentHashMap<Long,AMQPCallBack>();
	
	//the channelId assigned for this instance
	protected int _channelId;
	
	public AMQPCallBackSupport(int channelId)
	{
		_channelId = channelId; 
	}
	
	private long getNextCorrelationId()
	{
		return _localCorrelationIdGenerator.nextLong();
	}
	
	
	// For methods that still use nowait, hopefully they will remove nowait
	protected AMQPMethodEvent handleNoWait(boolean noWait,AMQMethodBody methodBody,AMQPCallBack cb)
	{
		if(noWait)
		{
			// u only need to register if u are expecting a response
			long localCorrelationId = getNextCorrelationId();
			AMQPMethodEvent msg = new AMQPMethodEvent(_channelId,methodBody,QpidConstants.EMPTY_CORRELATION_ID,localCorrelationId);
			_cbMap.put(localCorrelationId, cb);
			return msg; 
		}
		else
		{
			AMQPMethodEvent msg = new AMQPMethodEvent(_channelId,methodBody,QpidConstants.EMPTY_CORRELATION_ID);
			return msg;			
		}
	}
	
	protected AMQPMethodEvent handleAsynchronousCall(AMQMethodBody methodBody,AMQPCallBack cb)
	{
		long localCorrelationId = getNextCorrelationId();
		AMQPMethodEvent msg = new AMQPMethodEvent(_channelId,methodBody,QpidConstants.EMPTY_CORRELATION_ID,localCorrelationId);
		_cbMap.put(localCorrelationId, cb);
		return msg;
	}
	
	protected void invokeCallBack(long localCorrelationId, AMQMethodBody methodBody)
	{
		if(_cbMap.contains(localCorrelationId))
		{
			AMQPCallBack cb = (AMQPCallBack)_cbMap.get(localCorrelationId);
			cb.brokerResponded(methodBody);
		}
	}

}