xyz.cloudbans.client.Clients.java Source code

Java tutorial

Introduction

Here is the source code for xyz.cloudbans.client.Clients.java

Source

/*
 * Copyright 2016 CloudBans (https://cloudbans.xyz)
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package xyz.cloudbans.client;

import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import xyz.cloudbans.client.config.ClientConfig;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

public class Clients {

    public Clients() {
        throw new UnsupportedOperationException(getClass().getSimpleName() + " is not initiatable.");
    }

    public static Client create(ClientConfig config) {
        return create(Executors.defaultThreadFactory(), config);
    }

    public static Client create(ExecutorService executor, ClientConfig config) {
        if (executor instanceof ThreadPoolExecutor)
            return create((ThreadPoolExecutor) executor, config);
        else
            throw new IllegalArgumentException(
                    "Executor of type " + executor.getClass().getName() + " is not supported.");
    }

    public static Client create(ThreadPoolExecutor executor, ClientConfig config) {
        return create(executor.getThreadFactory(), config);
    }

    public static Client create(ThreadFactory threadFactory, ClientConfig config) {
        return create(threadFactory, config, true);
    }

    public static Client create(ThreadFactory threadFactory, ClientConfig config, boolean start) {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().setThreadFactory(threadFactory).build();
        if (start)
            httpClient.start();
        return new DefaultClient(httpClient, config);
    }
}