2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
24 import java.io.BufferedReader;
25 import java.io.ByteArrayInputStream;
27 import java.io.FileInputStream;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.OutputStreamWriter;
31 import java.lang.reflect.Field;
32 import java.lang.reflect.InvocationTargetException;
33 import java.lang.reflect.Method;
34 import java.lang.reflect.Modifier;
35 import java.net.HttpURLConnection;
36 import java.net.MalformedURLException;
38 import java.nio.charset.StandardCharsets;
39 import java.security.KeyManagementException;
40 import java.security.KeyStore;
41 import java.security.NoSuchAlgorithmException;
42 import java.text.SimpleDateFormat;
43 import java.util.Properties;
45 import javax.net.ssl.HostnameVerifier;
46 import javax.net.ssl.HttpsURLConnection;
47 import javax.net.ssl.KeyManagerFactory;
48 import javax.net.ssl.SSLContext;
49 import javax.net.ssl.SSLSession;
50 import javax.net.ssl.SSLSocketFactory;
51 import javax.ws.rs.HttpMethod;
53 import org.apache.commons.codec.binary.Base64;
54 import org.onap.ccsdk.sli.adaptors.aai.AAIService.TransactionIdTracker;
55 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
56 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
57 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
58 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
59 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
60 import org.onap.ccsdk.sli.core.sli.MetricLogger;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 import com.fasterxml.jackson.databind.DeserializationFeature;
65 import com.fasterxml.jackson.databind.ObjectMapper;
66 import com.sun.jersey.api.client.config.DefaultClientConfig;
67 import com.sun.jersey.client.urlconnection.HTTPSProperties;
68 import org.apache.http.impl.EnglishReasonPhraseCatalog;
71 * The AAIClientRESTExecutor class provides CRUD API for AAI Client service.
72 * @author richtabedzki
74 public class AAIClientRESTExecutor implements AAIExecutorInterface {
76 private final String truststorePath;
77 private final String truststorePassword;
78 private final String keystorePath;
79 private final String keystorePassword;
80 private final Boolean ignoreCertificateHostError;
81 // authentication credentials
82 private String userName;
83 private String userPassword;
84 private final String applicationId;
88 * @param props - properties to initialize an instance.
90 public AAIClientRESTExecutor(Properties props) {
93 userName = props.getProperty(AAIService.CLIENT_NAME);
94 userPassword = props.getProperty(AAIService.CLIENT_PWWD);
96 if(userName == null || userName.isEmpty()){
97 LOG.debug("Basic user name is not set");
99 if(userPassword == null || userPassword.isEmpty()) {
100 LOG.debug("Basic password is not set");
103 truststorePath = props.getProperty(AAIService.TRUSTSTORE_PATH);
104 truststorePassword = props.getProperty(AAIService.TRUSTSTORE_PSSWD);
105 keystorePath = props.getProperty(AAIService.KEYSTORE_PATH);
106 keystorePassword = props.getProperty(AAIService.KEYSTORE_PSSWD);
108 String tmpApplicationId =props.getProperty(AAIService.APPLICATION_ID);
109 if(tmpApplicationId == null || tmpApplicationId.isEmpty()) {
110 tmpApplicationId = "SDNC";
112 applicationId = tmpApplicationId;
114 String iche = props.getProperty(AAIService.CERTIFICATE_HOST_ERROR);
115 boolean host_error = false;
116 if(iche != null && !iche.isEmpty()) {
117 host_error = Boolean.valueOf(iche);
120 ignoreCertificateHostError = host_error;
122 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
123 public boolean verify(String string,SSLSession ssls) {
124 return ignoreCertificateHostError;
128 if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) {
129 System.setProperty("javax.net.ssl.trustStore", truststorePath);
130 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
133 if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).exists())
135 DefaultClientConfig config = new DefaultClientConfig();
136 //both jersey and HttpURLConnection can use this
137 SSLContext ctx = null;
139 ctx = SSLContext.getInstance("TLS");
141 KeyManagerFactory kmf = null;
142 try (FileInputStream fin = new FileInputStream(keystorePath)){
143 String storeType = "PKCS12";
144 String def = KeyStore.getDefaultType();
145 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
147 String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1);
149 if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
152 KeyStore ks = KeyStore.getInstance(storeType);
154 char[] pwd = keystorePassword.toCharArray();
157 } catch (Exception ex) {
158 LOG.error("AAIResource", ex);
161 ctx.init(kmf.getKeyManagers(), null, null);
162 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
164 public boolean verify( String s, SSLSession sslSession ) {
165 return ignoreCertificateHostError;
170 LOG.debug("SSLContext created");
172 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
173 LOG.error("AAIResource", exc);
178 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
179 methodsField.setAccessible(true);
180 // get the methods field modifiers
181 Field modifiersField = Field.class.getDeclaredField("modifiers");
182 // bypass the "private" modifier
183 modifiersField.setAccessible(true);
185 // remove the "final" modifier
186 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
188 /* valid HTTP methods */
190 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
192 // set the new methods - including patch
193 methodsField.set(null, methods);
195 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
196 LOG.warn("Adding PATCH method", e);
198 LOG.info("AAIResource.ctor initialized.");
202 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
203 private static final String NOT_PROVIDED = "NOT PROVIDED";
204 private final MetricLogger ml = new MetricLogger();
206 private SSLContext CTX;
209 private int connection_timeout = 300000;
211 private int read_timeout = 300000;
214 * Returns an String that contains JSON data returned from the AAI Server.
216 * This method always returns immediately, whether or not the
219 * @param request an instance of AAIRequiest representing
220 * the request made by DirectedGraph node.
221 * @return the JSON based representation of data instance requested.
225 public String get(AAIRequest request) throws AAIServiceException {
226 String response = null;
227 InputStream inputStream = null;
228 HttpURLConnection con = null;
229 URL requestUrl = null;
231 StringBuilder errorStringBuilder = new StringBuilder();
235 if(request.getRequestObject() != null) {
236 requestUrl = request.getRequestUrl(HttpMethod.POST, null);
237 requestUrl = appendDepth(requestUrl, request);
238 con = getConfiguredConnection(requestUrl, HttpMethod.POST);
239 String json_text = request.toJSONString();
240 LOGwriteDateTrace("data", json_text);
241 logMetricRequest("POST "+requestUrl.getPath(), json_text, requestUrl.getPath());
242 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
243 osw.write(json_text);
246 requestUrl = request.getRequestUrl(HttpMethod.GET, null);
247 requestUrl = appendDepth(requestUrl, request);
248 con = getConfiguredConnection(requestUrl, HttpMethod.GET);
249 logMetricRequest("GET "+requestUrl.getPath(), "", requestUrl.getPath());
253 int responseCode = con.getResponseCode();
254 if (responseCode == HttpURLConnection.HTTP_OK) {
255 inputStream = con.getInputStream();
257 inputStream = con.getErrorStream();
259 String responseMessage = null;
261 responseMessage = con.getResponseMessage();
262 } catch(Exception exc) {
263 responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
264 if(responseMessage == null)
265 responseMessage = NOT_PROVIDED;
268 // Process the response
269 LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
270 logMetricResponse(responseCode, responseMessage);
272 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
273 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
275 ObjectMapper mapper = AAIService.getObjectMapper();
277 if (responseCode == HttpURLConnection.HTTP_OK) {
278 StringBuilder stringBuilder = new StringBuilder();
280 while( ( line = reader.readLine() ) != null ) {
281 stringBuilder.append( line );
283 response = stringBuilder.toString();
285 Object object = mapper.readValue(response, Object.class);
286 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
287 } catch(Exception exc) {
288 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
290 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
291 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
292 ErrorResponse errorresponse = null;
294 errorresponse = mapper.readValue(reader, ErrorResponse.class);
295 } catch(Exception exc) {
296 errorresponse = new ErrorResponse();
297 RequestError requestError = new RequestError();
298 ServiceException serviceException = new ServiceException();
299 serviceException.setText("Entry does not exist.");
300 requestError.setServiceException(serviceException);
301 errorresponse.setRequestError(requestError );
303 throw new AAIServiceException(responseCode, errorresponse);
304 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
305 StringBuilder stringBuilder = new StringBuilder();
307 while( ( line = reader.readLine() ) != null ) {
308 stringBuilder.append( line );
310 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
311 ServiceException serviceException = new ServiceException();
312 serviceException.setMessageId("HTTP_UNAUTHORIZED");
313 serviceException.setText(stringBuilder.toString());
314 RequestError requestError = new RequestError();
315 requestError.setServiceException(serviceException);
316 ErrorResponse errorresponse = new ErrorResponse();
317 errorresponse.setRequestError(requestError);
318 throw new AAIServiceException(responseCode, errorresponse);
321 while( ( line = reader.readLine() ) != null ) {
322 errorStringBuilder.append("\n").append( line );
325 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
326 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
327 throw new AAIServiceException(responseCode, errorresponse);
330 } catch(AAIServiceException aaiexc) {
332 } catch (Exception exc) {
333 LOG.warn(errorStringBuilder.toString(), exc);
334 throw new AAIServiceException(exc);
336 if(inputStream != null){
339 } catch(Exception exc) {
348 * Returns an String that contains JSON data returned from the AAI Server.
350 * This method always returns immediately, whether or not the
353 * @param request an instance of AAIRequiest representing
354 * the request made by DirectedGraph node.
355 * @return the JSON based representation of data instance requested.
359 public String post(AAIRequest request) throws AAIServiceException {
360 InputStream inputStream = null;
363 String resourceVersion = null;
364 AAIDatum instance = request.getRequestObject();
367 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
368 if(getResourceVersionMethod != null){
370 Object object = getResourceVersionMethod.invoke(instance);
372 resourceVersion = object.toString();
373 } catch (InvocationTargetException exc) {
377 } catch(Exception exc) {
381 URL requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion);
382 HttpURLConnection con = getConfiguredConnection(requestUrl, HttpMethod.PUT);
383 ObjectMapper mapper = AAIService.getObjectMapper();
384 String jsonText = request.toJSONString();
386 LOGwriteDateTrace("data", jsonText);
387 logMetricRequest("PUT "+requestUrl.getPath(), jsonText, requestUrl.getPath());
389 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
394 int responseCode = con.getResponseCode();
395 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
396 inputStream = con.getInputStream();
398 inputStream = con.getErrorStream();
400 String responseMessage = null;
402 responseMessage = con.getResponseMessage();
403 } catch(Exception exc) {
404 responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
405 if(responseMessage == null)
406 responseMessage = NOT_PROVIDED;
409 LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
410 logMetricResponse(responseCode, responseMessage);
412 // Process the response
413 BufferedReader reader;
415 reader = new BufferedReader( new InputStreamReader( inputStream ) );
416 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
418 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
419 StringBuilder stringBuilder = new StringBuilder();
421 while( ( line = reader.readLine() ) != null ) {
422 stringBuilder.append( line );
424 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
425 return stringBuilder.toString();
427 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
428 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
430 throw new AAIServiceException(responseCode, errorresponse);
432 } catch(AAIServiceException aaiexc) {
434 } catch (Exception exc) {
435 LOG.warn("AAIRequestExecutor.post", exc);
436 throw new AAIServiceException(exc);
439 if(inputStream != null)
441 } catch (Exception exc) {
442 LOG.warn("AAIRequestExecutor.post", exc);
448 * Returns Boolean that contains completion state of the command executed.
450 * This method always returns immediately, whether or not the
453 * @param request an instance of AAIRequiest representing
454 * @param resourceVersion a resource version of the data instacne to be deleted.
455 * the request made by DirectedGraph node.
456 * @return completion state of the command.
460 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
461 Boolean response = null;
462 InputStream inputStream = null;
464 if(resourceVersion == null) {
465 throw new AAIServiceException("resource-version is required for DELETE request");
469 URL requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion);
470 HttpURLConnection conn = getConfiguredConnection(requestUrl, HttpMethod.DELETE);
471 logMetricRequest("DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
472 conn.setDoOutput(true);
475 int responseCode = conn.getResponseCode();
476 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
477 inputStream = conn.getInputStream();
479 inputStream = conn.getErrorStream();
481 String responseMessage = null;
483 responseMessage = conn.getResponseMessage();
484 } catch(Exception exc) {
485 responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
486 if(responseMessage == null)
487 responseMessage = NOT_PROVIDED;
490 // Process the response
491 LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
492 logMetricResponse(responseCode, responseMessage);
494 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
495 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
498 ObjectMapper mapper = AAIService.getObjectMapper();
500 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
501 StringBuilder stringBuilder = new StringBuilder();
503 while( ( line = reader.readLine() ) != null ) {
504 stringBuilder.append( line );
506 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
508 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
509 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
512 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
513 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
514 throw new AAIServiceException(responseCode, errorresponse);
516 } catch(AAIServiceException aaiexc) {
518 } catch (Exception exc) {
519 LOG.warn("delete", exc);
520 throw new AAIServiceException(exc);
522 if(inputStream != null){
525 } catch(Exception exc) {
526 LOG.warn("delete", exc);
534 * Returns an String that contains JSON data returned from the AAI Server.
536 * This method always returns immediately, whether or not the
539 * @param request an instance of AAIRequiest representing
540 * the request made by DirectedGraph node.
541 * @param clas an definition of the class for which data will be returned
542 * @return the instance of the class with data.
546 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
547 Object response = null;
548 InputStream inputStream = null;
551 URL requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
552 HttpURLConnection con = getConfiguredConnection(requestUrl, HttpMethod.GET);
553 logMetricRequest("GET "+requestUrl.getPath(), "", requestUrl.getPath());
556 int responseCode = con.getResponseCode();
557 if (responseCode == HttpURLConnection.HTTP_OK) {
558 inputStream = con.getInputStream();
560 inputStream = con.getErrorStream();
562 String responseMessage = null;
564 responseMessage = con.getResponseMessage();
565 } catch(Exception exc) {
566 responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
567 if(responseMessage == null)
568 responseMessage = NOT_PROVIDED;
571 LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
572 logMetricResponse(responseCode, responseMessage);
573 ObjectMapper mapper = AAIService.getObjectMapper();
575 if (responseCode == HttpURLConnection.HTTP_OK) {
576 // Process the response
577 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
578 response = mapper.readValue(reader, clas);
579 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
580 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
581 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
584 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
585 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
586 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
587 throw new AAIServiceException(responseCode, errorresponse);
590 } catch(AAIServiceException aaiexc) {
592 } catch (Exception exc) {
593 LOG.warn("GET", exc);
594 throw new AAIServiceException(exc);
596 if(inputStream != null){
599 } catch(Exception exc) {
600 LOG.warn("GET", exc);
608 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
609 InputStream inputStream = null;
612 AAIDatum instance = request.getRequestObject();
613 if(instance instanceof ResourceVersion) {
614 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
617 URL requestUrl = null;
618 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
619 ObjectMapper mapper = AAIService.getObjectMapper();
620 String jsonText = request.toJSONString();
622 LOGwriteDateTrace("data", jsonText);
623 logMetricRequest("PATCH "+requestUrl.getPath(), jsonText, requestUrl.getPath());
625 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
630 int responseCode = con.getResponseCode();
631 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
632 inputStream = con.getInputStream();
634 inputStream = con.getErrorStream();
636 String responseMessage = null;
638 responseMessage = con.getResponseMessage();
639 } catch(Exception exc) {
640 responseMessage = EnglishReasonPhraseCatalog.INSTANCE.getReason(responseCode,null);
641 if(responseMessage == null)
642 responseMessage = NOT_PROVIDED;
645 LOG.info("HttpURLConnection result: {} : {}", responseCode, responseMessage);
646 logMetricResponse(responseCode, responseMessage);
648 // Process the response
649 BufferedReader reader;
651 reader = new BufferedReader( new InputStreamReader( inputStream ) );
652 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
654 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
655 StringBuilder stringBuilder = new StringBuilder();
657 while( ( line = reader.readLine() ) != null ) {
658 stringBuilder.append( line );
660 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
663 StringBuilder stringBuilder = new StringBuilder();
665 while( ( line = reader.readLine() ) != null ) {
666 stringBuilder.append("\n").append( line );
668 LOG.info(stringBuilder.toString());
671 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
672 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
674 throw new AAIServiceException(responseCode, errorresponse);
676 } catch(AAIServiceException aaiexc) {
678 } catch (Exception exc) {
679 LOG.warn("AAIRequestExecutor.patch", exc);
680 throw new AAIServiceException(exc);
683 if(inputStream != null)
685 } catch (Exception exc) {
686 LOG.warn("AAIRequestExecutor.patch", exc);
698 protected HttpURLConnection getConfiguredConnection(URL httpReqUrl, String method) throws Exception {
699 HttpURLConnection con = (HttpURLConnection) httpReqUrl.openConnection();
701 // Set up the connection properties
702 con.setRequestProperty("Connection", "close");
703 con.setDoInput(true);
704 con.setDoOutput(true);
705 con.setUseCaches(false);
706 con.setConnectTimeout(connection_timeout);
707 con.setReadTimeout(read_timeout);
708 con.setRequestMethod(method);
709 con.setRequestProperty("Accept", "application/json");
710 con.setRequestProperty("Transfer-Encoding","chunked");
711 con.setRequestProperty("Content-Type",
712 "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json");
713 con.setRequestProperty("X-FromAppId", applicationId);
714 con.setRequestProperty("X-TransactionId", TransactionIdTracker.getNextTransactionId());
715 String mlId = ml.getRequestID();
716 if (mlId != null && !mlId.isEmpty()) {
717 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
718 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
720 LOG.debug("MetricLogger requestId is null");
723 if (userName != null && !userName.isEmpty() && userPassword != null && !userPassword.isEmpty()) {
724 String basicAuth = "Basic " + new String(Base64.encodeBase64((userName + ":" + userPassword).getBytes()));
725 con.setRequestProperty("Authorization", basicAuth);
728 if (con instanceof HttpsURLConnection && CTX != null) {
729 SSLSocketFactory sockFact = CTX.getSocketFactory();
730 HttpsURLConnection.class.cast(con).setSSLSocketFactory(sockFact);
735 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
737 String depth = request.requestProperties.getProperty("depth", "1");
738 String path = requestUrl.toString();
739 if(path.contains("?depth=") || path.contains("&depth=")) {
742 if(path.contains("?")) {
743 path = String.format("%s&depth=%s", path, depth);
745 path = String.format("%s?depth=%s", path, depth);
747 return new URL(path);
751 public void logMetricRequest(String targetServiceName, String msg, String path){
752 String svcInstanceId = "";
753 String svcName = null;
754 String partnerName = null;
755 String targetEntity = "A&AI";
756 String targetVirtualEntity = null;
758 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
761 public void logMetricResponse(int responseCode, String responseDescription){
762 ml.logResponse(responseCode < 400 ? "COMPLETE" : "ERROR", Integer.toString(responseCode), responseDescription);
765 protected void LOGwriteFirstTrace(String method, String url) {
766 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
767 LOG.info("A&AI transaction :");
768 LOG.info("Request Time : " + time + ", Method : " + method);
769 LOG.info("Request URL : "+ url);
772 protected void LOGwriteDateTrace(String name, String data) {
773 LOG.info("Input - " + name + " : " + data);
776 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
777 LOG.info("Response code : " + response_code +", " + comment);
778 LOG.info(String.format("Response data : %s", data));