2 * Copyright (c) 2017 Ericsson Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.aaa.shiro.realm.util.http;
10 import java.util.HashSet;
12 import javax.net.ssl.HostnameVerifier;
13 import javax.net.ssl.SSLContext;
14 import javax.ws.rs.client.Client;
15 import javax.ws.rs.client.ClientBuilder;
16 import org.glassfish.jersey.client.ClientConfig;
19 * An utility that represents an HTTP client that allows to make
22 //Suppressed so UT's can mock it using Mockito.
23 @SuppressWarnings("checkstyle:FinalClass")
24 public class SimpleHttpClient {
26 private final Client client;
28 private SimpleHttpClient(final Client client) {
33 * Obtain a builder for {@code SimpleHttpClient}.
35 * @return the client builder.
37 public static Builder clientBuilder() {
42 * Obtain a builder for {@link SimpleHttpRequest}.
44 * @param outputType the return type of the request.
45 * @param <T> the return type of the request.
46 * @return the request builder.
48 public <T> SimpleHttpRequest.Builder<T> requestBuilder(Class<T> outputType) {
49 return new SimpleHttpRequest.Builder<>(client, outputType);
52 public static class Builder {
54 private SSLContext sslContext;
55 private HostnameVerifier hostnameVerifier;
56 private final Set<Class<?>> providers = new HashSet<>();
63 * Sets the SSLContext to be used for SSL requests.
65 * @param context the SSLContext.
66 * @return self, the client builder.
68 public Builder sslContext(final SSLContext context) {
69 this.sslContext = context;
74 * Sets the hostname verifier the request is made with.
76 * @param verifier the hostname verifier.
77 * @return self, the client builder.
79 public Builder hostnameVerifier(final HostnameVerifier verifier) {
80 this.hostnameVerifier = verifier;
85 * Sets a JAX-RS provider to use for this request. Can be called
86 * multiple times to add multiple providers.
88 * @param provider the provider.
89 * @return self, the client builder.
91 public Builder provider(final Class<?> provider) {
92 providers.add(provider);
101 public SimpleHttpClient build() {
102 final ClientConfig clientConfig = new ClientConfig();
103 providers.forEach(clientConfig::register);
104 Client client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(hostnameVerifier)
105 .withConfig(clientConfig).build();
106 return new SimpleHttpClient(client);