package org.hso.ecommerce.api; import org.hso.ecommerce.entities.shop.CustomerOrder; import org.hso.ecommerce.uimodel.DeliveryData; import org.hso.ecommerce.uimodel.DeliveryDataEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.util.*; @Service public class RestServiceForDelivery { @Autowired private final RestTemplateBuilder restTemplateBuilder = null; private final String DELIVERY_IP_ADDRESS = "http://[::1]:8082"; public String getDeliveryID(CustomerOrder customerOrder) throws ResourceAccessException { String url = DELIVERY_IP_ADDRESS + "/newDelivery"; RestTemplate restTemplate = restTemplateBuilder.build(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map requestBody = new HashMap<>(); requestBody.put("name",customerOrder.destination.name); requestBody.put("address",customerOrder.destination.addressString); HttpEntity> entity = new HttpEntity<>(requestBody,headers); ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST,entity, String.class); if (response.getStatusCode() == HttpStatus.OK) { return response.getBody(); } else { throw new ResourceAccessException("Http Status wrong"); } } public DeliveryData getDeliveryData(UUID trackingID) { String url = DELIVERY_IP_ADDRESS + "/status"; RestTemplate restTemplate = restTemplateBuilder.build(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("trackingID",trackingID.toString()); HttpEntity entity = new HttpEntity<>(headers); ResponseEntity response; try { response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, DeliveryData.class); if (response.getStatusCode() == HttpStatus.OK) { return response.getBody(); } else { return new DeliveryData("","",DeliveryDataEnum.NO_DATA); } } catch (ResourceAccessException e) { return new DeliveryData("","",DeliveryDataEnum.NO_DATA); } } }