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

org.johnnei.enjin.internal.http.impl.RequestExecuterImpl Maven / Gradle / Ivy

The newest version!
package org.johnnei.enjin.internal.http.impl;

import java.io.IOException;
import java.lang.reflect.Type;

import org.johnnei.enjin.EnjinException;
import org.johnnei.enjin.internal.RequestUtils;
import org.johnnei.enjin.internal.RequestWrapper;
import org.johnnei.enjin.internal.ResponseWrapper;
import org.johnnei.enjin.internal.gson.GsonFactory;
import org.johnnei.enjin.internal.http.IHttpAccess;
import org.johnnei.enjin.internal.http.IRequestExecuter;

import com.google.gson.Gson;

public class RequestExecuterImpl implements IRequestExecuter {

	public static final String API_PATH = "/api/v1/api.php";

	private Gson gson;

	private IHttpAccess httpAccess;

	private String domain;

	public RequestExecuterImpl(IHttpAccess httpAcces, String domain) {
		this.httpAccess = httpAcces;
		this.domain = domain + API_PATH;
		this.gson = GsonFactory.create();
	}

	@Override
	public  R getRequestResult(RequestWrapper request, Type type) {
		ResponseWrapper result = executeRequest(request, type);
		if (result.isInErrorState()) {
			result.getError().throwAsException();
		}

		return result.getResponse();
	}

	@Override
	public  ResponseWrapper executeRequest(RequestWrapper request, Type type) {
		try {
			String jsonResult = httpAccess.getString(domain, request);
			ResponseWrapper response = gson.fromJson(jsonResult, type);

			RequestUtils.verifyResponse(request, response);

			return response;
		} catch (IOException e) {
			throw new EnjinException("Failed to finish API call", e);
		}
	}

	public void setHttpAccess(IHttpAccess httpAccess) {
		this.httpAccess = httpAccess;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy