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
9 package org.opendaylight.aaa.shiro.realm.util.http;
11 import com.sun.jersey.api.client.Client;
12 import com.sun.jersey.api.client.config.ClientConfig;
13 import com.sun.jersey.api.client.config.DefaultClientConfig;
14 import com.sun.jersey.client.urlconnection.HTTPSProperties;
15 import java.util.HashSet;
17 import javax.net.ssl.HostnameVerifier;
18 import javax.net.ssl.SSLContext;
21 * An utility that represents an HTTP client that allows to make
24 //Suppressed so UT's can mock it using Mockito.
25 @SuppressWarnings("checkstyle:FinalClass")
26 public class SimpleHttpClient {
28 private final Client client;
30 private SimpleHttpClient(final Client client) {
35 * Obtain a builder for {@code SimpleHttpClient}.
37 * @return the client builder.
39 public static Builder clientBuilder() {
44 * Obtain a builder for {@link SimpleHttpRequest}.
46 * @param outputType the return type of the request.
47 * @param <T> the return type of the request.
48 * @return the request builder.
50 public <T> SimpleHttpRequest.Builder<T> requestBuilder(Class<T> outputType) {
51 return new SimpleHttpRequest.Builder<>(client, outputType);
54 public static class Builder {
56 private SSLContext sslContext;
57 private HostnameVerifier hostnameVerifier;
58 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 DefaultClientConfig();
103 clientConfig.getClasses().addAll(providers);
104 clientConfig.getProperties().put(
105 HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
106 new HTTPSProperties(hostnameVerifier, sslContext));
107 final Client client = Client.create(clientConfig);
108 return new SimpleHttpClient(client);