2d2e2da03af85f072617f0ca28565e030531d9e3
[SpringWebServicesForFun/.git] /
1 package de.spring.webservices.rest.client;
2
3 import java.net.URI;
4 import java.util.Arrays;
5 import java.util.List;
6
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;
14
15 import de.spring.webservices.domain.Car;
16
17 @Service("carClientService")
18 public class CarClientService {
19         private static final Logger LOGGER = LoggerFactory.getLogger(CarClientService.class);
20
21         private final String apiCarsUrl;
22         private final String apiCarUrl;
23         private final RestTemplate restTemplate;
24         
25     @Autowired
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;
31         }
32
33         
34         public List<Car> doGetCars() {                          
35                 ResponseEntity<Car[]> responseEntity = restTemplate.getForEntity(apiCarsUrl, Car[].class);
36                 
37                 return Arrays.asList(responseEntity.getBody());
38         }
39         
40         public Car doGetCar(long id) {                          
41                 ResponseEntity<Car> responseEntity = restTemplate.getForEntity(
42                                 apiCarUrl.replace(":id", String.valueOf(id)), Car.class);
43                 
44                 return responseEntity.getBody();
45         }
46         
47
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());
52                         
53                 return responseEntity.getBody();
54         }
55 }