84 lines
2.9 KiB
Java
84 lines
2.9 KiB
Java
package org.hso.ecommerce.api;
|
|
|
|
import org.hso.ecommerce.app.config.AppSettings;
|
|
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.HashMap;
|
|
import java.util.Map;
|
|
|
|
@Service
|
|
public class RestServiceForDelivery {
|
|
|
|
@Autowired
|
|
private final RestTemplateBuilder restTemplateBuilder = null;
|
|
|
|
@Autowired
|
|
private final AppSettings settings = null;
|
|
|
|
private String getDeliveryEndpoint() {
|
|
return settings.getParcelServiceApiURL();
|
|
}
|
|
|
|
|
|
public String getDeliveryID(CustomerOrder customerOrder) throws ResourceAccessException {
|
|
String url = getDeliveryEndpoint() + "/newDelivery";
|
|
|
|
RestTemplate restTemplate = restTemplateBuilder.build();
|
|
|
|
HttpHeaders headers = new HttpHeaders();
|
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
|
|
|
Map<String, String> requestBody = new HashMap<>();
|
|
|
|
requestBody.put("name", customerOrder.destination.name);
|
|
requestBody.put("address", customerOrder.destination.addressString);
|
|
|
|
HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestBody, headers);
|
|
|
|
ResponseEntity<String> 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(String trackingID) {
|
|
|
|
String url = getDeliveryEndpoint() + "/status";
|
|
|
|
RestTemplate restTemplate = restTemplateBuilder.build();
|
|
|
|
HttpHeaders headers = new HttpHeaders();
|
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
|
|
|
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("trackingID", trackingID);
|
|
|
|
HttpEntity<?> entity = new HttpEntity<>(headers);
|
|
|
|
ResponseEntity<DeliveryData> 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 (Exception e) {
|
|
return new DeliveryData("", "", DeliveryDataEnum.NO_DATA);
|
|
}
|
|
}
|
|
}
|