diff options
Diffstat (limited to 'common/src/main')
10 files changed, 314 insertions, 175 deletions
diff --git a/common/src/main/java/org/onap/so/client/RestClientSSL.java b/common/src/main/java/org/onap/so/client/RestClientSSL.java index 461bb5832c..8eaeee97ee 100644 --- a/common/src/main/java/org/onap/so/client/RestClientSSL.java +++ b/common/src/main/java/org/onap/so/client/RestClientSSL.java @@ -72,23 +72,15 @@ public abstract class RestClientSSL extends RestClient { private KeyStore getKeyStore() { KeyStore ks = null; char[] password = System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY).toCharArray(); - FileInputStream fis = null; - try { + try(FileInputStream fis = new FileInputStream(System.getProperty(RestClientSSL.SSL_KEY_STORE_KEY))) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); - fis = new FileInputStream(System.getProperty(RestClientSSL.SSL_KEY_STORE_KEY)); + ks.load(fis, password); } catch(Exception e) { return null; } - finally { - if (fis != null) { - try { - fis.close(); - } - catch(Exception e) {} - } - } + return ks; } } diff --git a/common/src/main/java/org/onap/so/client/RestRequest.java b/common/src/main/java/org/onap/so/client/RestRequest.java index 25bf54b643..985d7cc885 100644 --- a/common/src/main/java/org/onap/so/client/RestRequest.java +++ b/common/src/main/java/org/onap/so/client/RestRequest.java @@ -72,17 +72,13 @@ public class RestRequest implements Callable<Response> { try { mapper.get().map(response); } catch (NotFoundException e) { - if (this.client.props.mapNotFoundToEmpty()) { + if (this.client.props.mapNotFoundToEmpty() && "GET".equals(method)) { msoLogger.error(e); return response; } else { throw e; } } - } else { - if (response.getStatus() == Status.NOT_FOUND.getStatusCode() && this.client.props.mapNotFoundToEmpty()) { - return response; - } } return response; diff --git a/common/src/main/java/org/onap/so/client/aai/AAIClient.java b/common/src/main/java/org/onap/so/client/aai/AAIClient.java index 39843b2263..3d2410e2a2 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIClient.java @@ -22,11 +22,13 @@ package org.onap.so.client.aai; import java.net.URI; +import javax.ws.rs.NotFoundException; import javax.ws.rs.core.UriBuilder; import org.onap.so.client.RestClient; import org.onap.so.client.graphinventory.GraphInventoryClient; import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; +import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,7 +51,12 @@ public abstract class AAIClient extends GraphInventoryClient { } @Override protected RestClient createClient(GraphInventoryUri uri) { - return new AAIRestClient(getRestProperties(), constructPath(uri)); + try { + return new AAIRestClient(getRestProperties(), constructPath(uri)); + } catch (GraphInventoryUriComputationException | NotFoundException e) { + logger.debug("failed to construct A&AI uri", e); + throw e; + } } protected AAIVersion getVersion() { diff --git a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java index 04757c6fc2..072534d6f6 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java @@ -32,6 +32,7 @@ import javax.ws.rs.core.Response.Status; import org.onap.aai.domain.yang.Relationship; import org.onap.so.client.RestClient; import org.onap.so.client.RestProperties; +import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUri; @@ -81,9 +82,13 @@ public class AAIResourcesClient extends AAIClient { */ public boolean exists(AAIResourceUri uri) { AAIUri forceMinimal = this.addParams(Optional.of(Depth.ZERO), true, uri); - RestClient aaiRC = this.createClient(forceMinimal); - - return aaiRC.get().getStatus() == Status.OK.getStatusCode(); + try { + RestClient aaiRC = this.createClient(forceMinimal); + + return aaiRC.get().getStatus() == Status.OK.getStatusCode(); + } catch (NotFoundException e) { + return false; + } } /** @@ -100,6 +105,21 @@ public class AAIResourcesClient extends AAIClient { } /** + * Adds a relationship between two objects in A&AI + * with a given edge label + * @param uriA + * @param uriB + * @param edge label + * @return + */ + public void connect(AAIResourceUri uriA, AAIResourceUri uriB, AAIEdgeLabel label) { + AAIResourceUri uriAClone = uriA.clone(); + RestClient aaiRC = this.createClient(uriAClone.relationshipAPI()); + aaiRC.put(this.buildRelationship(uriB, label)); + return; + } + + /** * Removes relationship from two objects in A&AI * * @param uriA @@ -148,7 +168,15 @@ public class AAIResourcesClient extends AAIClient { * @return */ public <T> Optional<T> get(Class<T> clazz, AAIResourceUri uri) { - return this.createClient(uri).get(clazz); + try { + return this.createClient(uri).get(clazz); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + return Optional.empty(); + } else { + throw e; + } + } } /** @@ -157,7 +185,15 @@ public class AAIResourcesClient extends AAIClient { * @return */ public Response getFullResponse(AAIResourceUri uri) { - return this.createClient(uri).get(); + try { + return this.createClient(uri).get(); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + return e.getResponse(); + } else { + throw e; + } + } } /** @@ -167,7 +203,15 @@ public class AAIResourcesClient extends AAIClient { * @return */ public <T> Optional<T> get(GenericType<T> resultClass, AAIResourceUri uri) { - return this.createClient(uri).get(resultClass); + try { + return this.createClient(uri).get(resultClass); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + return Optional.empty(); + } else { + throw e; + } + } } /** @@ -177,7 +221,16 @@ public class AAIResourcesClient extends AAIClient { * @return */ public AAIResultWrapper get(AAIResourceUri uri) { - String json = this.createClient(uri).get(String.class).orElse(null); + String json; + try { + json = this.createClient(uri).get(String.class).orElse(null); + } catch (NotFoundException e) { + if (this.getRestProperties().mapNotFoundToEmpty()) { + json = null; + } else { + throw e; + } + } return new AAIResultWrapper(json); } @@ -189,22 +242,42 @@ public class AAIResourcesClient extends AAIClient { * @return */ public AAIResultWrapper get(AAIResourceUri uri, Class<? extends RuntimeException> c) { - + String json; + try { + json = this.createClient(uri).get(String.class) + .orElseThrow(() -> createException(c, uri.build() + " not found in A&AI")); + } catch (NotFoundException e) { + throw createException(c, "could not construct uri for use with A&AI"); + } + + return new AAIResultWrapper(json); + } + + private RuntimeException createException(Class<? extends RuntimeException> c, String message) { RuntimeException e; try { - e = c.getConstructor(String.class).newInstance(uri.build() + " not found in A&AI"); + e = c.getConstructor(String.class).newInstance(message); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { throw new IllegalArgumentException("could not create instance for " + c.getName()); } - String json = this.createClient(uri).get(String.class) - .orElseThrow(() -> e); - return new AAIResultWrapper(json); + + return e; } private Relationship buildRelationship(AAIResourceUri uri) { + return buildRelationship(uri, Optional.empty()); + } + + private Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) { + return buildRelationship(uri, Optional.of(label)); + } + private Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) { final Relationship result = new Relationship(); result.setRelatedLink(uri.build().toString()); + if (label.isPresent()) { + result.setRelationshipLabel(label.toString()); + } return result; } @@ -248,7 +321,7 @@ public class AAIResourcesClient extends AAIClient { return clone; } @Override - protected <T extends RestProperties> T getRestProperties() { + public <T extends RestProperties> T getRestProperties() { return super.getRestProperties(); } } diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java new file mode 100644 index 0000000000..0356e86861 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java @@ -0,0 +1,21 @@ +package org.onap.so.client.aai.entities; + +import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel; + +public enum AAIEdgeLabel implements GraphInventoryEdgeLabel { + + BELONGS_TO("org.onap.relationships.inventory.BelongsTo"), + USES("org.onap.relationships.inventory.Uses"); + + + private final String label; + private AAIEdgeLabel(String label) { + this.label = label; + } + + + @Override + public String toString() { + return this.label; + } +} diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java index 093918d49b..a132e15d1f 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java @@ -22,19 +22,19 @@ package org.onap.so.client.aai.entities.uri; import java.io.IOException; import java.net.URI; -import java.util.Collections; +import java.util.Arrays; import java.util.Map; import java.util.Optional; import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; import javax.ws.rs.core.UriBuilder; import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIQueryClient; -import org.onap.so.client.graphinventory.Format; -import org.onap.so.client.aai.entities.CustomQuery; +import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.Results; -import org.onap.so.client.graphinventory.entities.uri.SimpleUri; +import org.onap.so.client.graphinventory.Format; +import org.onap.so.client.graphinventory.entities.uri.HttpAwareUri; import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadException; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException; @@ -42,7 +42,7 @@ import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundExc import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -public class ServiceInstanceUri extends AAISimpleUri { +public class ServiceInstanceUri extends AAISimpleUri implements HttpAwareUri { private Optional<String> cachedValue = Optional.empty(); @@ -55,11 +55,10 @@ public class ServiceInstanceUri extends AAISimpleUri { } protected String getSerivceInstance(Object id) throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException { if (!this.getCachedValue().isPresent()) { - AAIResourceUri serviceInstanceUri = AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE, id); - CustomQuery query = new CustomQuery(Collections.singletonList(serviceInstanceUri)); + AAIResourceUri serviceInstanceUri = AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE, id).format(Format.PATHED); String resultJson; try { - resultJson = this.getQueryClient().query(Format.PATHED, query); + resultJson = this.getResourcesClient().get(serviceInstanceUri, NotFoundException.class).getJson(); } catch (BadRequestException e) { throw new GraphInventoryUriNotFoundException("Service instance " + id + " not found at: " + serviceInstanceUri.build()); @@ -99,7 +98,7 @@ public class ServiceInstanceUri extends AAISimpleUri { protected Optional<String> getCachedValue() { return this.cachedValue; } - + @Override public URI build() { try { @@ -119,8 +118,11 @@ public class ServiceInstanceUri extends AAISimpleUri { return new ServiceInstanceUri(this.internalURI.clone(), this.getCachedValue(), values); } - protected AAIQueryClient getQueryClient() { - AAIResourceUri uri = AAIUriFactory.createNodesUri(AAIObjectType.ALLOTTED_RESOURCE, "").clone(); - return new AAIQueryClient(); + public AAIResourcesClient getResourcesClient() { + return new AAIResourcesClient(); + } + @Override + public URI buildNoNetwork() { + return super.build(new String[]{"NONE", "NONE", (String)this.values[0]}); } } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java new file mode 100644 index 0000000000..1ede2f9e1b --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java @@ -0,0 +1,8 @@ +package org.onap.so.client.graphinventory.entities; + +public interface GraphInventoryEdgeLabel { + + + @Override + public String toString(); +} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java new file mode 100644 index 0000000000..145959dc73 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java @@ -0,0 +1,9 @@ +package org.onap.so.client.graphinventory.entities.uri; + +import java.net.URI; + +public interface HttpAwareUri { + + + public URI buildNoNetwork(); +} diff --git a/common/src/main/java/org/onap/so/logger/MsoLogger.java b/common/src/main/java/org/onap/so/logger/MsoLogger.java index 10f572e772..e4cac067ba 100644 --- a/common/src/main/java/org/onap/so/logger/MsoLogger.java +++ b/common/src/main/java/org/onap/so/logger/MsoLogger.java @@ -35,6 +35,8 @@ import org.onap.so.entity.MsoRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; /** @@ -49,15 +51,23 @@ import org.slf4j.MDC; */ public class MsoLogger { - // MDC parameters - public static final String REQUEST_ID = "RequestId"; - public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; + // Required MDC parameters + public static final String REQUEST_ID = "RequestID"; + public static final String INVOCATION_ID = "InvocationID"; + public static final String INSTANCE_UUID = "InstanceUUID"; public static final String SERVICE_NAME = "ServiceName"; + public static final String STATUSCODE = "StatusCode"; + public static final String RESPONSECODE = "ResponseCode"; + public static final String RESPONSEDESC = "ResponseDesc"; + public static final String FQDN = "ServerFQDN"; + + + public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; + public static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName"; - public static final String INSTANCE_UUID = "InstanceUUID"; public static final String SERVER_IP = "ServerIPAddress"; - public static final String FQDN = "ServerFQDN"; + public static final String REMOTE_HOST = "RemoteHost"; public static final String ALERT_SEVERITY = "AlertSeverity"; public static final String TIMER = "Timer"; @@ -73,16 +83,17 @@ public class MsoLogger { public static final String HEADER_REQUEST_ID = "X-RequestId"; public static final String TRANSACTION_ID = "X-TransactionID"; public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; + public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID"; + public static final String CLIENT_ID = "X-ClientID"; + public static final String INVOCATION_ID_HEADER = "X-InvocationID"; // Audit/Metric log specific public static final String BEGINTIME = "BeginTimestamp"; public static final String STARTTIME = "StartTimeMilis"; public static final String ENDTIME = "EndTimestamp"; public static final String PARTNERNAME = "PartnerName"; - public static final String STATUSCODE = "StatusCode"; - public static final String RESPONSECODE = "ResponseCode"; - public static final String RESPONSEDESC = "ResponseDesc"; + // Metric log specific @@ -103,8 +114,10 @@ public class MsoLogger { public static final String ERRORCODE = "ErrorCode"; public static final String ERRORDESC = "ErrorDesc"; + //Status Codes public static final String COMPLETE = "COMPLETE"; - + public static final String INPROGRESS = "INPROGRESS"; + public enum Catalog { APIH, BPEL, RA, ASDC, GENERAL } @@ -157,6 +170,9 @@ public class MsoLogger { this.value = value; } } + + public static final Marker ENTRY = MarkerFactory.getMarker("ENTRY"); + public static final Marker EXIT = MarkerFactory.getMarker("EXIT"); private Logger logger; private Logger metricsLogger; diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java index 9fab4ff0df..d278a5f761 100644 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java @@ -44,137 +44,152 @@ import javax.ws.rs.core.Response; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; - import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.ObjectMapper; @Priority(1) @Provider @Component public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerResponseFilter { - - private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,JaxRsFilterLogging.class); - - @Context - private HttpServletRequest httpServletRequest; - - @Context - private Providers providers; - - @Autowired - ObjectMapper objectMapper; - - @Override - public void filter(ContainerRequestContext containerRequest) { - - try { - String clientID = null; - //check headers for request id - MultivaluedMap<String, String> headers = containerRequest.getHeaders(); - String requestId = (String) headers.getFirst(MsoLogger.HEADER_REQUEST_ID ); - if(requestId == null || requestId.isEmpty()){ - if(headers.containsKey(MsoLogger.TRANSACTION_ID)){ - requestId = headers.getFirst(MsoLogger.TRANSACTION_ID); - }else if(headers.containsKey(MsoLogger.ECOMP_REQUEST_ID)){ - requestId = headers.getFirst(MsoLogger.ECOMP_REQUEST_ID); - }else{ - requestId = UUID.randomUUID().toString(); - logger.warnSimple(containerRequest.getUriInfo().getPath(),"Generating RequestId for Request"); - } - } - containerRequest.setProperty("requestId", requestId); - if(headers.containsKey(MsoLogger.CLIENT_ID)){ - clientID = headers.getFirst(MsoLogger.CLIENT_ID); - }else{ - clientID = "UNKNOWN"; - headers.add(MsoLogger.CLIENT_ID, clientID); - } - String remoteIpAddress = ""; - if (httpServletRequest != null) { - remoteIpAddress = httpServletRequest.getRemoteAddr(); - } - Instant instant = Instant.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) - .withLocale( Locale.US ) - .withZone( ZoneId.systemDefault() ); - - String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID ); - if(partnerName == null || partnerName.isEmpty()) - partnerName="UNKNOWN"; - - MDC.put(MsoLogger.FROM_APP_ID,partnerName); - MDC.put(MsoLogger.SERVICE_NAME, containerRequest.getUriInfo().getPath()); - MDC.put(MsoLogger.BEGINTIME, formatter.format(instant)); - MDC.put(MsoLogger.REQUEST_ID,requestId); - MDC.put(MsoLogger.PARTNERNAME,partnerName); - MDC.put(MsoLogger.REMOTE_HOST, String.valueOf(remoteIpAddress)); - MDC.put(MsoLogger.STARTTIME, String.valueOf(System.currentTimeMillis())); - MDC.put(MsoLogger.CLIENT_ID, clientID); - } catch (Exception e) { - logger.warnSimple("Error in incoming JAX-RS Inteceptor", e); - } - } - - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) - throws IOException { - try { - Instant instant = Instant.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) - .withLocale( Locale.US ) - .withZone( ZoneId.systemDefault() ); - String startTime= MDC.get(MsoLogger.STARTTIME); - long elapsedTime; - try { - elapsedTime = System.currentTimeMillis() - Long.parseLong(startTime); - }catch(NumberFormatException e){ - elapsedTime = 0; - } - String statusCode; - if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){ - statusCode=MsoLogger.COMPLETE; - }else{ - statusCode= MsoLogger.StatusCode.ERROR.toString(); - } - - MDC.put(MsoLogger.RESPONSEDESC,payloadMessage(responseContext)); - MDC.put(MsoLogger.STATUSCODE, statusCode); - MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus())); - MDC.put(MsoLogger.TIMER, String.valueOf(elapsedTime)); - MDC.put(MsoLogger.ENDTIME,formatter.format(instant)); - logger.recordAuditEvent(); - } catch ( Exception e) { - logger.warnSimple("Error in outgoing JAX-RS Inteceptor", e); - } - } - - private String payloadMessage(ContainerResponseContext responseContext) throws IOException { - String message = new String(); - if (responseContext.hasEntity()) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Class<?> entityClass = responseContext.getEntityClass(); - Type entityType = responseContext.getEntityType(); - Annotation[] entityAnnotations = responseContext.getEntityAnnotations(); - MediaType mediaType = responseContext.getMediaType(); - @SuppressWarnings("unchecked") - MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers.getMessageBodyWriter(entityClass, - entityType, - entityAnnotations, - mediaType); - bodyWriter.writeTo(responseContext.getEntity(), - entityClass, - entityType, - entityAnnotations, - mediaType, - responseContext.getHeaders(), - baos); - message = message.concat(new String(baos.toByteArray())); - } - return message; - } + + protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class); + + @Context + private HttpServletRequest httpServletRequest; + + @Context + private Providers providers; + + @Autowired + ObjectMapper objectMapper; + + @Override + public void filter(ContainerRequestContext containerRequest) { + + try { + String clientID = null; + //check headers for request id + MultivaluedMap<String, String> headers = containerRequest.getHeaders(); + String requestId = findRequestId(headers); + containerRequest.setProperty("requestId", requestId); + if(headers.containsKey(MsoLogger.CLIENT_ID)){ + clientID = headers.getFirst(MsoLogger.CLIENT_ID); + }else{ + clientID = "UNKNOWN"; + headers.add(MsoLogger.CLIENT_ID, clientID); + } + + String remoteIpAddress = ""; + if (httpServletRequest != null) { + remoteIpAddress = httpServletRequest.getRemoteAddr(); + } + Instant instant = Instant.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) + .withLocale( Locale.US ) + .withZone( ZoneId.systemDefault() ); + + String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID ); + if(partnerName == null || partnerName.isEmpty()) + partnerName="UNKNOWN"; + + MDC.put(MsoLogger.REQUEST_ID,requestId); + MDC.put(MsoLogger.INVOCATION_ID,requestId); + MDC.put(MsoLogger.FROM_APP_ID,partnerName); + MDC.put(MsoLogger.SERVICE_NAME, containerRequest.getUriInfo().getPath()); + MDC.put(MsoLogger.INVOCATION_ID, findInvocationId(headers)); + MDC.put(MsoLogger.STATUSCODE, MsoLogger.INPROGRESS); + MDC.put(MsoLogger.BEGINTIME, formatter.format(instant)); + MDC.put(MsoLogger.PARTNERNAME,partnerName); + MDC.put(MsoLogger.REMOTE_HOST, String.valueOf(remoteIpAddress)); + MDC.put(MsoLogger.STARTTIME, String.valueOf(System.currentTimeMillis())); + logger.debug(MsoLogger.ENTRY, "Entering."); + } catch (Exception e) { + logger.warn("Error in incoming JAX-RS Inteceptor", e); + } + } + + + private String findRequestId(MultivaluedMap<String, String> headers) { + String requestId = (String) headers.getFirst(MsoLogger.HEADER_REQUEST_ID ); + if(requestId == null || requestId.isEmpty()){ + if(headers.containsKey(MsoLogger.ONAP_REQUEST_ID)){ + requestId = headers.getFirst(MsoLogger.ONAP_REQUEST_ID); + }else if(headers.containsKey(MsoLogger.ECOMP_REQUEST_ID)){ + requestId = headers.getFirst(MsoLogger.ECOMP_REQUEST_ID); + }else{ + requestId = UUID.randomUUID().toString(); + } + } + return requestId; + } + + private String findInvocationId(MultivaluedMap<String, String> headers) { + String invocationId = (String) headers.getFirst(MsoLogger.INVOCATION_ID_HEADER ); + if(invocationId == null || invocationId.isEmpty()) + invocationId =UUID.randomUUID().toString(); + return invocationId; + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { + try { + Instant instant = Instant.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ) + .withLocale( Locale.US ) + .withZone( ZoneId.systemDefault() ); + String startTime= MDC.get(MsoLogger.STARTTIME); + long elapsedTime; + try { + elapsedTime = System.currentTimeMillis() - Long.parseLong(startTime); + }catch(NumberFormatException e){ + elapsedTime = 0; + } + String statusCode; + if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){ + statusCode=MsoLogger.COMPLETE; + }else{ + statusCode= MsoLogger.StatusCode.ERROR.toString(); + } + + MDC.put(MsoLogger.RESPONSEDESC,payloadMessage(responseContext)); + MDC.put(MsoLogger.STATUSCODE, statusCode); + MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus())); + MDC.put(MsoLogger.TIMER, String.valueOf(elapsedTime)); + MDC.put(MsoLogger.ENDTIME,formatter.format(instant)); + logger.debug(MsoLogger.EXIT, "Exiting."); + } catch ( Exception e) { + logger.warn("Error in outgoing JAX-RS Inteceptor", e); + } + } + + private String payloadMessage(ContainerResponseContext responseContext) throws IOException { + String message = new String(); + if (responseContext.hasEntity()) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Class<?> entityClass = responseContext.getEntityClass(); + Type entityType = responseContext.getEntityType(); + Annotation[] entityAnnotations = responseContext.getEntityAnnotations(); + MediaType mediaType = responseContext.getMediaType(); + @SuppressWarnings("unchecked") + MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers.getMessageBodyWriter(entityClass, + entityType, + entityAnnotations, + mediaType); + bodyWriter.writeTo(responseContext.getEntity(), + entityClass, + entityType, + entityAnnotations, + mediaType, + responseContext.getHeaders(), + baos); + message = message.concat(new String(baos.toByteArray())); + } + return message; + } } |