social-service-client/src/main/java/org/gcube/portal/social_networking_client_li.../utils/HttpClient.java

88 lines
2.9 KiB
Java

package org.gcube.portal.social_networking_client_library.utils;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import org.gcube.portal.social_networking_client_library.filter.AuthorizationFilter;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
/**
* Http client with post and get methods (jersey is used)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class HttpClient{
private static Logger logger = LoggerFactory.getLogger(HttpClient.class);
/**
* Executes a get request
* @param genericType
* @param genericType
* @param genericType
* @param returnType
* @param requestUrl
* @param token
* @return
*/
public static <R> R get(GenericType<ResponseBean<R>> returnType, String requestUrl){
logger.debug("Executing get request at url " + requestUrl);
ClientConfig cc = new ClientConfig().register(new JacksonFeature()).register(new AuthorizationFilter());
Client client = ClientBuilder.newClient(cc);
WebTarget webResourceGet = client.target(requestUrl);
ResponseBean<R> response = webResourceGet.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(returnType);
if(response == null)
throw new WebApplicationException("Response returned by the service is null");
if (response.getMessage() != null && !response.getMessage().isEmpty())
throw new WebApplicationException(
"Error message is " + response.getMessage());
return response.getResult();
}
/**
* Executes a post request
* @param returnType
* @param requestUrl
* @param token
* @param body
* @return
* @throws JsonProcessingException
*/
public static <R> R post(GenericType<ResponseBean<R>> returnType, String requestUrl, Object obj){
logger.debug("Executing post request at url " + requestUrl);
ClientConfig cc = new ClientConfig().register(new JacksonFeature()).register(new AuthorizationFilter());
Client client = ClientBuilder.newClient(cc);
WebTarget webResourceGet = client.target(requestUrl);
logger.debug("Entity looks like " + Entity.json(obj));
ResponseBean<R> response = webResourceGet.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(Entity.json(obj), returnType);
if(response == null)
throw new WebApplicationException("Response returned by the service is null");
if (response.getMessage() != null && !response.getMessage().isEmpty())
throw new WebApplicationException(
"Error message is " + response.getMessage());
return response.getResult();
}
}