All Downloads are FREE. Search and download functionalities are using the official Maven repository.

vite.api.utils.Generator Maven / Gradle / Ivy

The newest version!
package vite.api.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import vite.api.exception.ApiError;
import vite.api.exception.ApiException;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Generator {

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder = new Retrofit.Builder()
            .addConverterFactory(JacksonConverterFactory.create());

    private static Retrofit retrofit;

    public static  S createService(Class serviceClass, String baseUrl) {
        builder.baseUrl(baseUrl);
        builder.client(httpClient.connectTimeout(2000, TimeUnit.MILLISECONDS).readTimeout(2000, TimeUnit.MILLISECONDS).build());
        builder.addConverterFactory(JacksonConverterFactory.create());
        retrofit = builder.build();
        return retrofit.create(serviceClass);
    }

    public static  T executeSync(Call call) {
        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                return response.body();
            } else {
                ApiError apiError = getApiError(response);
                throw new ApiException(apiError);
            }
        } catch (IOException e) {
            throw new ApiException(e);
        }
    }


	public static  void executeAsync(Call call, List> responseList) {

	    call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {

            	//responseList.add(response);
            }

            @Override
            public void onFailure(Call call, Throwable throwable) {

            	System.err.println(JSONObject.toJSONString(call.request().body()));
            }
        });

	}


	private static ApiError getApiError(Response response) throws IOException, ApiException {
		return (ApiError) retrofit.responseBodyConverter(ApiError.class, new Annotation[0]).convert(response.errorBody());
	}
}