1. Adjust the directory hierarchy
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / consul / Consul.java
1 /**
2 * Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.openo.msb.wrapper.consul;
18
19 import java.net.MalformedURLException;
20 import java.net.URL;
21
22 import javax.net.ssl.SSLContext;
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25
26 import org.openo.msb.wrapper.consul.util.Jackson;
27 import org.openo.msb.wrapper.consul.util.ObjectMapperContextResolver;
28
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.fasterxml.jackson.datatype.guava.GuavaModule;
31 import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
32 import com.google.common.base.Optional;
33 import com.google.common.base.Predicate;
34 import com.google.common.collect.FluentIterable;
35 import com.google.common.net.HostAndPort;
36
37 /**
38  * Client for interacting with the Consul HTTP API.
39  *
40  * @author rfast
41  */
42 public class Consul {
43
44     /**
45      * Default Consul HTTP API host.
46      */
47     public static final String DEFAULT_HTTP_HOST = "localhost";
48
49     /**
50      * Default Consul HTTP API port.
51      */
52     public static final int DEFAULT_HTTP_PORT = 8500;
53
54
55
56
57     private final CatalogClient catalogClient;
58     
59     private final HealthClient healthClient;
60
61
62     /**
63      * Private constructor.
64      *
65      * @param url     The full URL of a running Consul instance.
66      * @param builder JAX-RS client builder instance.
67      */
68     private Consul(String url, ClientBuilder builder, ObjectMapper mapper) {
69
70         if (!FluentIterable.from(builder.getConfiguration().getClasses())
71                       .filter(new Predicate<Class<?>>() {
72                         @Override
73                         public boolean apply(final Class<?> clazz) {
74                             return JacksonJaxbJsonProvider.class.isAssignableFrom(clazz);
75                         }
76                     }).first().isPresent()) {
77             builder.register(JacksonJaxbJsonProvider.class);
78         }
79         final Client client = builder
80                 .register(new ObjectMapperContextResolver(mapper))
81                 .build();
82
83      
84         if(url.endsWith("8500")){
85             this.catalogClient = new CatalogClient(client.target(url).path("v1").path("catalog"));
86             this.healthClient = new HealthClient(client.target(url).path("v1").path("health"));
87             }
88             else{
89                 this.catalogClient = new CatalogClient(client.target(url).path("api").path("catalog").path("v1"));
90                 this.healthClient = new HealthClient(client.target(url).path("api").path("health").path("v1"));   
91             }
92        
93
94 //        agentClient.ping();
95     }
96
97     /**
98      * Creates a new client given a complete URL.
99      *
100      * @deprecated Use {@link Consul.Builder}
101      *
102      * @param url     The Consul API URL.
103      * @param builder The JAX-RS client builder instance.
104      * @return A new client.
105      */
106     @Deprecated
107     public static Consul newClient(String url, ClientBuilder builder, ObjectMapper mapper) {
108         return new Consul(url, builder, mapper);
109     }
110
111     /**
112      * Creates a new client given a host and a port.
113      *
114      * @deprecated Use {@link Consul.Builder}
115      *
116      * @param host    The Consul API hostname or IP.
117      * @param port    The Consul port.
118      * @param builder The JAX-RS client builder instance.
119      * @return A new client.
120      */
121     @Deprecated
122     public static Consul newClient(String host, int port, ClientBuilder builder, ObjectMapper mapper) {
123         try {
124             return new Consul(new URL("http", host, port, "").toString(), builder, mapper);
125         } catch (MalformedURLException e) {
126             throw new ConsulException("Bad Consul URL", e);
127         }
128     }
129
130     /**
131      * Creates a new client given a host and a port.
132      *
133      * @deprecated Use {@link Consul.Builder}
134      *
135      * @param host The Consul API hostname or IP.
136      * @param port The Consul port.
137      * @return A new client.
138      */
139     @Deprecated
140     public static Consul newClient(String host, int port) {
141         return newClient(host, port, ClientBuilder.newBuilder(), Jackson.MAPPER);
142     }
143
144     /**
145      * Creates a new client given a host and a port.
146      *
147      * @deprecated Use {@link Consul.Builder}
148      *
149      * @return A new client.
150      */
151     @Deprecated
152     public static Consul newClient() {
153         return newClient(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT);
154     }
155
156    
157     /**
158      * Get the Catalog HTTP client.
159      * <p>
160      * /v1/catalog
161      *
162      * @return The Catalog HTTP client.
163      */
164     public CatalogClient catalogClient() {
165         return catalogClient;
166     }
167     
168     public HealthClient healthClient() {
169         return healthClient;
170     }
171     /**
172      * Creates a new {@link Builder} object.
173      *
174      * @return A new Consul builder.
175      */
176     public static Builder builder() {
177         return new Builder();
178     }
179
180     /**
181      * Builder for {@link Consul} client objects.
182      */
183     public static class Builder {
184         private URL url;
185         private Optional<SSLContext> sslContext = Optional.absent();
186         private ObjectMapper objectMapper = Jackson.MAPPER;
187         private ClientBuilder clientBuilder = ClientBuilder.newBuilder();
188
189         {
190             try {
191                 url = new URL("http", "localhost", 8500, "");
192             } catch (MalformedURLException e) {
193                 throw new RuntimeException(e);
194             }
195         }
196
197         /**
198          * Constructs a new builder.
199          */
200         Builder() {
201
202         }
203
204         /**
205          * Sets the URL from a {@link URL} object.
206          *
207          * @param url The Consul agent URL.
208          * @return The builder.
209          */
210         public Builder withUrl(URL url) {
211             this.url = url;
212
213             return this;
214         }
215
216         /**
217          * Sets the URL from a {@link HostAndPort} object.
218          *
219          * @param hostAndPort The Consul agent host and port.
220          * @return The builder.
221          */
222         public Builder withHostAndPort(HostAndPort hostAndPort) {
223             try {
224                 this.url = new URL("http", hostAndPort.getHostText(), hostAndPort.getPort(), "");
225             } catch (MalformedURLException e) {
226                 throw new RuntimeException(e);
227             }
228
229             return this;
230         }
231
232         /**
233          * Sets the URL from a string.
234          *
235          * @param url The Consul agent URL.
236          * @return The builder.
237          */
238         public Builder withUrl(String url) {
239             try {
240                 this.url = new URL(url);
241             } catch (MalformedURLException e) {
242                 throw new RuntimeException(e);
243             }
244
245             return this;
246         }
247
248         /**
249          * Sets the {@link SSLContext} for the client.
250          *
251          * @param sslContext The SSL context for HTTPS agents.
252          * @return The builder.
253          */
254         public Builder withSslContext(SSLContext sslContext) {
255             this.sslContext = Optional.of(sslContext);
256
257             return this;
258         }
259
260         /**
261          * Sets the {@link ObjectMapper} for the client.
262          *
263          * @param objectMapper The {@link ObjectMapper} to use.
264          * @return The builder.
265          */
266         public Builder withObjectMapper(ObjectMapper objectMapper) {
267             this.objectMapper = objectMapper;
268
269             objectMapper.registerModule(new GuavaModule());
270
271             return this;
272         }
273
274         /**
275          * Sets the JAX-RS {@link ClientBuilder} to use.
276          *
277          * @param clientBuilder The JAX-RS builder.
278          * @return This builder.
279          */
280         public Builder withClientBuilder(ClientBuilder clientBuilder) {
281             this.clientBuilder = clientBuilder;
282
283             return this;
284         }
285
286         /**
287          * Constructs a new {@link Consul} client.
288          *
289          * @return A new Consul client.
290          */
291         public Consul build() {
292             if (this.sslContext.isPresent()) {
293                 this.clientBuilder.sslContext(this.sslContext.get());
294             }
295
296             return new Consul(this.url.toExternalForm(), this.clientBuilder, this.objectMapper);
297         }
298     }
299 }