blob: 6208bc97077e865e6a1daaec3232bde19f13c865 (
plain) (
blame)
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
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.shared;
import com.yahoo.jdisc.AbstractResource;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.log.LogLevel;
import com.yahoo.messagebus.*;
import com.yahoo.messagebus.Error;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
/**
* @author Simon Thoresen Hult
*/
public class SharedIntermediateSession extends AbstractResource
implements ClientSession, ServerSession, MessageHandler, ReplyHandler
{
private static final Logger log = Logger.getLogger(SharedIntermediateSession.class.getName());
private final AtomicReference<MessageHandler> msgHandler = new AtomicReference<>();
private final SharedMessageBus mbus;
private final IntermediateSession session;
private final ResourceReference mbusReference;
public SharedIntermediateSession(SharedMessageBus mbus, IntermediateSessionParams params) {
if (params.getReplyHandler() != null) {
throw new IllegalArgumentException("Reply handler must be null.");
}
this.mbus = mbus;
this.msgHandler.set(params.getMessageHandler());
this.session = mbus.messageBus().createIntermediateSession(params.setReplyHandler(this)
.setMessageHandler(this));
this.mbusReference = mbus.refer();
}
public IntermediateSession session() {
return session;
}
@Override
public Result sendMessage(Message msg) {
session.forward(msg);
return Result.ACCEPTED;
}
@Override
public void sendReply(Reply reply) {
session.forward(reply);
}
@Override
public MessageHandler getMessageHandler() {
return msgHandler.get();
}
@Override
public void setMessageHandler(MessageHandler msgHandler) {
if (!this.msgHandler.compareAndSet(null, msgHandler)) {
throw new IllegalStateException("Message handler already registered.");
}
}
@Override
public void handleMessage(Message msg) {
MessageHandler msgHandler = this.msgHandler.get();
if (msgHandler == null) {
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.SESSION_BUSY, "Session not fully configured yet."));
sendReply(reply);
return;
}
msgHandler.handleMessage(msg);
}
@Override
public void handleReply(Reply reply) {
reply.popHandler().handleReply(reply);
}
@Override
public String connectionSpec() {
return session.getConnectionSpec();
}
@Override
public String name() {
return session.getName();
}
@Override
protected void destroy() {
log.log(LogLevel.DEBUG, "Destroying shared intermediate session.");
session.destroy();
mbusReference.close();
}
}
|