bdb540b8e49136fbec1a4da05994040151319240
[SpringWebServicesForFun/.git] /
1 package de.spring.webservices.rest.client.service.impl;
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 import de.spring.webservices.rest.client.service.CarClientService;
17
18 @Service("carClientService")
19 public class CarClientServiceImpl implements CarClientService {
20         private static final Logger LOGGER = LoggerFactory.getLogger(CarClientServiceImpl.class);
21
22         private final String apiCarsUrl;
23         private final String apiCarUrl;
24         private final RestTemplate restTemplate;
25         
26     @Autowired
27         public CarClientServiceImpl(@Value("${url.base}${url.cars}") String apiCarsUrl,
28                         @Value("${url.base}${url.car}") String apiCarUrl, RestTemplate restTemplate) {
29                 this.apiCarsUrl = apiCarsUrl;
30                 this.apiCarUrl = apiCarUrl;
31                 this.restTemplate = restTemplate;
32         }
33
34         
35     @Override
36         public List<Car> doGetCars() {                          
37                 ResponseEntity<Car[]> responseEntity = restTemplate.getForEntity(apiCarsUrl, Car[].class);
38                 
39                 return Arrays.asList(responseEntity.getBody());
40         }
41         
42     @Override
43         public Car doGetCar(long id) {                          
44                 ResponseEntity<Car> responseEntity = restTemplate.getForEntity(
45                                 apiCarUrl.replace(":id", String.valueOf(id)), Car.class);
46                 
47                 return responseEntity.getBody();
48         }
49         
50     @Override
51         public Car doNewCar(Car car) {          
52                 ResponseEntity<Car> responseEntity = restTemplate.postForEntity(apiCarsUrl, car, Car.class);
53                 URI newCarLocation = responseEntity.getHeaders().getLocation();
54                 LOGGER.info("new car location: " + newCarLocation.getPath());
55                         
56                 return responseEntity.getBody();
57         }
58 }