-
Notifications
You must be signed in to change notification settings - Fork 41
/
CloudSalesOrderService.java
348 lines (288 loc) · 12.9 KB
/
CloudSalesOrderService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package com.sap.refapps.espm.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Optional;
import jakarta.jms.Connection;
import jakarta.jms.JMSException;
import jakarta.jms.MessageProducer;
import jakarta.jms.Queue;
import jakarta.jms.Session;
import jakarta.jms.TextMessage;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sap.cloud.security.xsuaa.client.OAuth2TokenResponse;
import com.sap.cloud.security.xsuaa.tokenflows.TokenFlowException;
import com.sap.cloud.security.xsuaa.tokenflows.XsuaaTokenFlows;
import com.sap.cloud.servicesdk.xbem.extension.sapcp.jms.MessagingServiceJmsConnectionFactory;
import com.sap.refapps.espm.model.SalesOrder;
import com.sap.refapps.espm.model.SalesOrderRepository;
import com.sap.refapps.espm.model.Tax;
import com.sap.refapps.espm.util.ResilienceHandler;
import com.sap.refapps.espm.util.SalesOrderLifecycleStatusEnum;
import com.sap.refapps.espm.util.SalesOrderLifecycleStatusNameEnum;
/**
* Implementation class for the sales order service, deployable in cloud
* environment.
*
*/
@Profile("cloud")
@Service
public class CloudSalesOrderService extends AbstractSalesOrderService {
private static final Logger logger = LoggerFactory.getLogger(CloudSalesOrderService.class);
@Value("${tax.destinationName}")
private String taxDestination;
private String taxUri;
private final ObjectMapper mapper = new ObjectMapper();
private HashMap<String, String> taxUrlCache = new HashMap<>(1);
private final HttpHeaders headers = new HttpHeaders();
private final String taxEndPointSuffix = "/tax.svc/api/v1/calculate/tax?amount=";
private static final String DESTINATION = "destination";
private static final String TOKEN_ENDPOINT = "/oauth/token";
private static final String AUTHORIZATION = "Authorization";
private static final String CONTENT_TYPE = "Content-Type";
private static final String GRANT_TYPE = "grant_type=";
private static final String CLIENT_CREDENTIALS = "client_credentials";
private static final String UTF8 = "UTF-8";
private static final String ACCESS_TOKEN = "access_token";
private static final String DESTINATION_ENDPOINT = "/destination-configuration/v1/destinations/";
private static final String DESTINATION_CONFIG = "destinationConfiguration";
private String accessToken;
private DestinationService destination;
@Autowired(required = false)
private MessagingServiceJmsConnectionFactory jmsConnectionFactory;
@Autowired
private XsuaaTokenFlows xsuaaTokenFlows;
/**
* @param salesOrderRepository
* @param rest
*/
@Autowired
public CloudSalesOrderService(final SalesOrderRepository salesOrderRepository, final RestTemplate rest,
final ResilienceHandler resilienceHandler) {
super(salesOrderRepository, rest, resilienceHandler);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Override
public void insert(final SalesOrder salesOrder)
throws JsonProcessingException, UnsupportedEncodingException, JMSException {
final BigDecimal netAmount;
Date now = new Date();
DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
// create MathContext object with 4 precision
MathContext mc = new MathContext(15);
final Tax tax = getTax(salesOrder.getGrossAmount());
netAmount = tax.getTaxAmount().add(salesOrder.getGrossAmount(), mc);
salesOrder.setLifecycleStatus(SalesOrderLifecycleStatusEnum.N.toString());
salesOrder.setLifecycleStatusName(SalesOrderLifecycleStatusNameEnum.N.toString());
salesOrder.setNetAmount(netAmount);
salesOrder.setTaxAmount(tax.getTaxAmount());
salesOrder.setQuantityUnit("EA");
salesOrder.setCreatedAt(dateFormat.format(now));
final ObjectMapper mapper = new ObjectMapper();
final String salesOrderString = mapper.writeValueAsString(salesOrder);
sendMessage(salesOrderString);
}
@Override
public Tax supplyTax(BigDecimal amount) {
Tax tax;
taxUri = taxUrlCache.get("TAX_URI");
if (taxUri == null) {
taxUri = getTaxUri();
taxUrlCache.put("TAX_URI", taxUri);
}
if (taxUri == "") {
logger.info("Calling fall back Tax calculation as Tax destination is not found");
tax = resilienceHandler.applyResiliencePatterns(amount);
} else {
URI uri = URI.create(taxUri + amount);
HttpEntity entity = new HttpEntity(evaluateTokenAndAuthorizeClient());
try {
// If Tax URI does not work check again in the destination if the URL in
// destination has changed.
taxUri = getTaxUri();
taxUrlCache.put("TAX_URI", taxUri);
uri = URI.create(taxUri + amount);
ResponseEntity<Tax> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, entity, Tax.class);
tax = responseEntity.getBody();
} catch (HttpClientErrorException e) {
logger.info("Retrying to connect to the tax service...");
uri = URI.create(taxUri + amount);
ResponseEntity<Tax> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, entity, Tax.class);
tax = responseEntity.getBody();
}
}
logger.info("Tax service endpoint is {}", taxUri);
logger.info("Tax service is called to calculate tax for amount : {}", amount);
logger.info("Tax amount is : {}", tax.getTaxAmount());
return tax;
}
private HttpHeaders evaluateTokenAndAuthorizeClient() {
OAuth2TokenResponse clientCredentialsTokenResponse = null;
try {
// client credentials flow
clientCredentialsTokenResponse = xsuaaTokenFlows.clientCredentialsTokenFlow().execute();
} catch (TokenFlowException e) {
logger.error("Couldn't get client credentials token: {}", e.getMessage());
} catch (Exception e) {
logger.error("Please contact the administrator for details: {}", e.getMessage());
}
String appToken = clientCredentialsTokenResponse.getAccessToken();
headers.set("Authorization", "Bearer " + appToken);
return headers;
}
private String getTaxUri() {
String taxUrl = getTaxUrlFromDestinationService() + taxEndPointSuffix;
logger.info("***********Tax microservice endpoint is {}********", taxUrl);
return taxUrl;
}
private String getTaxUrlFromDestinationService() {
Optional<String> destinationUrl = Optional.empty();
try {
Optional<String> destinationConfigDetails = getDestinationConfiguration();
ObjectMapper mapper = new ObjectMapper();
JsonNode vcap = mapper.readTree(destinationConfigDetails.get());
JsonNode destinationConfiguration = vcap.get(DESTINATION_CONFIG);
destinationUrl = Optional.of(destinationConfiguration.get("URL").asText());
} catch(IOException io) {
logger.error(io.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
}
return destinationUrl.get();
}
/**
* Sends a request to get the destination configuration details by authorizing user with a bearer token
* and returns the details.
*
* @return
* @throws IOException
*/
private Optional<String> getDestinationConfiguration() throws IOException {
Optional<String> destinationConfig = Optional.empty();
destination = getDestinationServiceDetails(DESTINATION);
final String destinationRequestUrl = destination.uri + DESTINATION_ENDPOINT + taxDestination;
logger.info("Fetching the destination configuration attributes using the request url {}", destinationRequestUrl);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(destinationRequestUrl);
httpGet.setHeader(HttpHeaders.CONTENT_TYPE,"application/json");
logger.info("Authorizing user with bearer token...");
httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken());
HttpResponse response = httpClient.execute(httpGet);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), UTF8));
destinationConfig = Optional.of(br.readLine());
return destinationConfig;
}
/**
* Reads the access token content returned by the api authorizeAndConfigureNewToken(),
* fetches the access token and returns it.
*
* @return String
*/
private String getAccessToken() {
Optional<String> accessTokenContent = Optional.empty();
try {
accessTokenContent = authorizeAndConfigureNewToken();
if(accessTokenContent.isPresent()) {
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String,String>>() {};
HashMap<String, String> hashMap = mapper.readValue(accessTokenContent.get(), typeRef);
accessToken = hashMap.get(ACCESS_TOKEN);
}
} catch (JsonParseException e) {
logger.error(e.getMessage());
} catch (JsonMappingException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
return accessToken;
}
/**
*
* Authorizes user and configures a new access token using client credentials as the grant type.
* Returns the complete content of an access token.
*
* @return
* @throws JsonProcessingException
* @throws IOException
*/
private Optional<String> authorizeAndConfigureNewToken() throws JsonProcessingException, IOException {
destination = getDestinationServiceDetails(DESTINATION);
Optional<String> tokenContent = Optional.empty();
final String tokenURL = destination.url + TOKEN_ENDPOINT;
// authentication credentials encoding
String base64Credentials = Base64.getEncoder().encodeToString(
(destination.clientid + ":" + destination.clientsecret).getBytes());
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(tokenURL);
logger.info("Generates new token using client credentials...");
httpPost.addHeader(AUTHORIZATION, "Basic " + base64Credentials);
httpPost.addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded");
StringEntity input = new StringEntity(GRANT_TYPE + CLIENT_CREDENTIALS);
httpPost.setEntity(input);
//send and retrieve response
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), UTF8));
tokenContent = Optional.of(br.readLine());
return tokenContent;
}
private DestinationService getDestinationServiceDetails(String node) throws IOException {
final String destinationService = System.getenv("VCAP_SERVICES");
final JsonNode root = mapper.readTree(destinationService);
final JsonNode destinations = root.get(node).get(0).get("credentials");
final DestinationService destination = mapper.treeToValue(destinations, DestinationService.class);
return destination;
}
private synchronized void sendMessage(final String messageString) throws JMSException {
final Connection connection = jmsConnectionFactory.createConnection();
connection.start();
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Queue queue = session.createQueue("queue:" + System.getenv("QUEUE_NAME"));
final MessageProducer messageProducer = session.createProducer(queue);
TextMessage message = session.createTextMessage(messageString);
messageProducer.send(message);
session.close();
connection.close();
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
class DestinationService {
public String clientid;
public String clientsecret;
public String uri;
public String url;
}