Вопрос

I have an object "Node" defined by its hostName and a list of strings (which consists in a list of one or more services that the Node provides). I need to write a method that iterates over a Map of <List<String>, Integer>, and when a client asks if a certain service is available, it returns all the nodes that provide the asked service.

I have a similar method that works for Node objects which contain a single string (not a list of strings):

  public Map<String, Integer> getProvidersForService(String svcName, int port) throws TException {
    Map<String, Integer> result = new HashMap<>();
    for (Map.Entry<Node, Integer> pair : nodePorts.entrySet()) {
        String nodeService = pair.getKey().services;            
        if (nodeService.equals(svcName)) {                          
            result.put(pair.getKey().services, pair.getValue()); 
            break;
        }
    }
    return result;
}

Now I need to adapt this method to the new object Node, that has a fixed list of strings. Each object Node will have a fixed list of strings. I'm not sure how to proceed, could you help me?

edit: this is the code I've tried to use but it has some problem. "NodeMultiService" is an object similar to "Node" that has hostName and List (instead of simple String) as parameters. Here's the code:

public Map<List<String>, Integer> getProvidersForMultiService(List<String> svcNames, int port) throws TException {
    svcNames = new ArrayList<String>();
    Map<List<String>, Integer> result = new HashMap<>();
    for (Map.Entry<NodeMultiService, Integer> pair : nodeMultiAndPorts.entrySet()) {
        List<String> nodeServices = pair.getKey().services;
        if (nodeServices.equals(svcNames)) {
            result.put(pair.getKey().services, pair.getValue());
            break;
        }
    }
    return result;
}

There is something wrong here because it seems doing nothing. I have a "registerNodeMulti" method that returns an int (namely, the port used by the Node to register on a server), and adds its services (a List) to the map. So I call this method to add a Node to the map, then I call the getProviderForMultiService method to look which node has an asked service.

A first trivial test is adding a single NodeMultiService, so the map should have one key/value, but this doesn't happen (I check that using assertions and the test doesn't pass the assertion that checks if the map size is 1).

Right now i'm stuck here, probably the solution is very simple but I'm not able to find it right now...

Это было полезно?

Решение

You need Map<String, List<X> >. Where X is a pointer to an endpoint providing a service whose name is the key in the map. In your case X === Integer, a port.

So:

Map<String, List<X> > endpoints; // {{"http", [80,8080]}, {"https", [443,8443]}, ...}
List<X> getProvidersForService<X>(String name) {
    return endpoints.get(name);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top