Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 1 | package org.onlab.netty; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | |
| 5 | /** |
| 6 | * Internal message representation with additional attributes |
| 7 | * for supporting, synchronous request/reply behavior. |
| 8 | */ |
| 9 | public final class InternalMessage implements Message { |
| 10 | |
| 11 | private long id; |
| 12 | private Endpoint sender; |
| 13 | private String type; |
| 14 | private Object payload; |
| 15 | private transient NettyMessagingService messagingService; |
| 16 | public static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGIG_REQUEST_REPLY"; |
| 17 | |
| 18 | // Must be created using the Builder. |
| 19 | private InternalMessage() {} |
| 20 | |
| 21 | public long id() { |
| 22 | return id; |
| 23 | } |
| 24 | |
| 25 | public String type() { |
| 26 | return type; |
| 27 | } |
| 28 | |
| 29 | public Endpoint sender() { |
| 30 | return sender; |
| 31 | } |
| 32 | |
| 33 | @Override |
| 34 | public Object payload() { |
| 35 | return payload; |
| 36 | } |
| 37 | |
Madan Jampani | 86ed055 | 2014-10-03 16:45:42 -0700 | [diff] [blame] | 38 | protected void setMessagingService(NettyMessagingService messagingService) { |
| 39 | this.messagingService = messagingService; |
| 40 | } |
| 41 | |
Madan Jampani | ab6d311 | 2014-10-02 16:30:14 -0700 | [diff] [blame] | 42 | @Override |
| 43 | public void respond(Object data) throws IOException { |
| 44 | Builder builder = new Builder(messagingService); |
| 45 | InternalMessage message = builder.withId(this.id) |
| 46 | // FIXME: Sender should be messagingService.localEp. |
| 47 | .withSender(this.sender) |
| 48 | .withPayload(data) |
| 49 | .withType(REPLY_MESSAGE_TYPE) |
| 50 | .build(); |
| 51 | messagingService.sendAsync(sender, message); |
| 52 | } |
| 53 | |
| 54 | |
| 55 | /** |
| 56 | * Builder for InternalMessages. |
| 57 | */ |
| 58 | public static class Builder { |
| 59 | private InternalMessage message; |
| 60 | |
| 61 | public Builder(NettyMessagingService messagingService) { |
| 62 | message = new InternalMessage(); |
| 63 | message.messagingService = messagingService; |
| 64 | } |
| 65 | |
| 66 | public Builder withId(long id) { |
| 67 | message.id = id; |
| 68 | return this; |
| 69 | } |
| 70 | |
| 71 | public Builder withType(String type) { |
| 72 | message.type = type; |
| 73 | return this; |
| 74 | } |
| 75 | |
| 76 | public Builder withSender(Endpoint sender) { |
| 77 | message.sender = sender; |
| 78 | return this; |
| 79 | } |
| 80 | public Builder withPayload(Object payload) { |
| 81 | message.payload = payload; |
| 82 | return this; |
| 83 | } |
| 84 | |
| 85 | public InternalMessage build() { |
| 86 | return message; |
| 87 | } |
| 88 | } |
Yuta HIGUCHI | 92626c0 | 2014-10-06 15:46:18 -0700 | [diff] [blame^] | 89 | } |