summaryrefslogtreecommitdiffstats
path: root/jdisc_messagebus_service/src/main/java/com/yahoo/messagebus/jdisc/test/RemoteClient.java
blob: d56704886e3ff387a5446dc3deeec9d3ff0c3757 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.jdisc.test;

import com.yahoo.jrt.ListenFailedException;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.*;
import com.yahoo.messagebus.network.rpc.RPCNetwork;
import com.yahoo.messagebus.network.rpc.RPCNetworkParams;
import com.yahoo.messagebus.test.SimpleProtocol;

import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen</a>
 */
public class RemoteClient {

    private final Slobrok slobrok;
    private final String slobrokId;
    private final MessageBus mbus;
    private final ReplyQueue queue = new ReplyQueue();
    private final SourceSession session;

    private RemoteClient(Slobrok slobrok, String slobrokId, Protocol protocol) {
        this.slobrok = slobrok;
        this.slobrokId = slobrok != null ? slobrok.configId() : slobrokId;
        mbus = new MessageBus(new RPCNetwork(new RPCNetworkParams().setSlobrokConfigId(this.slobrokId)),
                              new MessageBusParams().addProtocol(protocol));
        session = mbus.createSourceSession(new SourceSessionParams().setThrottlePolicy(null).setReplyHandler(queue));
    }

    public Result sendMessage(Message msg) {
        return session.send(msg);
    }

    public Reply awaitReply(int timeout, TimeUnit unit) throws InterruptedException {
        return queue.awaitReply(timeout, unit);
    }

    public String slobrokId() {
        return slobrokId;
    }

    public void close() {
        session.destroy();
        mbus.destroy();
        if (slobrok != null) {
            slobrok.stop();
        }
    }

    public static RemoteClient newInstanceWithInternSlobrok() {
        return new RemoteClient(newSlobrok(), null, new SimpleProtocol());
    }

    public static RemoteClient newInstanceWithExternSlobrok(String slobrokId) {
        return new RemoteClient(null, slobrokId, new SimpleProtocol());
    }

    public static RemoteClient newInstanceWithProtocolAndInternSlobrok(Protocol protocol) {
        return new RemoteClient(newSlobrok(), null, protocol);
    }

    private static Slobrok newSlobrok() {
        Slobrok slobrok;
        try {
            slobrok = new Slobrok();
        } catch (ListenFailedException e) {
            throw new IllegalStateException(e);
        }
        return slobrok;
    }
}