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

org.openforis.collect.client.AbstractClient Maven / Gradle / Ivy

There is a newer version: 4.0.97
Show newest version
package org.openforis.collect.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public abstract class AbstractClient {

	public  T getOne(String url, Class type) {
		return get(url, createSingleItemResponseProcessor(type));
	}

	public  List getList(String url, Class type) {
		return getList(url, null, type);
	}
	
	public  List getList(String url, Map params, final Class type) {
		if (params != null) {
			url = appendQueryParams(url, params);
		}
		return get(url, new ResponseProcessor>() {
			public List process(Reader r) {
				T[] result = new GsonBuilder().create().fromJson(r, TypeToken.getArray(type).getType());
				return Arrays.asList(result);
			}
		});
	}

	public  T post(String url, Object data, Class resultType) {
		return httpConnect(url, "POST", toPostData(data), createSingleItemResponseProcessor(resultType));
	}
	
	public  T patch(String url, Object data, Class resultType) {
		return httpConnect(url, "PATCH", toPostData(data), createSingleItemResponseProcessor(resultType));
	}
	
	public void delete(String url) {
		httpConnect(url, "DELETE", null, new ResponseProcessor() {
			public Void process(Reader r) {
				return null;
			}
		});
	}
	
	protected  R get(String url, ResponseProcessor responseProcessor) {
		return httpConnect(url, "GET", null, responseProcessor);
	}
	
	private  ResponseProcessor createSingleItemResponseProcessor(final Class type) {
		return new ResponseProcessor() {
			public T process(Reader r) {
				T result = new GsonBuilder().create().fromJson(r, type);
				return result;
			}
		};
	}
	
	private  R httpConnect(String url, String method, byte[] data, ResponseProcessor responseProcessor) {
		HttpURLConnection c = null;
		try {
			c = (HttpURLConnection) new URL(url).openConnection();

			c.setDoOutput(true);
			c.setDoInput(true);
			c.setUseCaches(false);
			c.setRequestMethod(method);
			c.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			c.setRequestProperty("Accept", "application/json");

			if (data != null) {
				OutputStream os = c.getOutputStream();
				os.write(data);
				os.flush();
			}
			
			if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
				throw new RuntimeException(String.format("Failed to load url %s with method %s: HTTP error code : %s", url, method, c.getResponseCode()));
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((c.getInputStream())));
			return responseProcessor.process(br);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (c != null) {
				c.disconnect();
			}
		}
	}
	
	private byte[] toPostData(Object data) {
		Gson gson = new GsonBuilder().create();
		String postData;
		if (data instanceof Map) {
			postData = gson.toJson(data, new TypeToken>() {}.getType());
		} else {
			postData = gson.toJson(data);
		}
		try {
			return postData.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	private String appendQueryParams(String url, Map params) {
		List pairs = new ArrayList();
		for (Entry entry : params.entrySet()) {
			Object entryVal = entry.getValue();
			pairs.add(new BasicNameValuePair(entry.getKey(), entryVal == null ? null : entryVal.toString()));
		}
		return url + "?" + URLEncodedUtils.format(pairs, "UTF-8");
	}
	
	private interface ResponseProcessor {
		
		R process(Reader r);
		
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy