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

com.mydaco.client.MydacoClient Maven / Gradle / Ivy

package com.mydaco.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

abstract class MydacoClient {
	
	private final static ContentType contentType = ContentType.create("application/json", Consts.UTF_8);
	private final static String PARAMETERS = "parameters";
	private final static String ENDPOINT_TOKEN =  "endpointToken";

	private final Gson gson = new Gson();
	private String domain = "http://localhost";
	
	abstract void close() throws IOException;

	HttpPost createRequest(String endpointToken, JsonObject parameters) {
		JsonObject reqObject = new JsonObject();
		reqObject.addProperty(ENDPOINT_TOKEN, endpointToken);
		reqObject.add(PARAMETERS, parameters);
		String requestString = gson.toJson(reqObject);
		HttpPost httpPost = new HttpPost(domain);
		StringEntity entity = new StringEntity(requestString, contentType);
		entity.setChunked(true);
		httpPost.setEntity(entity);
		return httpPost;
	};
	
	JsonObject readResponse(HttpResponse response) throws IOException {	
		if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new IOException(response.getStatusLine().getReasonPhrase());
		}
		InputStream inputStream = response.getEntity().getContent();
		JsonObject responseJson = gson.fromJson(new InputStreamReader(inputStream), JsonObject.class);
		inputStream.close();
		return responseJson;
	}
	
	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}
	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy