1 package de.spring.webservices.rest.client;
4 import java.util.Arrays;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.beans.factory.annotation.Value;
11 import org.springframework.http.ResponseEntity;
12 import org.springframework.stereotype.Service;
13 import org.springframework.web.client.RestTemplate;
15 import de.spring.webservices.domain.Car;
17 @Service("carClientService")
18 public class CarClientService {
19 private static final Logger LOGGER = LoggerFactory.getLogger(CarClientService.class);
21 private final String apiCarsUrl;
22 private final String apiCarUrl;
23 private final RestTemplate restTemplate;
26 public CarClientService(@Value("${url.base}${url.cars}") String apiCarsUrl,
27 @Value("${url.base}${url.car}") String apiCarUrl, RestTemplate restTemplate) {
28 this.apiCarsUrl = apiCarsUrl;
29 this.apiCarUrl = apiCarUrl;
30 this.restTemplate = restTemplate;
34 public List<Car> doGetCars() {
35 ResponseEntity<Car[]> responseEntity = restTemplate.getForEntity(apiCarsUrl, Car[].class);
37 return Arrays.asList(responseEntity.getBody());
40 public Car doGetCar(long id) {
41 ResponseEntity<Car> responseEntity = restTemplate.getForEntity(
42 apiCarUrl.replace(":id", String.valueOf(id)), Car.class);
44 return responseEntity.getBody();
48 public Car doNewCar(Car car) {
49 ResponseEntity<Car> responseEntity = restTemplate.postForEntity(apiCarsUrl, car, Car.class);
50 URI newCarLocation = responseEntity.getHeaders().getLocation();
51 LOGGER.info("new car location: " + newCarLocation.getPath());
53 return responseEntity.getBody();