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;
52 import javax.ws.rs.core.Response.Status;
53 import javax.ws.rs.core.Response;
55 import org.apache.commons.codec.binary.Base64;
56 import org.onap.ccsdk.sli.adaptors.aai.AAIService.TransactionIdTracker;
57 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
58 import org.onap.ccsdk.sli.adaptors.aai.data.ErrorResponse;
59 import org.onap.ccsdk.sli.adaptors.aai.data.RequestError;
60 import org.onap.ccsdk.sli.adaptors.aai.data.ResourceVersion;
61 import org.onap.ccsdk.sli.adaptors.aai.data.ServiceException;
62 import org.onap.ccsdk.sli.core.sli.MetricLogger;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 import com.fasterxml.jackson.databind.DeserializationFeature;
67 import com.fasterxml.jackson.databind.ObjectMapper;
68 import com.sun.jersey.api.client.config.DefaultClientConfig;
69 import com.sun.jersey.client.urlconnection.HTTPSProperties;
72 * The AAIClientRESTExecutor class provides CRUD API for AAI Client service.
73 * @author richtabedzki
75 public class AAIClientRESTExecutor implements AAIExecutorInterface {
77 private final String truststorePath;
78 private final String truststorePassword;
79 private final String keystorePath;
80 private final String keystorePassword;
81 private final Boolean ignoreCertificateHostError;
82 // authentication credentials
83 private String userName;
84 private String userPassword;
85 private final String applicationId;
89 * @param props - properties to initialize an instance.
91 public AAIClientRESTExecutor(Properties props) {
94 userName = props.getProperty(AAIService.CLIENT_NAME);
95 userPassword = props.getProperty(AAIService.CLIENT_PWWD);
97 if(userName == null || userName.isEmpty()){
98 LOG.debug("Basic user name is not set");
100 if(userPassword == null || userPassword.isEmpty()) {
101 LOG.debug("Basic password is not set");
104 truststorePath = props.getProperty(AAIService.TRUSTSTORE_PATH);
105 truststorePassword = props.getProperty(AAIService.TRUSTSTORE_PSSWD);
106 keystorePath = props.getProperty(AAIService.KEYSTORE_PATH);
107 keystorePassword = props.getProperty(AAIService.KEYSTORE_PSSWD);
109 String tmpApplicationId =props.getProperty(AAIService.APPLICATION_ID);
110 if(tmpApplicationId == null || tmpApplicationId.isEmpty()) {
111 tmpApplicationId = "SDNC";
113 applicationId = tmpApplicationId;
115 String iche = props.getProperty(AAIService.CERTIFICATE_HOST_ERROR);
116 boolean host_error = false;
117 if(iche != null && !iche.isEmpty()) {
118 host_error = Boolean.valueOf(iche);
121 ignoreCertificateHostError = host_error;
123 HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
124 public boolean verify(String string,SSLSession ssls) {
125 return ignoreCertificateHostError;
129 if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) {
130 System.setProperty("javax.net.ssl.trustStore", truststorePath);
131 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
134 if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).exists())
136 DefaultClientConfig config = new DefaultClientConfig();
137 //both jersey and HttpURLConnection can use this
138 SSLContext ctx = null;
140 ctx = SSLContext.getInstance("TLS");
142 KeyManagerFactory kmf = null;
143 try (FileInputStream fin = new FileInputStream(keystorePath)){
144 String storeType = "PKCS12";
145 String def = KeyStore.getDefaultType();
146 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
148 String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1);
150 if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
153 KeyStore ks = KeyStore.getInstance(storeType);
155 char[] pwd = keystorePassword.toCharArray();
158 } catch (Exception ex) {
159 LOG.error("AAIResource", ex);
162 ctx.init(kmf.getKeyManagers(), null, null);
163 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() {
165 public boolean verify( String s, SSLSession sslSession ) {
166 return ignoreCertificateHostError;
171 LOG.debug("SSLContext created");
173 } catch (KeyManagementException | NoSuchAlgorithmException exc) {
174 LOG.error("AAIResource", exc);
179 Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
180 methodsField.setAccessible(true);
181 // get the methods field modifiers
182 Field modifiersField = Field.class.getDeclaredField("modifiers");
183 // bypass the "private" modifier
184 modifiersField.setAccessible(true);
186 // remove the "final" modifier
187 modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
189 /* valid HTTP methods */
191 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
193 // set the new methods - including patch
194 methodsField.set(null, methods);
196 } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
197 LOG.warn("Adding PATCH method", e);
199 LOG.info("AAIResource.ctor initialized.");
203 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
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 Status status = Response.Status.fromStatusCode(responseCode) ;
264 if(status != null && status.getReasonPhrase() != null)
265 responseMessage = status.getReasonPhrase();
267 responseMessage = "NOT PROVIDED";
270 // Process the response
271 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
272 logMetricResponse(responseCode, responseMessage);
274 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
275 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
277 ObjectMapper mapper = AAIService.getObjectMapper();
279 if (responseCode == HttpURLConnection.HTTP_OK) {
280 StringBuilder stringBuilder = new StringBuilder();
282 while( ( line = reader.readLine() ) != null ) {
283 stringBuilder.append( line );
285 response = stringBuilder.toString();
287 Object object = mapper.readValue(response, Object.class);
288 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object));
289 } catch(Exception exc) {
290 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response));
292 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
293 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
294 ErrorResponse errorresponse = null;
296 errorresponse = mapper.readValue(reader, ErrorResponse.class);
297 } catch(Exception exc) {
298 errorresponse = new ErrorResponse();
299 RequestError requestError = new RequestError();
300 ServiceException serviceException = new ServiceException();
301 serviceException.setText("Entry does not exist.");
302 requestError.setServiceException(serviceException);
303 errorresponse.setRequestError(requestError );
305 throw new AAIServiceException(responseCode, errorresponse);
306 } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
307 StringBuilder stringBuilder = new StringBuilder();
309 while( ( line = reader.readLine() ) != null ) {
310 stringBuilder.append( line );
312 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
313 ServiceException serviceException = new ServiceException();
314 serviceException.setMessageId("HTTP_UNAUTHORIZED");
315 serviceException.setText(stringBuilder.toString());
316 RequestError requestError = new RequestError();
317 requestError.setServiceException(serviceException);
318 ErrorResponse errorresponse = new ErrorResponse();
319 errorresponse.setRequestError(requestError);
320 throw new AAIServiceException(responseCode, errorresponse);
323 while( ( line = reader.readLine() ) != null ) {
324 errorStringBuilder.append("\n").append( line );
327 ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class);
328 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
329 throw new AAIServiceException(responseCode, errorresponse);
332 } catch(AAIServiceException aaiexc) {
334 } catch (Exception exc) {
335 LOG.warn(errorStringBuilder.toString(), exc);
336 throw new AAIServiceException(exc);
338 if(inputStream != null){
341 } catch(Exception exc) {
350 * Returns an String that contains JSON data returned from the AAI Server.
352 * This method always returns immediately, whether or not the
355 * @param request an instance of AAIRequiest representing
356 * the request made by DirectedGraph node.
357 * @return the JSON based representation of data instance requested.
361 public String post(AAIRequest request) throws AAIServiceException {
362 InputStream inputStream = null;
365 String resourceVersion = null;
366 AAIDatum instance = request.getRequestObject();
369 Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion");
370 if(getResourceVersionMethod != null){
372 Object object = getResourceVersionMethod.invoke(instance);
374 resourceVersion = object.toString();
375 } catch (InvocationTargetException exc) {
379 } catch(Exception exc) {
383 URL requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion);
384 HttpURLConnection con = getConfiguredConnection(requestUrl, HttpMethod.PUT);
385 ObjectMapper mapper = AAIService.getObjectMapper();
386 String jsonText = request.toJSONString();
388 LOGwriteDateTrace("data", jsonText);
389 logMetricRequest("PUT "+requestUrl.getPath(), jsonText, requestUrl.getPath());
391 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
396 int responseCode = con.getResponseCode();
397 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
398 inputStream = con.getInputStream();
400 inputStream = con.getErrorStream();
402 String responseMessage = null;
404 responseMessage = con.getResponseMessage();
405 } catch(Exception exc) {
406 Status status = Response.Status.fromStatusCode(responseCode) ;
407 if(status != null && status.getReasonPhrase() != null)
408 responseMessage = status.getReasonPhrase();
410 responseMessage = "NOT PROVIDED";
413 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
414 logMetricResponse(responseCode, responseMessage);
416 // Process the response
417 BufferedReader reader;
419 reader = new BufferedReader( new InputStreamReader( inputStream ) );
420 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
422 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
423 StringBuilder stringBuilder = new StringBuilder();
425 while( ( line = reader.readLine() ) != null ) {
426 stringBuilder.append( line );
428 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
429 return stringBuilder.toString();
431 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
432 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
434 throw new AAIServiceException(responseCode, errorresponse);
436 } catch(AAIServiceException aaiexc) {
438 } catch (Exception exc) {
439 LOG.warn("AAIRequestExecutor.post", exc);
440 throw new AAIServiceException(exc);
443 if(inputStream != null)
445 } catch (Exception exc) {
446 LOG.warn("AAIRequestExecutor.post", exc);
452 * Returns Boolean that contains completion state of the command executed.
454 * This method always returns immediately, whether or not the
457 * @param request an instance of AAIRequiest representing
458 * @param resourceVersion a resource version of the data instacne to be deleted.
459 * the request made by DirectedGraph node.
460 * @return completion state of the command.
464 public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException {
465 Boolean response = null;
466 InputStream inputStream = null;
468 if(resourceVersion == null) {
469 throw new AAIServiceException("resource-version is required for DELETE request");
473 URL requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion);
474 HttpURLConnection conn = getConfiguredConnection(requestUrl, HttpMethod.DELETE);
475 logMetricRequest("DELETE "+requestUrl.getPath(), "", requestUrl.getPath());
476 conn.setDoOutput(true);
479 int responseCode = conn.getResponseCode();
480 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
481 inputStream = conn.getInputStream();
483 inputStream = conn.getErrorStream();
485 String responseMessage = null;
487 responseMessage = conn.getResponseMessage();
488 } catch(Exception exc) {
489 Status status = Response.Status.fromStatusCode(responseCode) ;
490 if(status != null && status.getReasonPhrase() != null)
491 responseMessage = status.getReasonPhrase();
493 responseMessage = "NOT PROVIDED";
496 // Process the response
497 LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage);
498 logMetricResponse(responseCode, responseMessage);
500 if(inputStream == null) inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
501 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
504 ObjectMapper mapper = AAIService.getObjectMapper();
506 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
507 StringBuilder stringBuilder = new StringBuilder();
509 while( ( line = reader.readLine() ) != null ) {
510 stringBuilder.append( line );
512 LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString());
514 } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) {
515 LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist.");
518 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
519 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
520 throw new AAIServiceException(responseCode, errorresponse);
522 } catch(AAIServiceException aaiexc) {
524 } catch (Exception exc) {
525 LOG.warn("delete", exc);
526 throw new AAIServiceException(exc);
528 if(inputStream != null){
531 } catch(Exception exc) {
532 LOG.warn("delete", exc);
540 * Returns an String that contains JSON data returned from the AAI Server.
542 * This method always returns immediately, whether or not the
545 * @param request an instance of AAIRequiest representing
546 * the request made by DirectedGraph node.
547 * @param clas an definition of the class for which data will be returned
548 * @return the instance of the class with data.
552 public Object query(AAIRequest request, Class clas) throws AAIServiceException {
553 Object response = null;
554 InputStream inputStream = null;
557 URL requestUrl = request.getRequestQueryUrl(HttpMethod.GET);
558 HttpURLConnection con = getConfiguredConnection(requestUrl, HttpMethod.GET);
559 logMetricRequest("GET "+requestUrl.getPath(), "", requestUrl.getPath());
562 int responseCode = con.getResponseCode();
563 if (responseCode == HttpURLConnection.HTTP_OK) {
564 inputStream = con.getInputStream();
566 inputStream = con.getErrorStream();
568 String responseMessage = null;
570 responseMessage = con.getResponseMessage();
571 } catch(Exception exc) {
572 Status status = Response.Status.fromStatusCode(responseCode) ;
573 if(status != null && status.getReasonPhrase() != null)
574 responseMessage = status.getReasonPhrase();
576 responseMessage = "NOT PROVIDED";
579 logMetricResponse(responseCode, responseMessage);
580 ObjectMapper mapper = AAIService.getObjectMapper();
582 if (responseCode == HttpURLConnection.HTTP_OK) {
583 // Process the response
584 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
585 response = mapper.readValue(reader, clas);
586 LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
587 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
588 LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
591 BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
592 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
593 LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
594 throw new AAIServiceException(responseCode, errorresponse);
597 } catch(AAIServiceException aaiexc) {
599 } catch (Exception exc) {
600 LOG.warn("GET", exc);
601 throw new AAIServiceException(exc);
603 if(inputStream != null){
606 } catch(Exception exc) {
607 LOG.warn("GET", exc);
615 public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException {
616 InputStream inputStream = null;
619 AAIDatum instance = request.getRequestObject();
620 if(instance instanceof ResourceVersion) {
621 resourceVersion = ((ResourceVersion)instance).getResourceVersion();
624 URL requestUrl = null;
625 HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH");
626 ObjectMapper mapper = AAIService.getObjectMapper();
627 String jsonText = request.toJSONString();
629 LOGwriteDateTrace("data", jsonText);
630 logMetricRequest("PATCH "+requestUrl.getPath(), jsonText, requestUrl.getPath());
632 OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
637 int responseCode = con.getResponseCode();
638 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
639 inputStream = con.getInputStream();
641 inputStream = con.getErrorStream();
643 String responseMessage = null;
645 responseMessage = con.getResponseMessage();
646 } catch(Exception exc) {
647 Status status = Response.Status.fromStatusCode(responseCode) ;
648 if(status != null && status.getReasonPhrase() != null)
649 responseMessage = status.getReasonPhrase();
651 responseMessage = "NOT PROVIDED";
654 LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage);
655 logMetricResponse(responseCode, responseMessage);
657 // Process the response
658 BufferedReader reader;
660 reader = new BufferedReader( new InputStreamReader( inputStream ) );
661 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
663 if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
664 StringBuilder stringBuilder = new StringBuilder();
666 while( ( line = reader.readLine() ) != null ) {
667 stringBuilder.append( line );
669 LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}");
672 StringBuilder stringBuilder = new StringBuilder();
674 while( ( line = reader.readLine() ) != null ) {
675 stringBuilder.append("\n").append( line );
677 LOG.info(stringBuilder.toString());
680 ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
681 LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse));
683 throw new AAIServiceException(responseCode, errorresponse);
685 } catch(AAIServiceException aaiexc) {
687 } catch (Exception exc) {
688 LOG.warn("AAIRequestExecutor.patch", exc);
689 throw new AAIServiceException(exc);
692 if(inputStream != null)
694 } catch (Exception exc) {
695 LOG.warn("AAIRequestExecutor.patch", exc);
707 protected HttpURLConnection getConfiguredConnection(URL httpReqUrl, String method) throws Exception {
708 HttpURLConnection con = (HttpURLConnection) httpReqUrl.openConnection();
710 // Set up the connection properties
711 con.setRequestProperty("Connection", "close");
712 con.setDoInput(true);
713 con.setDoOutput(true);
714 con.setUseCaches(false);
715 con.setConnectTimeout(connection_timeout);
716 con.setReadTimeout(read_timeout);
717 con.setRequestMethod(method);
718 con.setRequestProperty("Accept", "application/json");
719 con.setRequestProperty("Transfer-Encoding","chunked");
720 con.setRequestProperty("Content-Type",
721 "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json");
722 con.setRequestProperty("X-FromAppId", applicationId);
723 con.setRequestProperty("X-TransactionId", TransactionIdTracker.getNextTransactionId());
724 String mlId = ml.getRequestID();
725 if (mlId != null && !mlId.isEmpty()) {
726 LOG.debug(String.format("MetricLogger requestId = %s", mlId));
727 con.setRequestProperty(MetricLogger.REQUEST_ID, mlId);
729 LOG.debug("MetricLogger requestId is null");
732 if (userName != null && !userName.isEmpty() && userPassword != null && !userPassword.isEmpty()) {
733 String basicAuth = "Basic " + new String(Base64.encodeBase64((userName + ":" + userPassword).getBytes()));
734 con.setRequestProperty("Authorization", basicAuth);
737 if (con instanceof HttpsURLConnection && CTX != null) {
738 SSLSocketFactory sockFact = CTX.getSocketFactory();
739 HttpsURLConnection.class.cast(con).setSSLSocketFactory(sockFact);
744 private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException {
746 String depth = request.requestProperties.getProperty("depth", "1");
747 String path = requestUrl.toString();
748 if(path.contains("?depth=") || path.contains("&depth=")) {
751 if(path.contains("?")) {
752 path = String.format("%s&depth=%s", path, depth);
754 path = String.format("%s?depth=%s", path, depth);
756 return new URL(path);
760 public void logMetricRequest(String targetServiceName, String msg, String path){
761 String svcInstanceId = "";
762 String svcName = null;
763 String partnerName = null;
764 String targetEntity = "A&AI";
765 String targetVirtualEntity = null;
767 ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg);
770 public void logMetricResponse(int responseCode, String responseDescription){
771 ml.logResponse(responseCode < 400 ? "COMPLETE" : "ERROR", Integer.toString(responseCode), responseDescription);
774 protected void LOGwriteFirstTrace(String method, String url) {
775 String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis());
776 LOG.info("A&AI transaction :");
777 LOG.info("Request Time : " + time + ", Method : " + method);
778 LOG.info("Request URL : "+ url);
781 protected void LOGwriteDateTrace(String name, String data) {
782 LOG.info("Input - " + name + " : " + data);
785 protected void LOGwriteEndingTrace(int response_code, String comment, String data) {
786 LOG.info("Response code : " + response_code +", " + comment);
787 LOG.info(String.format("Response data : %s", data));