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

org.jlot.client.remote.rest.AbstractRestCommand Maven / Gradle / Ivy

There is a newer version: 1.2
Show newest version
package org.jlot.client.remote.rest;

import javax.inject.Inject;

import org.jlot.api.RestError;
import org.jlot.client.configuration.ProjectConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

public abstract class AbstractRestCommand implements RestCommand
{
	private static final Logger		log	= LoggerFactory.getLogger(AbstractRestCommand.class);
	@Inject
	private ProjectConfiguration	projectConfiguration;
	@Inject
	private RestTemplate			restTemplate;
	@Inject
	private ObjectMapper			objectMapper;

	@Override
	public R execute ( T object ) throws RestException
	{
		try
		{
			return executeInternal(object);
		}
		catch (HttpClientErrorException e)
		{
			log.debug(e.getResponseBodyAsString());
			RestError restError = readRestError(e.getResponseBodyAsString());
			throw new RestException(restError);
		}
		catch (HttpServerErrorException e)
		{
			log.debug(e.getResponseBodyAsString());
			log.debug(e.getMessage(), e);
			throw e;
		}
	}

	private RestError readRestError ( String json )
	{
		try
		{
			return objectMapper.readValue(json, RestError.class);
		}
		catch (Exception e)
		{
			throw new IllegalStateException(e);
		}
	}

	protected abstract R executeInternal ( T object );

	protected abstract String getPath ( );

	protected String getUrl ( )
	{
		StringBuffer url = new StringBuffer();
		url.append(projectConfiguration.getServerUrl());
		url.append("api");
		url.append(getPath());
		return url.toString();
	}

	protected RestTemplate getRestTemplate ( )
	{
		return restTemplate;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy