summaryrefslogtreecommitdiffstats
path: root/documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/RoutingPolicyRepository.java
blob: 1a3a23eb8e415c36ce2695fd9b95798cddfc0659 (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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol;

import com.yahoo.documentapi.metrics.DocumentProtocolMetricSet;
import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.log.LogLevel;

import java.util.Map;
import java.util.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;

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

    private static final Logger log = Logger.getLogger(RoutingPolicyRepository.class.getName());
    private final Map<String, RoutingPolicyFactory> factories = new ConcurrentHashMap<String, RoutingPolicyFactory>();
    private final DocumentProtocolMetricSet metrics;

    RoutingPolicyRepository(DocumentProtocolMetricSet metrics) {
        this.metrics = metrics;
    }

    /**
     * Registers a routing policy factory for a given name.
     *
     * @param name    The name of the factory to register.
     * @param factory The factory to register.
     */
    void putFactory(String name, RoutingPolicyFactory factory) {
        factories.put(name, factory);
    }

    /**
     * Returns the routing policy factory for a given name.
     *
     * @param name The name of the factory to return.
     * @return The routing policy factory matching the criteria, or null.
     */
    RoutingPolicyFactory getFactory(String name) {
        return factories.get(name);
    }

    /**
     * Creates and returns a routing policy using the named factory and the given parameter.
     *
     * @param name  The name of the factory to use.
     * @param param The parameter to pass to the factory.
     * @return The created policy.
     */
    RoutingPolicy createPolicy(String name, String param) {
        RoutingPolicyFactory factory = getFactory(name);
        if (factory == null) {
            log.log(LogLevel.ERROR, "No routing policy factory found for name '" + name + "'.");
            return null;
        }
        final DocumentProtocolRoutingPolicy ret = factory.createPolicy(param);

        if (ret == null) {
            log.log(LogLevel.ERROR, "Routing policy factory " + factory.getClass().getName() + " failed to create a " +
                    "routing policy for parameter '" + name + "'.");
            return null;
        }

        if (ret.getMetrics() != null) {
            metrics.routingPolicyMetrics.addMetric(ret.getMetrics());
        }

        return ret;
    }
}