60ba87779c6878f7dc59509118e83b378422fb10
[msb/discovery.git] / sdclient / discovery-service / src / main / java / org / onap / msb / sdclient / wrapper / consul / cache / HealthCache.java
1 /**
2  * Copyright 2016-2017 ZTE, Inc. and others.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package org.onap.msb.sdclient.wrapper.consul.cache;
15
16 import java.math.BigInteger;
17 import java.util.List;
18
19 import org.onap.msb.sdclient.wrapper.consul.HealthClient;
20 import org.onap.msb.sdclient.wrapper.consul.async.ConsulResponseCallback;
21 import org.onap.msb.sdclient.wrapper.consul.model.health.ServiceHealth;
22
23 import com.google.common.base.Function;
24
25 public class HealthCache extends ConsulCache<String, ServiceHealth> {
26
27     private final String serviceName;
28
29     private HealthCache(Function<ServiceHealth, String> keyConversion,
30                     ConsulCache.CallbackConsumer<ServiceHealth> callbackConsumer, String serviceName) {
31         super(keyConversion, callbackConsumer);
32         this.serviceName = serviceName;
33         // TODO Auto-generated constructor stub
34     }
35
36
37     public static HealthCache newCache(final HealthClient healthClient, final String serviceName,
38                     final int watchSeconds) {
39         Function<ServiceHealth, String> keyExtractor = new Function<ServiceHealth, String>() {
40             @Override
41             public String apply(ServiceHealth input) {
42                 // return input.getKey().substring(rootPath.length() + 1);
43                 return input.getService().getId();
44             }
45         };
46
47         final CallbackConsumer<ServiceHealth> callbackConsumer = new CallbackConsumer<ServiceHealth>() {
48             @Override
49             public void consume(BigInteger index, ConsulResponseCallback<List<ServiceHealth>> callback) {
50                 healthClient.getHealthyServiceInstances(serviceName, watchParams(index, watchSeconds), callback);
51             }
52         };
53
54
55         return new HealthCache(keyExtractor, callbackConsumer, serviceName);
56
57
58     }
59
60     public String getServiceName() {
61         return this.serviceName;
62     }
63
64
65 }