diff options
author | O'Connor, Lina (lo8949) <lo8949@us.att.com> | 2020-03-11 13:36:42 -0600 |
---|---|---|
committer | O'Connor, Lina (lo8949) <lo8949@us.att.com> | 2020-03-11 13:39:55 -0600 |
commit | e062d90200373473b21b42b8b5f0d8ae18155494 (patch) | |
tree | 1b7cee491f06c44c9d91420c40e271b99403c0cb /aai-els-onap-logging/src/test | |
parent | ed992e01c17d5677dfa0e1d0a76a7f9bc12c2a90 (diff) |
Increase code coverage on aai-common: aai-els-onap-logging library
Added Junits
Issue-ID: AAI-2832
Change-Id: I68e11f67b4c16660707bc12de3c14df15145b2b7
Signed-off-by: O'Connor, Lina (lo8949) <lo8949@us.att.com>
Diffstat (limited to 'aai-els-onap-logging/src/test')
36 files changed, 3410 insertions, 0 deletions
diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/AaiAuditLogContainerFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/AaiAuditLogContainerFilterTest.java new file mode 100644 index 00000000..5f23e668 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/AaiAuditLogContainerFilterTest.java @@ -0,0 +1,85 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.aailog.filter; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class AaiAuditLogContainerFilterTest { + @Mock + private ContainerRequestContext containerRequest; + + @Mock + private ContainerResponseContext containerResponse; + + @Mock + private UriInfo uriInfo; + + @Spy + @InjectMocks + private AaiAuditLogContainerFilter aaiAuditFilter; + + @After + public void tearDown() { + MDC.clear(); + } + @Test + public void partnerAndServiceNameValueTest() throws java.net.URISyntaxException { + + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(Constants.HttpHeaders.HEADER_FROM_APP_ID, "FROM_APP_ID_TEST"); + when(containerRequest.getHeaders()).thenReturn(headerMap); + + URI uri = null; + try { + uri = new URI("https://localhost:9999/onap/aai/network/logical-link"); + } + catch (java.net.URISyntaxException e) { + throw e; + } + when(uriInfo.getAbsolutePath()).thenReturn(uri); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); + + aaiAuditFilter.filter(containerRequest); + assertEquals("FROM_APP_ID_TEST", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertEquals("/onap/aai/network/logical-link", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + } + +} + diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestClientLoggingInterceptorTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestClientLoggingInterceptorTest.java new file mode 100644 index 00000000..601a13be --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestClientLoggingInterceptorTest.java @@ -0,0 +1,106 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.aailog.filter; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpRequest; + +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class RestClientLoggingInterceptorTest { + + @Mock + private HttpRequest httpRequest; + + @Spy + @InjectMocks + private RestClientLoggingInterceptor restClientLoggingInterceptor; + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupHeadersTest() { + String transId="37b3ab2a-e57e-4fe8-8d8f-eee3019efce6"; + HttpHeaders headers = new HttpHeaders(); + headers.add(Constants.HttpHeaders.TRANSACTION_ID, transId); + restClientLoggingInterceptor.setupHeaders(httpRequest, headers); + + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.ECOMP_REQUEST_ID)); + assertEquals(transId, headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); + } + + @Test + public void getServiceNameTest() throws URISyntaxException { + URI uri = null; + try { + uri = new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"); + } catch (URISyntaxException e) { + throw e; + } + doReturn(uri).when(httpRequest).getURI(); + String serviceName = restClientLoggingInterceptor.getServiceName(httpRequest); + + assertEquals("/aai/v1/cloud-infrastructure/complexes", serviceName); + } + + @Test + public void setupMDCTest() throws URISyntaxException { + URI uri = new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"); + doReturn(uri).when(httpRequest).getURI(); + HttpHeaders headers = new HttpHeaders(); + restClientLoggingInterceptor.pre(httpRequest, headers); + assertEquals("/aai/v1/cloud-infrastructure/complexes", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME) ); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + String serverFQDN = ""; + InetAddress addr = null; + try { + addr = InetAddress.getLocalHost(); + serverFQDN = addr.getCanonicalHostName(); + + } catch (UnknownHostException e) { + serverFQDN = ""; + } + assertEquals(serverFQDN, MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + assertNotNull(headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestControllerClientLoggingInterceptorTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestControllerClientLoggingInterceptorTest.java new file mode 100644 index 00000000..48cb3efc --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestControllerClientLoggingInterceptorTest.java @@ -0,0 +1,107 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.aailog.filter; + +import com.sun.jersey.api.client.ClientRequest; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class RestControllerClientLoggingInterceptorTest { + + private ClientRequest clientRequest; + + @Spy + @InjectMocks + private RestControllerClientLoggingInterceptor restControllerClientLoggingInterceptor; + + @Before + public void init() throws URISyntaxException { + System.setProperty("javax.ws.rs.ext.RuntimeDelegate", "com.sun.ws.rs.ext.RuntimeDelegateImpl"); + clientRequest = ClientRequest.create().build(new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"), + "GET"); + } + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupHeadersTest() throws java.net.URISyntaxException { + + String transId="37b3ab2a-e57e-4fe8-8d8f-eee3019efce6"; + MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<String, Object>(); + requestHeaders.add(Constants.HttpHeaders.TRANSACTION_ID, transId); + clientRequest.getHeaders().putAll(requestHeaders); + restControllerClientLoggingInterceptor.pre(clientRequest); + MultivaluedMap<String, Object> headers = clientRequest.getHeaders(); + + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.ECOMP_REQUEST_ID)); + assertEquals(transId, headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); + assertNotNull(headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID)); + } + + @Test + public void getServiceNameTest() { + String serviceName = restControllerClientLoggingInterceptor.getServiceName(clientRequest); + assertEquals("/aai/v1/cloud-infrastructure/complexes", serviceName); + } + + @Test + public void setupMDCTest() throws URISyntaxException { + restControllerClientLoggingInterceptor.pre(clientRequest); + assertEquals("/aai/v1/cloud-infrastructure/complexes", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME) ); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + String serverFQDN = ""; + InetAddress addr = null; + try { + addr = InetAddress.getLocalHost(); + serverFQDN = addr.getCanonicalHostName(); + + } catch (UnknownHostException e) { + serverFQDN = ""; + } + assertEquals(serverFQDN, MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/InfoTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/InfoTest.java new file mode 100644 index 00000000..1d19e5bf --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/InfoTest.java @@ -0,0 +1,66 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.10.28 at 05:53:17 PM EDT +// + +package org.onap.aai.domain.restResponseInfo; + +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class InfoTest { + private Info info = new Info(); + + @Test + public void infoTest() { + Info.ResponseMessages responseMessages = info.getResponseMessages(); + if (responseMessages == null) responseMessages = new Info.ResponseMessages(); + + List<Info.ResponseMessages.ResponseMessage> list = responseMessages.getResponseMessage(); + Info.ResponseMessages.ResponseMessage respMsg = new Info.ResponseMessages.ResponseMessage(); + + respMsg.setMessageId("1"); + respMsg.setText("textValue"); + + Info.ResponseMessages.ResponseMessage.Variables vars = new Info.ResponseMessages.ResponseMessage.Variables(); + vars.getVariable().add("var1"); + vars.getVariable().add("var2"); + + respMsg.setVariables(vars); + list.add(respMsg); + info.setResponseMessages(responseMessages); + + Info.ResponseMessages responseMessages1 = info.getResponseMessages(); + List<Info.ResponseMessages.ResponseMessage> list1 = responseMessages1.getResponseMessage(); + Info.ResponseMessages.ResponseMessage respMsg1 = list1.get(0); + assertTrue(respMsg1.getMessageId().equals("1")); + assertTrue(respMsg1.getText().equals("textValue")); + assertTrue(respMsg1.getVariables().getVariable().contains("var1")); + assertTrue(respMsg1.getVariables().getVariable().contains("var2")); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/ObjectFactoryTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/ObjectFactoryTest.java new file mode 100644 index 00000000..55205794 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/ObjectFactoryTest.java @@ -0,0 +1,49 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.10.28 at 05:53:17 PM EDT +// + +package org.onap.aai.domain.restResponseInfo; + +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; + +public class ObjectFactoryTest { + private ObjectFactory objectFactory = new ObjectFactory(); + + @Test + public void objectFactoryTest() { + Info.ResponseMessages.ResponseMessage.Variables variables = objectFactory.createInfoResponseMessagesResponseMessageVariables(); + Info.ResponseMessages.ResponseMessage responseMessage = objectFactory.createInfoResponseMessagesResponseMessage(); + Info.ResponseMessages responseMessages = objectFactory.createInfoResponseMessages(); + Info info = objectFactory.createInfo(); + + assertNotNull(variables); + assertNotNull(responseMessage); + assertNotNull(responseMessages); + assertNotNull(info); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java new file mode 100644 index 00000000..4f08607f --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.exceptions; + +import org.junit.Test; +import org.onap.aai.logging.AaiElsErrorCode; +import org.onap.aai.logging.ErrorObject; + +import javax.ws.rs.core.Response; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class AAIExceptionTest { + private AAIException aaiException; + + @Test + public void defaultAAIExceptionTest() { + //AAI_4000=5:4:ERROR:4000:500:3002:Internal Error:900 + aaiException = new AAIException(); + assertEquals(AAIException.DEFAULT_EXCEPTION_CODE, aaiException.getCode()); + + ErrorObject errorObject = aaiException.getErrorObject(); + assertEquals(errorObject.getCategory(), "4"); + assertEquals(errorObject.getDisposition(), "5"); + assertEquals(errorObject.getSeverity(), "ERROR"); + assertEquals(errorObject.getHTTPResponseCode(), Response.Status.INTERNAL_SERVER_ERROR); + assertEquals(errorObject.getRESTErrorCode(), "3002"); + assertEquals(errorObject.getErrorCode(), "4000"); + assertEquals(errorObject.getAaiElsErrorCode(), AaiElsErrorCode.UNKNOWN_ERROR); + assertEquals(errorObject.getErrorText(), "Internal Error"); + + } + + @Test + public void aaiExceptionTest() { + //5:1:WARN:3303:403:3300:Too many objects would be returned by this request, please refine your request and retry:500 + aaiException = new AAIException("AAI_3303"); + assertEquals("AAI_3303", aaiException.getCode()); + + ErrorObject errorObject = aaiException.getErrorObject(); + assertEquals(errorObject.getCategory(), "1"); + assertEquals(errorObject.getDisposition(), "5"); + assertEquals(errorObject.getSeverity(), "WARN"); + assertEquals(errorObject.getHTTPResponseCode(), Response.Status.FORBIDDEN); + assertEquals(errorObject.getRESTErrorCode(), "3300"); + assertEquals(errorObject.getErrorCode(), "3303"); + assertEquals(errorObject.getAaiElsErrorCode(), AaiElsErrorCode.BUSINESS_PROCESS_ERROR); + assertEquals(errorObject.getErrorText(), "Too many objects would be returned by this request, please refine your request and retry"); + assertNotNull(aaiException.getTemplateVars()); + } + + @Test + public void aaiExceptionTestWithDetails() { + //5:1:WARN:3303:403:3300:Too many objects would be returned by this request, please refine your request and retry:500 + final String testDetails = "Test details"; + aaiException = new AAIException("AAI_3303", testDetails); + assertEquals(testDetails, aaiException.getMessage()); + assertEquals(testDetails, aaiException.getErrorObject().getDetails()); + assertNotNull(aaiException.getTemplateVars()); + } + + @Test + public void aaiExceptionTestWithCause() { + aaiException = new AAIException("AAI_3303", new IOException("File not found")); + Throwable t = aaiException.getCause(); + assertEquals("java.io.IOException: File not found", t.toString()); + assertNotNull(aaiException.getTemplateVars()); + } + + @Test + public void aaiExceptionTestWithCauseDetails() { + final String testFileName = "TestFileName"; + aaiException = new AAIException("AAI_3303", new IOException("File not found"), testFileName); + + Throwable t = aaiException.getCause(); + assertEquals("java.io.IOException: File not found", t.toString()); + assertEquals(testFileName, aaiException.getMessage()); + assertNotNull(aaiException.getTemplateVars()); + } +} + diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java new file mode 100644 index 00000000..dbfe60d5 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java @@ -0,0 +1,79 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.exceptions; + +import org.junit.Test; + +import java.io.IOException; +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class AAIExceptionWithInfoTest { + + private AAIExceptionWithInfo aaiException; + private static final String testInfo = "Test Info"; + private static final String testDetails = "Test Details"; + + @Test + public void aaiExceptionWithInfoTest() { + + aaiException = new AAIExceptionWithInfo(new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertNotNull(aaiException.getInfoHash()); + } + + @Test + public void aaiExceptionWithCodeInfoTest() { + aaiException = new AAIExceptionWithInfo("AAI_3300", new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertEquals("AAI_3300", aaiException.getCode()); + assertNotNull(aaiException.getInfoHash()); + } + + @Test + public void aaiExceptionWithCodeDetailsInfoTest() { + + aaiException = new AAIExceptionWithInfo("AAI_3300", testDetails, new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertEquals("AAI_3300", aaiException.getCode()); + assertEquals(testDetails, aaiException.getMessage()); + assertNotNull(aaiException.getInfoHash()); + } + + @Test + public void aaiExceptionWithCodeThrowableDetailsInfoTest() { + + aaiException = new AAIExceptionWithInfo("AAI_3300", new IOException("File not found"), testDetails, new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertEquals("AAI_3300", aaiException.getCode()); + assertEquals(testDetails, aaiException.getMessage()); + assertNotNull(aaiException.getInfoHash()); + Throwable t = aaiException.getCause(); + assertEquals("java.io.IOException: File not found", t.toString()); + } + +} + diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CNNameTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CNNameTest.java new file mode 100644 index 00000000..01b7bda1 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CNNameTest.java @@ -0,0 +1,108 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.mock.web.MockHttpServletRequest; + +import javax.security.auth.x500.X500Principal; +import java.security.cert.X509Certificate; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class CNNameTest { + @Mock + X509Certificate cert; + + @Mock + IAccessEvent accessEvent; + + @Spy + @InjectMocks + private CNName cnName; + + @Before + public void setup() { + when(cnName.isStarted()).thenReturn(true); + } + @Test + public void basicAuthTest(){ + + MockHttpServletRequest https = new MockHttpServletRequest(); + https.addHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA=="); + https.setAttribute("javax.servlet.request.cipher_suite", ""); + https.setAttribute("javax.servlet.request.X509Certificate", null); + + when(accessEvent.getRequest()).thenReturn(https); + assertEquals("user", cnName.convert(accessEvent)); + + } + @Test + public void incorrectHeaderBasicAuthTest(){ + + MockHttpServletRequest https = new MockHttpServletRequest(); + + https.addHeader("Authorization", "dXNlcjpwYXNzd29yZA=="); + https.setAttribute("javax.servlet.request.cipher_suite", ""); + https.setAttribute("javax.servlet.request.X509Certificate", null); + + when(accessEvent.getRequest()).thenReturn(https); + assertEquals("-", cnName.convert(accessEvent)); + + } + @Test + public void noCipherSuiteTest(){ + + MockHttpServletRequest https = new MockHttpServletRequest(); + + https.addHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA=="); + https.setAttribute("javax.servlet.request.cipher_suite", null); + https.setAttribute("javax.servlet.request.X509Certificate", null); + + when(accessEvent.getRequest()).thenReturn(https); + assertEquals("-", cnName.convert(accessEvent)); + + } + @Test + public void certificateTest(){ + String testSubject = "CN=TestName, OU=TestOU, O=TestOrg, C=Country"; + X509Certificate[] certChain = { cert }; + MockHttpServletRequest https = new MockHttpServletRequest(); + + https.setAttribute("javax.servlet.request.cipher_suite", ""); + https.setAttribute("javax.servlet.request.X509Certificate", certChain ); + + when(accessEvent.getRequest()).thenReturn(https); + when(cert.getSubjectX500Principal()).thenReturn(new X500Principal(testSubject) ); + + assertEquals(testSubject, cnName.convert(accessEvent)); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java new file mode 100644 index 00000000..71a07aa1 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java @@ -0,0 +1,38 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CustomLogPatternLayoutTest { + + private CustomLogPatternLayout customLogPatternLayout = new CustomLogPatternLayout(); + + @Test + public void defaultConverterTest(){ + + assertEquals(customLogPatternLayout.getDefaultConverterMap().get("z"), CNName.class.getName()); + assertEquals(customLogPatternLayout.getDefaultConverterMap().get("y"), DME2RestFlag.class.getName()); + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java new file mode 100644 index 00000000..737cb624 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class DME2RestFlagTest { + + @Mock + IAccessEvent accessEvent; + + @Spy + @InjectMocks + private DME2RestFlag dme2RestFlag; + + @Before + public void setup() { + when(dme2RestFlag.isStarted()).thenReturn(true); + } + @Test + public void dme2Test(){ + String[] contextArray = {"a", "b", "c"}; + String[] routeOfferArray = {"d", "e", "f"}; + String[] versionArray = {"1", "2", "3"}; + when(accessEvent.getRequestParameter("envContext")).thenReturn(contextArray); + when(accessEvent.getRequestParameter("routeOffer")).thenReturn(routeOfferArray); + when(accessEvent.getRequestParameter("version")).thenReturn(versionArray); + assertEquals("DME2", dme2RestFlag.convert(accessEvent)); + } + @Test + public void restTest(){ + String[] contextArray = {""}; + String[] routeOfferArray = {""}; + String[] versionArray = {""}; + when(accessEvent.getRequestParameter("envContext")).thenReturn(contextArray); + assertEquals("REST", dme2RestFlag.convert(accessEvent)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorLogHelperTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorLogHelperTest.java new file mode 100644 index 00000000..ae174691 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorLogHelperTest.java @@ -0,0 +1,151 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.domain.restPolicyException.PolicyException; +import org.onap.aai.domain.restPolicyException.RESTResponse; +import org.onap.aai.domain.restPolicyException.RequestError; +import org.onap.aai.domain.restServiceException.ServiceException; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.util.LogFile; +import org.onap.aai.util.MapperUtil; +import org.slf4j.MDC; + +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static java.lang.Thread.sleep; +import static org.junit.Assert.*; + +public class ErrorLogHelperTest { + + private static final String ErrorLogFileName = "error.log"; + + @Before + public void init() { + System.setProperty("AJSC_HOME", "."); + + } + @After + public void cleanup() throws IOException{ + MDC.clear(); + LogFile.deleteContents(ErrorLogFileName); + } + @Test + public void logErrorTest() throws IOException, InterruptedException { + //||main|UNKNOWN||||ERROR|500|Node cannot be deleted:3100:Bad Request:|ERR.5.4.6110 + ErrorLogHelper.logError("AAI_6110"); + sleep(5000); + String logContents = LogFile.getContents(ErrorLogFileName); + + assertNotNull(logContents); + + String logContentParts[] = logContents.split("\\|"); + + assertTrue(logContentParts.length >= 11 ); + assertEquals ("ERROR", logContentParts[7]); + assertEquals (AaiElsErrorCode.BUSINESS_PROCESS_ERROR, logContentParts[8]); + assertTrue (logContentParts[10].startsWith("ERR.5.4.6110")); + } + + @Test + public void logErrorWithMessageTest() throws IOException, InterruptedException { + //||main|UNKNOWN||||ERROR|500|Node cannot be deleted:3100:Bad Request:|ERR.5.4.6110 message + String errorMessage = "Object is referenced by additional objects"; + ErrorLogHelper.logError("AAI_6110", errorMessage); + sleep(5000); + String logContents = LogFile.getContents(ErrorLogFileName); + + assertNotNull(logContents); + + String logContentParts[] = logContents.split("\\|"); + + assertTrue(logContentParts.length >= 11 ); + assertTrue (logContentParts[9].contains(errorMessage)); + assertTrue (logContentParts[10].startsWith("ERR.5.4.6110")); + } + + @Test + public void getRESTAPIPolicyErrorResponseTest() throws AAIException{ + //AAI_3002=5:1:WARN:3002:400:3002:Error writing output performing %1 on %2:300 + ArrayList<MediaType> headers = new ArrayList<MediaType>(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + ArrayList<String> args = new ArrayList<String>(Arrays.asList("PUT", "resource")); + + AAIException aaie = new AAIException("AAI_3002"); + String errorResponse = ErrorLogHelper.getRESTAPIErrorResponse(headers, aaie, args); + assertNotNull(errorResponse); + + RESTResponse resp = MapperUtil.readAsObjectOf(RESTResponse.class, errorResponse); + RequestError requestError = resp.getRequestError(); + assertNotNull(requestError); + PolicyException policyException = requestError.getPolicyException(); + assertNotNull(policyException); + assertEquals("POL3002", policyException.getMessageId()); + + List<String> vars = policyException.getVariables(); + assertTrue(vars.contains("PUT")); + assertTrue(vars.contains("resource")); + } + @Test + public void getRESTAPIServiceErrorResponseTest() throws AAIException{ + //AAI_3009=5:6:WARN:3009:400:3009:Malformed URL:300 + ArrayList<MediaType> headers = new ArrayList<MediaType>(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + ArrayList<String> args = new ArrayList<String>(); + + AAIException aaie = new AAIException("AAI_3009"); + String errorResponse = ErrorLogHelper.getRESTAPIErrorResponse(headers, aaie, args); + assertNotNull(errorResponse); + + org.onap.aai.domain.restServiceException.RESTResponse resp = MapperUtil.readAsObjectOf(org.onap.aai.domain.restServiceException.RESTResponse.class, errorResponse); + org.onap.aai.domain.restServiceException.RequestError requestError = resp.getRequestError(); + assertNotNull(requestError); + ServiceException serviceException = requestError.getServiceException(); + assertNotNull(serviceException); + assertEquals("SVC3009", serviceException.getMessageId()); + + } + @Test + public void getRESTAPIServiceErrorResponseWithLoggingTest() throws IOException, InterruptedException{ + //AAI_3009=5:6:WARN:3009:400:3009:Malformed URL:300 + ArrayList<MediaType> headers = new ArrayList<MediaType>(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + ArrayList<String> args = new ArrayList<String>(); + + AAIException aaie = new AAIException("AAI_3009"); + String errorResponse = ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers, aaie, args); + sleep(5000); + assertNotNull(errorResponse); + String logContents = LogFile.getContents(ErrorLogFileName); + + assertNotNull(logContents); + String logContentParts[] = logContents.split("\\|"); + + assertTrue(logContentParts.length >= 11 ); + assertTrue (logContentParts[10].startsWith("ERR.5.6.3009")); + + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectFormatExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectFormatExceptionTest.java new file mode 100644 index 00000000..a5a8e496 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectFormatExceptionTest.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class ErrorObjectFormatExceptionTest { + + @Test + public void errorObjectFormatExceptionTest() { + ErrorObjectFormatException e = new ErrorObjectFormatException(); + assertTrue(e instanceof Exception); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectNotFoundExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectNotFoundExceptionTest.java new file mode 100644 index 00000000..8bffe4ff --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectNotFoundExceptionTest.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.*; + +public class ErrorObjectNotFoundExceptionTest { + + @Test + public void defaultExceptionTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException(); + assertTrue(e instanceof Exception); + } + @Test + public void errorObjectNotFoundExceptionWithMessageTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException("Error Message"); + assertTrue(e instanceof Exception); + assertEquals("Error Message", e.getMessage()); + } + @Test + public void errorObjectNotFoundExceptionWithCauseTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException(new ArithmeticException()); + assertTrue(e instanceof Exception); + assertTrue(e.getCause() instanceof ArithmeticException); + } + @Test + public void errorObjectNotFoundExceptionWithMsgCauseTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException("Error Message", new ArithmeticException()); + assertTrue(e instanceof Exception); + assertTrue(e.getCause() instanceof ArithmeticException); + assertEquals("Error Message", e.getMessage()); + } + @Test + public void errorObjectNotFoundExceptionTest() { + + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), true, true); + assertTrue(e instanceof Exception); + assertTrue(e.getCause() instanceof ArithmeticException); + assertEquals("Error Message", e.getMessage()); + e.addSuppressed(new IOException("Test IO Exception")); + assertTrue((e.getSuppressed())[0] instanceof IOException); + assertEquals("Test IO Exception", (e.getSuppressed())[0].getMessage()); + + ErrorObjectNotFoundException e1 = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), false, true); + e1.addSuppressed(new IOException("Test IO Exception")); + assertTrue((e1.getSuppressed() == null) || e1.getSuppressed().length == 0); + + } + + @Test + public void errorObjectNotFoundExceptionStackTraceTest() { + + ErrorObjectNotFoundException e1 = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), true, true); + try { + throw e1; + } + catch (ErrorObjectNotFoundException e) { + StackTraceElement[] stackTrace = e.getStackTrace(); + assertNotNull(stackTrace); + assertTrue(stackTrace.length > 0); + } + + ErrorObjectNotFoundException e2 = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), true, false); + try { + throw e2; + } + catch (ErrorObjectNotFoundException e) { + StackTraceElement[] stackTrace = e.getStackTrace(); + assertTrue(stackTrace == null || stackTrace.length == 0); + } + + } + /*public ErrorObjectNotFoundException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + // TODO Auto-generated constructor stub + }*/ +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectTest.java new file mode 100644 index 00000000..ff20105c --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectTest.java @@ -0,0 +1,95 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.Test; + +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertEquals; + +public class ErrorObjectTest { + private ErrorObject errorObject; + private static final String ERROR_DISPOSITION = "5"; + private static final String ERROR_SEVERITY = "ERROR"; + private static final String ERROR_CATEGORY = "4"; + private static final Integer ERROR_HTTP_RESPONSE_CODE = new Integer(401); + private static final String ERROR_REST_CODE = "3300"; + private static final String ERROR_CODE = "4000"; + private static final String ERROR_TEXT = "Test data error"; + private static final String ERROR_PATTERN = "ERR.5.4.4000"; + private static final String ERROR_SEVERITY_CODE = "2"; + @Test + public void errorObjectDefaultConstructorTest() { + errorObject = new ErrorObject(); + assertEquals("3002", errorObject.getRESTErrorCode()); + assertEquals(Response.Status.fromStatusCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()), errorObject.getHTTPResponseCode()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR,errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + } + @Test + public void errorObjectConstructor7Test() { + errorObject = new ErrorObject(ERROR_DISPOSITION, ERROR_CATEGORY, ERROR_SEVERITY, ERROR_HTTP_RESPONSE_CODE, + ERROR_REST_CODE, ERROR_CODE, ERROR_TEXT); + assertEquals(ERROR_DISPOSITION, errorObject.getDisposition()); + assertEquals(ERROR_SEVERITY, errorObject.getSeverity()); + assertEquals(ERROR_CATEGORY, errorObject.getCategory()); + assertEquals(Response.Status.fromStatusCode(ERROR_HTTP_RESPONSE_CODE), errorObject.getHTTPResponseCode()); + assertEquals(ERROR_REST_CODE, errorObject.getRESTErrorCode()); + assertEquals(ERROR_CODE, errorObject.getErrorCode()); + assertEquals(ERROR_TEXT, errorObject.getErrorText()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR,errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + } + + @Test + public void errorObjectConstructor5Test() { + errorObject = new ErrorObject(ERROR_SEVERITY, ERROR_CODE, ERROR_TEXT, ERROR_DISPOSITION, ERROR_CATEGORY); + assertEquals(ERROR_DISPOSITION, errorObject.getDisposition()); + assertEquals(ERROR_SEVERITY, errorObject.getSeverity()); + assertEquals(ERROR_CATEGORY, errorObject.getCategory()); + assertEquals(Response.Status.fromStatusCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()), errorObject.getHTTPResponseCode()); + assertEquals("3002", errorObject.getRESTErrorCode()); + assertEquals(ERROR_CODE, errorObject.getErrorCode()); + assertEquals(ERROR_TEXT, errorObject.getErrorText()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR,errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_PATTERN, errorObject.getErrorCodeString()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + } + + @Test + public void errorObjectConstructor6Test() { + errorObject = new ErrorObject(ERROR_SEVERITY, ERROR_HTTP_RESPONSE_CODE, ERROR_CODE, ERROR_TEXT, ERROR_DISPOSITION, ERROR_CATEGORY); + assertEquals(ERROR_DISPOSITION, errorObject.getDisposition()); + assertEquals(ERROR_SEVERITY, errorObject.getSeverity()); + assertEquals(ERROR_CATEGORY, errorObject.getCategory()); + assertEquals(Response.Status.fromStatusCode(ERROR_HTTP_RESPONSE_CODE), errorObject.getHTTPResponseCode()); + assertEquals("3002", errorObject.getRESTErrorCode()); + assertEquals(ERROR_CODE, errorObject.getErrorCode()); + assertEquals(ERROR_TEXT, errorObject.getErrorText()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR, errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_PATTERN, errorObject.getErrorCodeString()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + + } + + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LogFormatToolsTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LogFormatToolsTest.java new file mode 100644 index 00000000..695d7c08 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LogFormatToolsTest.java @@ -0,0 +1,39 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class LogFormatToolsTest { + + @Test + public void testLogFormatStackTrace() { + AAIException aaiException = new AAIException("AAI_4009", new ArithmeticException()); + + String stackTrace = LogFormatTools.getStackTop(aaiException); + assertTrue(stackTrace.startsWith("root cause=java.lang.ArithmeticException")); + assertFalse(stackTrace.contains("\\n")); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LoggingContextTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LoggingContextTest.java new file mode 100644 index 00000000..245840bc --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LoggingContextTest.java @@ -0,0 +1,78 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.After; +import org.junit.Test; +import org.slf4j.MDC; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class LoggingContextTest { + + @After + public void cleanup(){ + MDC.clear(); + } + @Test + public void elapsedTimeTest() { + LoggingContext.elapsedTime(300, TimeUnit.MILLISECONDS); + assertEquals(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()), "300"); + LoggingContext.init(); + assertTrue(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()) == null); + } + @Test + public void stopWatchTest() { + LoggingContext.init(); + assertFalse(LoggingContext.isStopWatchStarted()); + + LoggingContext.stopWatchStart(); + assertTrue(LoggingContext.isStopWatchStarted()); + + double elapsedTime = LoggingContext.stopWatchStop(); + assertFalse(LoggingContext.isStopWatchStarted()); + assertTrue(elapsedTime > 0); + } + @Test + public void putClearTest() { + String testServiceName = "TEST-SVC-NAME"; + LoggingContext.put(LoggingContext.LoggingField.SERVICE_NAME.toString(), testServiceName); + assertEquals(testServiceName, MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString())); + + LoggingContext.clear(); + assertTrue(MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString()) == null); + + } + + @Test + public void removeTest() { + String testServiceName = "TEST-SVC-NAME"; + LoggingContext.put(LoggingContext.LoggingField.SERVICE_NAME.toString(), testServiceName); + assertEquals(testServiceName, MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString())); + + LoggingContext.remove(LoggingContext.LoggingField.SERVICE_NAME.toString()); + assertTrue(MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString()) == null); + + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchNotStartedExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchNotStartedExceptionTest.java new file mode 100644 index 00000000..8a4123f0 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchNotStartedExceptionTest.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class StopWatchNotStartedExceptionTest { + + + @Test + public void stopWatchNotStartedExceptionTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException(); + assertTrue(e instanceof RuntimeException); + } + @Test + public void stopWatchNotStartedExceptionWithMessageTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException("Error Message"); + assertTrue(e instanceof RuntimeException); + assertEquals("Error Message", e.getMessage()); + } + @Test + public void stopWatchNotStartedExceptionWithCauseTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException(new ArithmeticException()); + assertTrue(e instanceof RuntimeException); + assertTrue(e.getCause() instanceof ArithmeticException); + } + @Test + public void stopWatchNotStartedExceptionWithMsgCauseTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException("Error Message", new ArithmeticException()); + assertTrue(e instanceof RuntimeException); + assertTrue(e.getCause() instanceof ArithmeticException); + assertEquals("Error Message", e.getMessage()); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchTest.java new file mode 100644 index 00000000..50a2d053 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchTest.java @@ -0,0 +1,93 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.logging; + +import org.junit.After; +import org.junit.Test; +import org.slf4j.MDC; + +import static java.lang.Thread.sleep; +import static org.junit.Assert.*; + +public class StopWatchTest { + + @After + public void cleanup() { + MDC.clear(); + } + @Test + public void elapsedTimeTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.stop(); + assertTrue(Long.parseLong(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString())) >= 1000L); + } + @Test + public void elapsedTimeConditionalTest() throws InterruptedException { + StopWatch.conditionalStart(); + sleep(1010); + StopWatch.stopIfStarted(); + String elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime = Long.parseLong(elapsedTimeStr); + assertTrue(elapsedTime >= 1000L); + } + @Test + public void clearTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.stop(); + assertNotNull( MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString())); + + StopWatch.clear(); + assertNull(MDC.get(LoggingContext.LoggingField.STOP_WATCH_START.toString())); + assertNull(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString())); + + } + + @Test + public void stopTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.stop(); + + String elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime1 = Long.parseLong(elapsedTimeStr); + + StopWatch.stopIfStarted(); + elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime2 = Long.parseLong(elapsedTimeStr); + assertTrue(elapsedTime1 == elapsedTime2); + } + + @Test + public void startTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.conditionalStart(); + StopWatch.stop(); + + String elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime = Long.parseLong(elapsedTimeStr); + + assertTrue(elapsedTime >= 1000L); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIApplicationConfigTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIApplicationConfigTest.java new file mode 100644 index 00000000..24efee3d --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIApplicationConfigTest.java @@ -0,0 +1,75 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.util; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class AAIApplicationConfigTest { + + @Before + public void setup() { + AAIApplicationConfig.init(); + } + + @Test + public void truststoreTest() throws AAIException { + assertEquals("truststore.jks", AAIApplicationConfig.getTruststore()); + } + @Test + public void keystoreTest() throws AAIException { + assertEquals("keystore.jks", AAIApplicationConfig.getKeystore()); + } + + @Test + public void getKeystorePkcs12Test() throws AAIException { + assertEquals("keystore.pkcs12", AAIApplicationConfig.getKeystorePkcs12()); + } + + @Test + public void getValueWithDefaultTest() throws AAIException { + assertEquals("default-value", AAIApplicationConfig.get("non-existing-key", "default-value")); + } + + @Test + public void getValueTest() throws AAIException { + assertEquals("certificates", AAIApplicationConfig.get("server.certs.location")); + } + @Test + public void getIntValueTest() throws AAIException { + assertTrue(8446 == AAIApplicationConfig.getInt("server.port")); + } + + @Test + public void getIntValueWithDefaultTest() throws AAIException { + assertTrue(9999 == AAIApplicationConfig.getInt("non-existing-key", "9999")); + } + + @Test + public void getValueWithReplacementTest() throws AAIException { + assertEquals("/opt/app/aai/etc/auth/aai-client-cert.p12", AAIApplicationConfig.get("schema.service.ssl.key-store")); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIConfigTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIConfigTest.java new file mode 100644 index 00000000..86d6c202 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIConfigTest.java @@ -0,0 +1,74 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.util; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.*; + +public class AAIConfigTest { + + @Before + public void setup() throws AAIException { + AAIConfig.init(); + } + + @Test + public void getValueWithDefaultTest() throws AAIException { + assertEquals("default-value", AAIConfig.get("non-existing-key", "default-value")); + } + + @Test + public void getValueTest() throws AAIException { + assertEquals("10", AAIConfig.get("aai.logging.maxStackTraceEntries")); + } + @Test + public void getIntValueTest() throws AAIException { + assertTrue(10 == AAIConfig.getInt("aai.logging.maxStackTraceEntries")); + } + + @Test + public void getIntValueWithDefaultTest() throws AAIException { + assertTrue(9999 == AAIConfig.getInt("non-existing-key", "9999")); + } + + @Test + public void getNodeNameTest() throws AAIException { + assertNotNull(AAIConfig.getNodeName()); + } + + @Test + public void notEmptyTest() throws AAIException { + String value = "test"; + assertFalse(AAIConfig.isEmpty(value)); + } + + @Test + public void emptyTest() throws AAIException { + String value = null; + assertTrue(AAIConfig.isEmpty(value)); + value = ""; + assertTrue(AAIConfig.isEmpty(value)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/FormatDateTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/FormatDateTest.java new file mode 100644 index 00000000..38ac5de5 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/FormatDateTest.java @@ -0,0 +1,40 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.util; + +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.assertNotNull; + +public class FormatDateTest { + private FormatDate formatDate = null; + + @Test + public void formatDateTest() throws AAIException { + formatDate = new FormatDate("yyyy-MM-dd HH:mm:ss.SSS"); + String dateTime = formatDate.getDateTime(); + assertNotNull(dateTime); + dateTime.matches("^\\d\\d\\d\\d-[0-1][0-9]-[0-2][0-9] [0-5][0-9]:[0-5][0-9]:[0-5][0-9].\\d\\d\\d$"); + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/LogFile.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/LogFile.java new file mode 100644 index 00000000..682f667b --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/LogFile.java @@ -0,0 +1,51 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.util; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.Charset; + +/** + * Utility class to read/delete contents of log file + */ +public class LogFile { + + public static String getContents(String fileName) throws IOException { + + FileInputStream fileInputStream = null; + String contents = null; + try { + fileInputStream = new FileInputStream("logs/" + fileName); + contents = IOUtils.toString(fileInputStream, "UTF-8"); + } + finally { + if (fileInputStream != null) fileInputStream.close(); + } + return contents; + } + public static void deleteContents(String fileName) throws IOException { + FileUtils.write(new File("logs/" + fileName), "", Charset.defaultCharset()); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java new file mode 100644 index 00000000..119bdf1e --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class AuditLogContainerFilterTest { + protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class); + + @Mock + private ContainerRequestContext containerRequest; + + @Mock + private ContainerResponseContext containerResponse; + + @Mock + private UriInfo uriInfo; + + @Spy + @InjectMocks + private AuditLogContainerFilter auditLogContainerFilter; + + @After + public void tearDown() { + MDC.clear(); + } + + + @Test + public void filterTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.REQUEST_ID, "e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); + when(containerRequest.getHeaders()).thenReturn(headerMap); + when(uriInfo.getPath()).thenReturn("onap/so/serviceInstances"); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); + auditLogContainerFilter.filter(containerRequest); + + assertEquals("e3b08fa3-535f-4c1b-8228-91318d2bb4ee", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + } + + @Test + public void getResponseCodeTest() { + when(containerResponse.getStatus()).thenReturn(200); + int responseCode = auditLogContainerFilter.getResponseCode(containerResponse); + + assertEquals(200, responseCode); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java new file mode 100644 index 00000000..d3f0f9f5 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.when; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class AuditLogServletFilterTest { + + @Mock + private ServletRequest request; + + @Mock + private ServletResponse response; + + @Mock + private HttpServletRequest servletRequest; + + @Mock + private HttpServletResponse servletResponse; + + @Spy + @InjectMocks + private AuditLogServletFilter auditLogServletFilter; + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void preTest() { + when(servletRequest.getRequestURI()).thenReturn("onap/so/serviceInstances"); + auditLogServletFilter.pre(servletRequest); + + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + + } + + @Test + public void getResponseCodeTest() { + when(servletResponse.getStatus()).thenReturn(200); + int responseCode = auditLogServletFilter.getResponseCode(servletResponse); + + assertEquals(200, responseCode); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java new file mode 100644 index 00000000..4d1f102a --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; + +public class LoggingContainerFilterTest { + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + + @Test + public void convertMultivaluedMapToHashMap() { + MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); + headers.add(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + SimpleMap result = new SimpleJaxrsHeadersMap(headers); + assertEquals(invocationId, result.get(ONAPLogConstants.Headers.INVOCATION_ID)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java new file mode 100644 index 00000000..9c89da5a --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java @@ -0,0 +1,279 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class MDCSetupTest extends MDCSetup { + + @Mock + private HttpServletRequest httpServletRequest; + + private String requestId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9a"; + + @After + public void tearDown() { + MDC.clear(); + System.clearProperty("partnerName"); + } + + @Test + public void setElapsedTimeTest() { + String expected = "318"; + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); + + setElapsedTime(); + assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setElapsedTimeInvokeTimestampTest() { + String expected = "318"; + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); + + setElapsedTimeInvokeTimestamp(); + assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setRequestIdTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(ONAPLogConstants.Headers.REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdRequestIdHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdTransactionIdHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.TRANSACTION_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdEcompRequestIdHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setInvocationIdTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + setInvocationId(new SimpleHashMap(headers)); + assertEquals(invocationId, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setInvocationIdNoHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + setInvocationId(new SimpleHashMap(headers)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setResponseStatusCodeTest() { + setResponseStatusCode(200); + assertEquals("COMPLETE", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + } + + @Test + public void setResponseStatusCodeErrorTest() { + setResponseStatusCode(400); + assertEquals("ERROR", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertEquals("400", MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); + assertEquals("Bad Request", MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); + } + + @Test + public void clearClientMDCsTest() { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "Bad Gateway"); + MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, "Bad Gateway"); + MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, "SDNC"); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + + clearClientMDCs(); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertNull(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); + } + + @Test + public void setTargetEntityTest() { + setTargetEntity(ONAPComponents.SO); + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + } + + @Test + public void setResponseDescriptionTest() { + setResponseDescription(502); + assertEquals("Bad Gateway", MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); + } + + @Test + public void setMDCPartnerNameBearerToken() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + String value = "Bearer some-compex-token"; + headerMap.putSingle(HttpHeaders.AUTHORIZATION, value); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals(Constants.DefaultValues.UNKNOWN, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.PARTNER_NAME, "SO"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameUserAgentHeaderTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(HttpHeaders.USER_AGENT, "Apache-HttpClient/4.5.8 (Java/1.8.0_191)"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("Apache-HttpClient/4.5.8 (Java/1.8.0_191)", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameNoHeaderTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("UNKNOWN", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setServerFQDNTest() { + setServerFQDN(); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + } + + @Test + public void setClientIPAddressTest() { + when(httpServletRequest.getHeader("X-Forwarded-For")).thenReturn("127.0.0.2"); + setClientIPAddress(httpServletRequest); + + assertEquals("127.0.0.2", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setClientIPAddressNoHeaderTest() { + when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1"); + setClientIPAddress(httpServletRequest); + + assertEquals("127.0.0.1", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setClientIPAddressNullTest() { + setClientIPAddress(null); + + assertEquals("", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setEntryTimeStampTest() { + setEntryTimeStamp(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); + } + + @Test + public void setLogTimestampTest() { + setLogTimestamp(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); + } + + @Test + public void setInstanceIDTest() { + setInstanceID(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); + } + + @Test + public void getPropertyTest() { + System.setProperty("partnerName", "partnerName"); + + String partnerName = getProperty("partnerName"); + assertEquals("partnerName", partnerName); + } + + @Test + public void getPropertyNullTest() { + String partnerName = getProperty("partner"); + assertEquals(null, partnerName); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java new file mode 100644 index 00000000..6f6a0ff1 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class MetricLogClientFilterTest { + @Mock + private ClientRequestContext clientRequest; + + @Spy + @InjectMocks + private MetricLogClientFilter metricLogClientFilter; + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupHeadersTest() { + MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); + doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(metricLogClientFilter).extractRequestID(); + metricLogClientFilter.setupHeaders(clientRequest, headers); + + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.ECOMP_REQUEST_ID)); + } + + @Test + public void setupMDCTest() throws URISyntaxException { + // TODO ingest change from upstream + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); + URI uri = new URI("onap/so/serviceInstances"); + doReturn(uri).when(clientRequest).getUri(); + + metricLogClientFilter.setupMDC(clientRequest); + + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNotNull(ONAPLogConstants.MDCs.SERVICE_NAME); + assertNotNull(ONAPLogConstants.MDCs.SERVER_FQDN); + assertNotNull(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + } + + @Test + public void setupMDCNoTargetEntityTest() throws URISyntaxException { + URI uri = new URI("onap/so/serviceInstances"); + doReturn(uri).when(clientRequest).getUri(); + + metricLogClientFilter.setupMDC(clientRequest); + + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertEquals("Unknown-Target-Entity", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNotNull(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + } + + @Test + public void extractRequestIDTest() { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); + String requestId = metricLogClientFilter.extractRequestID(); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", requestId); + } + + @Test + public void extractRequestIDNullTest() throws URISyntaxException { + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String requestId = metricLogClientFilter.extractRequestID(); + assertNotNull(requestId); + assertNotNull(ONAPLogConstants.MDCs.LOG_TIMESTAMP); + assertNotNull(ONAPLogConstants.MDCs.ELAPSED_TIME); + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java new file mode 100644 index 00000000..c2446a3f --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.net.URISyntaxException; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class PayloadLoggingClientFilterTest { + + @Mock + private ClientRequestContext requestContext; + + @Spy + @InjectMocks + private PayloadLoggingClientFilter payloadLoggingClientFilter; + + @Test + public void formatMethodTest() throws IOException, URISyntaxException { + when(requestContext.getHeaderString("X-HTTP-Method-Override")).thenReturn("filter"); + when(requestContext.getMethod()).thenReturn("filtered"); + String method = payloadLoggingClientFilter.formatMethod(requestContext); + + assertEquals("filtered (overridden to filter)", method); + } + + @Test + public void formatMethodNullHeaderTest() throws IOException, URISyntaxException { + when(requestContext.getMethod()).thenReturn("filtered"); + String method = payloadLoggingClientFilter.formatMethod(requestContext); + + assertEquals("filtered", method); + } + + @Test + public void getHeadersTest() { + MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); + headers.add(Constants.HttpHeaders.ONAP_PARTNER_NAME, "SO"); + headers.add("Authorization", "Test"); + + String printHeaders = payloadLoggingClientFilter.getHeaders(headers); + + assertEquals("{Authorization=[***REDACTED***], X-ONAP-PartnerName=[SO]}", printHeaders); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java new file mode 100644 index 00000000..e2c5da9c --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; + +public class SimpleJaxrsHeadersMapTest { + + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + + @Test + public void convertMultivaluedMapToHashMap() { + MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); + headers.add(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + SimpleMap result = new SimpleJaxrsHeadersMap(headers); + assertEquals(invocationId, result.get(ONAPLogConstants.Headers.INVOCATION_ID)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java new file mode 100644 index 00000000..fff67768 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import javax.servlet.http.HttpServletRequest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class SimpleServletHeadersMapTest { + + @Mock + private HttpServletRequest request; + + @Spy + @InjectMocks + private SimpleServletHeadersMap map; + + @Test + public void getTest() { + when(request.getHeader("testHeader")).thenReturn("testResult"); + String result = map.get("testHeader"); + + assertEquals("testResult", result); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogAdapterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogAdapterTest.java new file mode 100644 index 00000000..9549eaa9 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogAdapterTest.java @@ -0,0 +1,437 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.ref.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.event.Level; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.Test; + +import javax.xml.bind.DatatypeConverter; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.hamcrest.core.IsSame.sameInstance; +import static org.hamcrest.core.StringEndsWith.endsWith; +import static org.hamcrest.number.OrderingComparison.lessThan; + +/** + * Tests for {@link ONAPLogAdapter}. + */ +public class ONAPLogAdapterTest { + + /** + * Ensure that MDCs are cleared after each testcase. + */ + @AfterMethod + public void resetMDCs() { + MDC.clear(); + } + + /** + * Test nullcheck. + */ + @Test + public void testCheckNotNull() { + + ONAPLogAdapter.checkNotNull(""); + + try { + ONAPLogAdapter.checkNotNull(null); + Assert.fail("Should throw NullPointerException"); + } + catch (final NullPointerException e) { + + } + } + + /** + * Test defaulting of nulls. + */ + @Test + public void testDefaultToEmpty() { + assertThat(ONAPLogAdapter.defaultToEmpty("123"), is("123")); + assertThat(ONAPLogAdapter.defaultToEmpty(Integer.valueOf(1984)), is("1984")); + assertThat(ONAPLogAdapter.defaultToEmpty(null), is("")); + } + + /** + * Test defaulting of nulls. + */ + @Test + public void testDefaultToUUID() { + assertThat(ONAPLogAdapter.defaultToUUID("123"), is("123")); + UUID.fromString(ONAPLogAdapter.defaultToUUID(null)); + } + + /** + * Test ENTERING. + */ + @Test + public void testEntering() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + http.setRequestURI("uri123"); + http.setServerName("local123"); + http.setRemoteAddr("remote123"); + http.addHeader("X-ONAP-RequestID", "request123"); + http.addHeader("X-InvocationID", "invocation123"); + http.addHeader("X-ONAP-PartnerName", "partner123"); + + try { + adapter.getServiceDescriptor().setServiceName("uri123"); + adapter.entering(http); + final Map<String, String> mdcs = MDC.getCopyOfContextMap(); + assertThat(mdcs.get("RequestID"), is("request123")); + assertThat(mdcs.get("PartnerName"), is("partner123")); + assertThat(mdcs.get("ServiceName"), is("uri123")); + assertThat(mdcs.get("ServerFQDN"), is("local123")); + assertThat(mdcs.get("ClientIPAddress"), is("remote123")); + + // Timestamp format and value: + + final String invokeTimestampString = mdcs.get("InvokeTimestamp"); + assertThat(invokeTimestampString, notNullValue()); + assertThat(invokeTimestampString, endsWith("Z")); + final long invokeTimestamp = DatatypeConverter.parseDateTime(invokeTimestampString).getTimeInMillis(); + assertThat(Math.abs(System.currentTimeMillis() - invokeTimestamp), lessThan(5000L)); + } + finally { + MDC.clear(); + } + } + + /** + * Test ENTERING with an EMPTY_STRING serviceName. + */ + @Test + public void testEnteringWithEMPTY_STRING_serviceName() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + http.setRequestURI("uri123"); + http.setServerName("local123"); + http.setRemoteAddr("remote123"); + http.addHeader("X-ONAP-RequestID", "request123"); + http.addHeader("X-InvocationID", "invocation123"); + http.addHeader("X-ONAP-PartnerName", "partner123"); + + try { + // an empty string should kick in setting the actual service name (treated same as null) + adapter.getServiceDescriptor().setServiceName(""); + adapter.entering(http); + final Map<String, String> mdcs = MDC.getCopyOfContextMap(); + assertThat(mdcs.get("RequestID"), is("request123")); + assertThat(mdcs.get("PartnerName"), is("partner123")); + assertThat(mdcs.get("ServiceName"), is("uri123")); + assertThat(mdcs.get("ServerFQDN"), is("local123")); + assertThat(mdcs.get("ClientIPAddress"), is("remote123")); + + // Timestamp format and value: + + final String invokeTimestampString = mdcs.get("InvokeTimestamp"); + assertThat(invokeTimestampString, notNullValue()); + assertThat(invokeTimestampString, endsWith("Z")); + final long invokeTimestamp = DatatypeConverter.parseDateTime(invokeTimestampString).getTimeInMillis(); + assertThat(Math.abs(System.currentTimeMillis() - invokeTimestamp), lessThan(5000L)); + } + finally { + MDC.clear(); + } + } + + @Test + public void testSetServiceDescriptor() { + final ONAPLogAdapter.ServiceDescriptor override = new ONAPLogAdapter.ServiceDescriptor(); + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final ONAPLogAdapter.ServiceDescriptor before = adapter.getServiceDescriptor(); + adapter.setServiceDescriptor(override); + final ONAPLogAdapter.ServiceDescriptor after = adapter.getServiceDescriptor(); + assertThat(after, not(sameInstance(before))); + assertThat(after, is(override)); + } + + @Test + public void testSetResponseDescriptor() { + final ONAPLogAdapter.ResponseDescriptor override = new ONAPLogAdapter.ResponseDescriptor(); + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final ONAPLogAdapter.ResponseDescriptor before = adapter.getResponseDescriptor(); + adapter.setResponseDescriptor(override); + final ONAPLogAdapter.ResponseDescriptor after = adapter.getResponseDescriptor(); + assertThat(after, not(sameInstance(before))); + assertThat(after, is(override)); + } + + @Test + public void testUnwrap() { + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + assertThat(adapter.unwrap(), is(logger)); + } + + /** + * Test EXITING. + */ + @Test + public void testExiting() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + try { + MDC.put("somekey", "somevalue"); + assertThat(MDC.get("somekey"), is("somevalue")); + adapter.exiting(); + assertThat(MDC.get("somekey"), nullValue()); + } + finally { + MDC.clear(); + } + } + + /** + * Test INVOKE. + */ + @Test + public void testInvokeSyncAsyncNull() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final UUID syncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(syncUUID, notNullValue()); + + final UUID asyncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(asyncUUID, notNullValue()); + + final UUID agnosticUUID = adapter.invoke((ONAPLogConstants.InvocationMode)null); + assertThat(agnosticUUID, notNullValue()); + + } + + /** + * Test INVOKE, with RequestAdapter. + */ + @Test + public void testInvokeWithAdapter() throws Exception { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final Map<String, String> headers = new HashMap<>(); + final ONAPLogAdapter.RequestBuilder builder = new ONAPLogAdapter.RequestBuilder<ONAPLogAdapter.RequestBuilder>() { + @Override + public ONAPLogAdapter.RequestBuilder setHeader(final String name, final String value) { + headers.put(name, value); + return this; + } + }; + + try { + final UUID uuid = adapter.invoke(builder, ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(uuid, notNullValue()); + assertThat(headers.get(ONAPLogConstants.Headers.INVOCATION_ID), is(uuid.toString())); + assertThat(headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME), is(true)); + assertThat(headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID), is(true)); + } + finally { + MDC.clear(); + } + } + + /** + * Test INVOKE, with RequestAdapter. + */ + @Test + public void testInvokeWithAdapterAndNull() throws Exception { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final Map<String, String> headers = new HashMap<>(); + final ONAPLogAdapter.RequestBuilder builder = new ONAPLogAdapter.RequestBuilder<ONAPLogAdapter.RequestBuilder>() { + @Override + public ONAPLogAdapter.RequestBuilder setHeader(final String name, final String value) { + headers.put(name, value); + return this; + } + }; + + try { + final UUID uuid = adapter.invoke(builder); + assertThat(uuid, notNullValue()); + assertThat(headers.get(ONAPLogConstants.Headers.INVOCATION_ID), is(uuid.toString())); + assertThat(headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME), is(true)); + assertThat(headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID), is(true)); + } + finally { + MDC.clear(); + } + } + + @Test + public void testHttpServletRequestAdapter() { + + final UUID uuid = UUID.randomUUID(); + final MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("uuid", uuid.toString()); + request.setRequestURI("/ctx0"); + request.setServerName("srv0"); + + final ONAPLogAdapter.HttpServletRequestAdapter adapter + = new ONAPLogAdapter.HttpServletRequestAdapter(request); + assertThat(adapter.getHeader("uuid"), is(uuid.toString())); + assertThat(adapter.getRequestURI(), is("/ctx0")); + assertThat(adapter.getServerAddress(), is("srv0")); + } + + @Test + public void testServiceDescriptor() { + final String uuid = UUID.randomUUID().toString(); + + final ONAPLogAdapter.ServiceDescriptor adapter + = new ONAPLogAdapter.ServiceDescriptor(); + adapter.setServiceUUID(uuid); + adapter.setServiceName("name0"); + + assertThat(MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID), nullValue()); + + adapter.setMDCs(); + + assertThat(MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME), is("name0")); + assertThat(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID), is(uuid)); + } + + @Test + public void testResponseDescriptor() { + final String uuid = UUID.randomUUID().toString(); + + final ONAPLogAdapter.ResponseDescriptor adapter + = new ONAPLogAdapter.ResponseDescriptor(); + adapter.setResponseCode("code0"); + adapter.setResponseDescription("desc0"); + adapter.setResponseSeverity(Level.INFO); + adapter.setResponseStatus(ONAPLogConstants.ResponseStatus.COMPLETE); + + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_SEVERITY), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE), nullValue()); + + adapter.setMDCs(); + + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE), is("code0")); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION), is("desc0")); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_SEVERITY), is("INFO")); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE), is("COMPLETE")); + } + + /** + * Exercise the contract, for a caller that's happy to have their + * service name automatically derived. (This validates nothing + * and achieves nothing; it's just to provide an example of minimal usage). + */ + @Test + public void testContract() { + + // Note no wrapper around HttpServletRequest, which will work for + // most invocations (since they come via HTTP), but otherwise + // can implement your own RequestAdapter. + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + + // Immediately log ENTERING marker, with global MDCs. + + adapter.entering(http); + try { + + // Generate (and log) an invocationID, then use it to + // invoke another component. + + final RESTClient client = new RESTClient(); // implements ONAPLogAdapter.RequestBuilder<RESTClient>. + adapter.invoke(client, ONAPLogConstants.InvocationMode.SYNCHRONOUS); + final RESTRequest request = null; // TODO: build real request. + final RESTResponse response = client.execute(request); // TODO: handle real response. + + // Set response details prior to #exiting. + // (Obviously there'd be errorhandling, etc. IRL). + + adapter.getResponseDescriptor() + .setResponseCode((String)null) + .setResponseSeverity(Level.INFO) + .setResponseStatus(ONAPLogConstants.ResponseStatus.COMPLETE); + } + finally { + + // Return, logging EXIT marker, with response MDCs. + + adapter.exiting(); + } + } + + /** + * Dummy class, for example code. + */ + static class RESTClient implements ONAPLogAdapter.RequestBuilder<RESTClient> { + + @Override + public RESTClient setHeader(final String name, final String value) { + return null; + } + + RESTResponse execute(RESTRequest request) { + return null; + } + } + + /** + * Dummy class, for example code. + */ + static class RESTRequest { + + } + + /** + * Dummy class, for example code. + */ + static class RESTResponse { + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogConstantsTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogConstantsTest.java new file mode 100644 index 00000000..9a46f05b --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogConstantsTest.java @@ -0,0 +1,132 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.logging.ref.slf4j; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; + +/** + * Tests for {@link ONAPLogConstants}. + */ +public class ONAPLogConstantsTest { + + @Test + public void testConstructors() throws Exception { + assertInaccessibleConstructor(ONAPLogConstants.class); + assertInaccessibleConstructor(ONAPLogConstants.MDCs.class); + assertInaccessibleConstructor(ONAPLogConstants.Markers.class); + assertInaccessibleConstructor(ONAPLogConstants.Headers.class); + } + + @Test + public void testConstructorUnsupported() throws Exception { + try { + Constructor<?> c = ONAPLogConstants.class.getDeclaredConstructors()[0]; + c.setAccessible(true); + c.newInstance(); + Assert.fail("Should fail for hidden constructor."); + } + catch (final InvocationTargetException e) { + assertThat(e.getCause(), instanceOf(UnsupportedOperationException.class)); + } + } + + @Test + public void testHeaders() { + assertThat(ONAPLogConstants.Headers.REQUEST_ID, is("X-ONAP-RequestID")); + assertThat(ONAPLogConstants.Headers.PARTNER_NAME, is("X-ONAP-PartnerName")); + } + + @Test + public void testMarkers() { + assertThat(ONAPLogConstants.Markers.ENTRY.toString(), is("ENTRY")); + assertThat(ONAPLogConstants.Markers.EXIT.toString(), is("EXIT")); + assertThat(ONAPLogConstants.Markers.INVOKE.toString(), is("INVOKE")); + assertThat(ONAPLogConstants.Markers.INVOKE_ASYNCHRONOUS.toString(), is("INVOKE [ ASYNCHRONOUS ]")); + assertThat(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS.toString(), is("INVOKE [ SYNCHRONOUS ]")); + } + + @Test + public void testInvocationMode() { + assertThat(ONAPLogConstants.InvocationMode.SYNCHRONOUS.getMarker(), + is(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS)); + assertThat(ONAPLogConstants.InvocationMode.ASYNCHRONOUS.getMarker(), + is(ONAPLogConstants.Markers.INVOKE_ASYNCHRONOUS)); + } + + @Test + public void testInvocationModeToString() { + assertThat(ONAPLogConstants.InvocationMode.SYNCHRONOUS.toString(), + is("SYNCHRONOUS")); + } + + @Test + public void testResponseStatus() { + assertThat(ONAPLogConstants.ResponseStatus.COMPLETE.toString(), is("COMPLETE")); + assertThat(ONAPLogConstants.ResponseStatus.ERROR.toString(), is("ERROR")); + } + + @Test + public void testMDCs() { + + assertThat(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS.toString(), is("ClientIPAddress")); + assertThat(ONAPLogConstants.MDCs.SERVER_FQDN.toString(), is("ServerFQDN")); + + assertThat(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP.toString(), is("EntryTimestamp")); + assertThat(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP.toString(), is("InvokeTimestamp")); + + assertThat(ONAPLogConstants.MDCs.REQUEST_ID.toString(), is("RequestID")); + assertThat(ONAPLogConstants.MDCs.INVOCATION_ID.toString(), is("InvocationID")); + assertThat(ONAPLogConstants.MDCs.PARTNER_NAME.toString(), is("PartnerName")); + assertThat(ONAPLogConstants.MDCs.INSTANCE_UUID.toString(), is("InstanceID")); + assertThat(ONAPLogConstants.MDCs.SERVICE_NAME.toString(), is("ServiceName")); + assertThat(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME.toString(), is("TargetServiceName")); + + } + + static void assertInaccessibleConstructor(final Class<?> c) throws Exception { + try { + c.getDeclaredConstructors()[0].newInstance(); + Assert.fail("Should fail for hidden constructor."); + } + catch (final IllegalAccessException e) { + + } + + try { + final Constructor<?> constructor = c.getDeclaredConstructors()[0]; + constructor.setAccessible(true); + constructor.newInstance(); + Assert.fail("Should fail even when invoked."); + } + catch (final InvocationTargetException e) { + assertThat(e.getCause(), instanceOf(UnsupportedOperationException.class)); + } + } +} diff --git a/aai-els-onap-logging/src/test/resources/aaiconfig.properties b/aai-els-onap-logging/src/test/resources/aaiconfig.properties new file mode 100644 index 00000000..3162e3ae --- /dev/null +++ b/aai-els-onap-logging/src/test/resources/aaiconfig.properties @@ -0,0 +1,19 @@ +# +# ============LICENSE_START======================================================= +# org.onap.aai +# ================================================================================ +# Copyright © 2017-18 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +aai.logging.maxStackTraceEntries=10 diff --git a/aai-els-onap-logging/src/test/resources/application.properties b/aai-els-onap-logging/src/test/resources/application.properties new file mode 100644 index 00000000..df8fd64d --- /dev/null +++ b/aai-els-onap-logging/src/test/resources/application.properties @@ -0,0 +1,29 @@ +# +# ============LICENSE_START======================================================= +# org.onap.aai +# ================================================================================ +# Copyright © 2017-18 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +spring.application.name=AAI Microservice +server.port=8446 +server.local.startpath=/opt/app/aai +schema.version.list=v10,v11,v12,v13,v14,v15,v16,v17,v18,v19 +server.certs.location=certificates +server.ssl.key-store=keystore.jks +server.ssl.key-store.pkcs12=keystore.pkcs12 +server.ssl.trust-store=truststore.jks +schema.service.ssl.key-store=${server.local.startpath}/etc/auth/aai-client-cert.p12 +schema.service.ssl.trust-store=${server.local.startpath}/etc/auth/aai_keystore.jks + diff --git a/aai-els-onap-logging/src/test/resources/error.properties b/aai-els-onap-logging/src/test/resources/error.properties new file mode 100644 index 00000000..c1470dae --- /dev/null +++ b/aai-els-onap-logging/src/test/resources/error.properties @@ -0,0 +1,161 @@ +#------------------------------------------------------------------------------- ---------- +#Key=Disposition:Category:Severity:Error Code:HTTP ResponseCode:RESTError Code:Error Message +#------------------------------------------------------------------------------- ---------- +# General success +AAI_0000=0:0:INFO:0000:200:0000:Success:0 + +# health check success +AAI_0001=0:0:INFO:0001:200:0001:Success X-FromAppId=%1 X-TransactionId=%2:0 +AAI_0002=0:0:INFO:0002:200:0001:Successful health check:0 + +# Success with additional info +AAI_0003=0:3:INFO:0003:202:0003:Success with additional info performing %1 on %2. Added %3 with key %4:0 +AAI_0004=0:3:INFO:0004:202:0003:Added prerequisite object to db:0 + +#--- aairest: 3000-3299 +# svc errors +AAI_3000=5:2:INFO:3000:400:3000:Invalid input performing %1 on %2:300 +AAI_3001=5:6:INFO:3001:404:3001:Resource not found for %1 using id %2:300 +AAI_3002=5:1:WARN:3002:400:3002:Error writing output performing %1 on %2:300 +AAI_3003=5:1:WARN:3003:400:3003:Failed to make edge to missing target node of type %3 with keys %4 performing %1 on %2:400 +AAI_3005=5:6:WARN:3005:404:3001:Node cannot be directly accessed for read, must be accessed via ancestor(s):100 +AAI_3006=5:6:WARN:3006:404:3001:Node cannot be directly accessed for write, must be accessed via ancestor(s):100 +AAI_3007=5:6:INFO:3007:410:3007:This version (%1) of the API is retired, please migrate to %2:500 +AAI_3008=5:6:ERROR:3008:400:3008:URI is not encoded in UTF-8:300 +AAI_3009=5:6:WARN:3009:400:3009:Malformed URL:300 +AAI_3010=5:6:WARN:3010:400:3002:Cannot write via this URL:100 +AAI_3011=5:6:WARN:3011:400:3000:Unknown XML namespace used in payload:300 +AAI_3012=5:6:WARN:3012:400:3012:Unrecognized AAI function:300 +AAI_3013=5:6:WARN:3013:400:3013:Query payload missing required parameters %1:300 +AAI_3014=5:6:WARN:3014:400:3014:Query payload is invalid %1:300 +AAI_3015=5:6:INFO:3015:410:3015:The %1 capability is retired, please contact the A&AI SE team to identify a replacement query:500 +AAI_3016=5:6:INFO:3007:400:3016:Request uri is not valid, please check the version %1:500 +AAI_3017=5:6:INFO:3007:400:3016:Request uri is not valid, please check the uri %1:500 +AAI_3025=5:4:FATAL:3025:500:3025:Error connecting to Schema Service:400 +AAI_3026=5:4:FATAL:3026:500:3026:Error reading OXM from Schema Service:400 +AAI_3027=5:4:FATAL:3026:500:3026:Error reading EdgeRules from Schema Service:400 + +# pol errors +AAI_3100=5:1:WARN:3100:400:3100:Unsupported operation %1:300 +AAI_3101=5:1:WARN:3101:403:3101:Attempt by client %1 to execute API %2:100 +AAI_3102=5:1:WARN:3102:400:3102:Error parsing input performing %1 on %2:300 +AAI_3300=5:1:WARN:3300:403:3300:Unauthorized:100 +AAI_3301=5:1:WARN:3301:401:3301:Stale credentials:100 +AAI_3302=5:1:WARN:3302:401:3301:Not authenticated:100 +AAI_3303=5:1:WARN:3303:403:3300:Too many objects would be returned by this request, please refine your request and retry:500 + +#--- aaigen: 4000-4099 +AAI_4000=5:4:ERROR:4000:500:3002:Internal Error:900 +AAI_4001=5:4:FATAL:4001:500:3002:Configuration file not found:500 +AAI_4002=5:4:FATAL:4002:500:3002:Error reading Configuration file:500 +AAI_4003=5:4:ERROR:4003:500:3002:Error writing to log file:500 +AAI_4004=5:4:FATAL:4004:500:3002:Error reading/parsing the error properties file:500 +AAI_4005=5:4:FATAL:4005:500:3002:Missing or invalid configuration parameter:500 +AAI_4006=5:4:FATAL:4006:500:3002:Unexpected error in service:500 +AAI_4007=5:4:WARN:4007:500:3102:Input parsing error:500 +AAI_4008=5:4:ERROR:4008:500:3002:Output parsing error:500 +AAI_4009=4:0:WARN:4009:400:3000:Invalid X-FromAppId in header:300 +AAI_4010=4:0:WARN:4010:400:3000:Invalid X-TransactionId in header:300 +AAI_4011=5:4:ERROR:4011:500:3002:Missing data for REST error response:500 +AAI_4014=4:0:WARN:4014:400:3000:Invalid Accept header:300 +AAI_4015=4:0:WARN:4015:400:3000:You must provide at least one indexed property:400 +AAI_4016=4:0:WARN:4016:400:3000:The depth parameter must be a number or the string "all":300 +AAI_4017=5:2:INFO:4017:400:3000:Could not set property:300 +AAI_4018=5:2:WARN:4018:400:3000:Unable to convert the string to integer:500 +AAI_4019=4:0:WARN:4019:400:3000:Request failed due to violations:400 +AAI_4020=5:4:ERROR:4020:500:3000:Unknown exception to calling validation service:500 +AAI_4021=5:4:FATAL:3025:500:4021:Error connecting to Validation Service:400 + +#--- aaidbmap: 5102-5199 +AAI_5102=5:4:FATAL:5102:500:3002:Graph database is null after open:400 +AAI_5105=5:4:ERROR:5105:500:3002:Unexpected error reading/updating database:300 +AAI_5106=5:4:WARN:5106:404:3001:Node not found:300 +AAI_5107=5:2:WARN:5107:400:3000:Required information missing:300 +AAI_5108=5:2:WARN:5108:200:0:Unexpected information in request being ignored:300 + +#--- aaidbgen: 6101-6199 +AAI_6101=5:4:ERROR:6101:500:3002:null JanusGraph object passed:400 +AAI_6102=5:4:WARN:6102:400:3000:Passed-in property is not valid for this nodeType:400 +AAI_6103=5:4:WARN:6103:400:3000:Required Node-property not found in input data:400 +AAI_6104=5:4:WARN:6104:400:3000:Required Node-property was passed with no data:400 +AAI_6105=5:4:WARN:6105:400:3000:Node-Key-Property not defined in DbMaps:400 +AAI_6106=5:4:WARN:6106:400:3000:Passed-in property is not valid for this edgeType:400 +AAI_6107=5:4:WARN:6107:400:3000:Required Edge-property not found in input data:400 +AAI_6108=5:4:WARN:6108:400:3000:Required Edge-property was passed with no data:400 +AAI_6109=5:4:WARN:6109:400:3000:Bad dependent Node value:400 +AAI_6110=5:4:ERROR:6110:400:3100:Node cannot be deleted:500 +AAI_6111=5:4:WARN:6111:400:3000:JSON processing error:300 +AAI_6112=5:4:ERROR:6112:400:3000:More than one node found by getUniqueNode():400 +AAI_6114=5:4:INFO:6114:404:3001:Node Not Found:300 +AAI_6115=5:4:ERROR:6115:400:3000:Unrecognized NodeType:400 +AAI_6116=5:4:ERROR:6116:400:3000:Unrecognized Property:400 +AAI_6117=5:4:ERROR:6117:400:3000:Uniqueness constraint violated:400 +AAI_6118=5:4:WARN:6118:400:3000:Required Field not passed.:400 +AAI_6120=5:4:WARN:6120:400:3000:Bad Parameter Passed:300 +AAI_6121=5:4:ERROR:6121:400:3000:Problem with internal AAI reference data:400 +AAI_6122=5:4:ERROR:6122:400:3000:Data Set not complete in DB for this request:400 +AAI_6123=5:4:ERROR:6123:500:3000:Bad Data found by DataGrooming Tool - Investigate:300 +AAI_6124=5:4:ERROR:6124:500:3000:File read/write error:500 +AAI_6125=5:4:WARN:6125:500:3000:Problem Pulling Data Set:500 +AAI_6126=5:4:ERROR:6126:400:3000:Edge cannot be deleted:400 +AAI_6127=5:4:INFO:6127:404:3001:Edge Not Found:400 +AAI_6128=5:4:INFO:6128:500:3000:Unexpected error:900 +AAI_6129=5:4:INFO:6129:404:3003:Error making edge to target node:400 +AAI_6130=5:4:WARN:6130:412:3000:Precondition Required:300 +AAI_6131=5:4:WARN:6131:412:3000:Precondition Failed:300 +AAI_6132=5:4:WARN:6132:400:3000:Bad Model Definition:500 +AAI_6133=5:4:WARN:6133:400:3000:Bad Named Query Definition:500 +AAI_6134=5:4:ERROR:6134:500:6134:Could not persist transaction to storage back end. Exhausted retry amount:500 +AAI_6135=5:4:WARN:6135:412:3000:Resource version specified on create:300 +AAI_6136=5:4:ERROR:6136:400:3000:Object cannot hold multiple items:400 +AAI_6137=5:4:ERROR:6137:400:3000:Cannot perform writes on multiple vertices:400 +AAI_6138=5:4:ERROR:6138:400:3000:Cannot delete multiple vertices:400 +AAI_6139=5:4:ERROR:6139:404:3000:Attempted to add edge to vertex that does not exist:400 +AAI_6140=5:4:ERROR:6140:400:3000:Edge multiplicity violated:400 +AAI_6141=5:4:WARN:6141:400:3000:Please Refine Query:400 +AAI_6142=5:4:INFO:6142:400:3000:Retrying transaction:900 +AAI_6143=5:4:INFO:6143:400:3000:Ghost vertex found:400 +AAI_6144=5:4:WARN:6144:400:3000:Cycle found in graph:400 +AAI_6145=5:4:ERROR:6145:400:3000:Cannot create a nested/containment edge via relationship:400 +AAI_6146=5:4:ERROR:6146:400:3000:Ambiguous identity map found, use a URI instead:300 +AAI_6147=5:4:ERROR:6147:400:3000:Payload Limit Reached, reduce payload:300 +AAI_6148=5:4:ERROR:6148:400:3000:More than one node found %1:300 +AAI_6149=5:4:ERROR:6149:404:3000:No relationship was found:300 + +#--- aaicsvp: 7101-7199 +AAI_7101=5:4:ERROR:7101:500:3002:Unexpected error in CSV file processing:900 +AAI_7102=5:4:ERROR:7102:500:3002:Error in cleanup temporary directory:500 +AAI_7104=5:4:ERROR:7104:500:3002:Failed to create directory:500 +AAI_7105=5:4:ERROR:7105:500:3002:Temporary directory exists:500 +AAI_7106=5:4:ERROR:7106:500:3002:Cannot delete:500 +AAI_7107=5:4:ERROR:7107:500:3002:Input file does not exist:500 +AAI_7108=5:4:ERROR:7108:500:3002:Output file does not exist:500 +AAI_7109=5:4:ERROR:7109:500:3002:Error closing file:500 +AAI_7110=5:4:ERROR:7110:500:3002:Error loading/reading properties file:500 +AAI_7111=5:4:ERROR:7111:500:3002:Error executing shell script:900 +AAI_7112=5:4:ERROR:7112:500:3002:Error creating output file:500 +AAI_7113=5:4:ERROR:7113:500:3002:Trailer record error:300 +AAI_7114=5:4:ERROR:7114:500:3002:Input file error:300 +AAI_7115=5:4:ERROR:7115:500:3002:Unexpected error:900 +AAI_7116=5:4:ERROR:7116:500:3002:Request error:900 +AAI_7117=5:4:ERROR:7117:500:3002:Error in get http client object:500 +AAI_7118=5:4:ERROR:7118:500:3002:Script Error:900 +AAI_7119=5:4:ERROR:7119:500:3002:Unknown host:900 + +#--- DMaaP related errors +AAI_7304=4:5:ERROR:7304:500:3002:Error reaching DMaaP to send event:200 +AAI_7350=5:4:ERROR:7305:500:3002:Notification event creation failed:500 + +#--- aairestctlr: 7401-7499 +AAI_7401=5:4:ERROR:7401:500:3002:Error connecting to AAI REST API:200 +AAI_7402=5:4:ERROR:7402:500:3002:Unexpected error:900 +AAI_7403=5:4:WARN:7403:400:3001:Request error:900 +AAI_7404=5:4:INFO:7404:404:3001:Node not found:300 +AAI_7405=5:4:WARN:7405:200:0:UUID not formatted correctly, generating UUID:300 +AAI_7406=5:4:ERROR:7406:400:7406:Request Timed Out:200 + +#--- aaiauth: 9101-9199 +AAI_9101=5:0:WARN:9101:403:3300:User is not authorized to perform function:100 +AAI_9107=5:0:WARN:9107:403:3300:SSL is not provided in request, please contact admin:100 +AAI_9108=5:0:WARN:9107:403:3300:Basic auth credentials is not provided in the request:100 +AAI_9109=5:0:WARN:9109:403:3300:User is not allowed to perform implicit delete:500 diff --git a/aai-els-onap-logging/src/test/resources/logback.xml b/aai-els-onap-logging/src/test/resources/logback.xml new file mode 100644 index 00000000..7bf5d98f --- /dev/null +++ b/aai-els-onap-logging/src/test/resources/logback.xml @@ -0,0 +1,168 @@ +<!-- + ============LICENSE_START======================================================= + org.onap.aai + ================================================================================ + Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= +--> +<configuration scan="true" scanPeriod="60 seconds" debug="false"> + <statusListener class="ch.qos.logback.core.status.NopStatusListener" /> + + <property resource="application.properties" /> + + <property name="namespace" value="aai-resources"/> + + <property name="AJSC_HOME" value="${AJSC_HOME:-.}" /> + <jmxConfigurator /> + <property name="logDirectory" value="${AJSC_HOME}/logs" /> + + <property name="p_tim" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}"/> + <property name="p_lvl" value="%level"/> + <property name="p_log" value="%logger"/> + <property name="p_mdc" value="%replace(%replace(%replace(%mdc){'\t','\\\\t'}){'\n', '\\\\n'}){'\\|', '!'}"/> + <property name="p_msg" value="%replace(%replace(%msg){'\t', '\\\\t'}){'\n','\\\\n'}"/> + <property name="p_exc" value="%replace(%replace(%rootException){'\t', '\\\\t'}){'\n','\\\\n'}"/> + <property name="p_mak" value="%replace(%replace(%marker){'\t', '\\\\t'}){'\n','\\\\n'}"/> + <property name="p_thr" value="%thread"/> + <property name="pattern" value="%nopexception${p_tim}\t${p_thr}\t${p_lvl}\t${p_log}\t${p_mdc}\t${p_msg}\t${p_exc}\t${p_mak}\t%n"/> + <!-- Patterns from onap demo --> + <property name="errorPattern" value="%X{LogTimestamp}|%X{RequestID}|%thread|%replace(%X{ServiceName}){'\\|', '!'}|%X{PartnerName}|%X{TargetEntity}|%replace(%X{TargetServiceName}){'\\|', '!'}|%.-5level|%X{ErrorCode}|%X{ErrorDesc}|%msg%n" /> + <property name="debugPattern" value="%X{LogTimestamp}|%X{RequestID}|%msg\t${p_mdc}\t${p_msg}\t${p_exc}\t${p_mak}\t|^%n" /> + <property name="auditPattern" value="%X{EntryTimestamp}|%X{LogTimestamp}|%X{RequestID}|%X{ServiceInstanceID}|%thread||%replace(%X{ServiceName}){'\\|', '!'}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDesc}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}||||${p_mak}|${p_mdc}|||%msg%n" /> + <property name="metricPattern" value="%X{InvokeTimestamp}|%X{LogTimestamp}|%X{RequestID}|%X{ServiceInstanceID}|%thread||%replace(%X{ServiceName}){'\\|', '!'}|%X{PartnerName}|%X{TargetEntity}|%replace(%X{TargetServiceName}){'\\|', '!'}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDesc}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}||||%X{TargetVirtualEntity}|${p_mak}|${p_mdc}|||%msg%n" /> + <property name="transLogPattern" value="%X{LogTimestamp}|%date{yyyy-MM-dd'T'HH:mm:ss.SSSZ, UTC}|%X{RequestID}|%X{ServiceInstanceID}|%-10t|%X{ServerFQDN}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%replace(%replace(%X{ResponseDesc}){'\\|', '!'}){'\r|\n', '^'}|%X{InstanceUUID}|%level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{clientIpAddress}||%X{unused}|%X{processKey}|%X{customField1}|%X{customField2}|%X{customField3}|%X{customField4}|co=%X{PartnerName}:%m%n"/> + <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" /> + <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" /> + <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" /> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern> + %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} + </pattern> + </encoder> + </appender> + + + <appender name="asyncMETRIC" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="METRIC"/> + </appender> + + <appender name="DEBUG" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.LevelFilter"> + <level>DEBUG</level> + <onMatch>ACCEPT</onMatch> + <onMismatch>DENY</onMismatch> + </filter> + <file>${logDirectory}/debug.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/debug.log.%d{yyyy-MM-dd}</fileNamePattern> + </rollingPolicy> + <encoder> + <pattern>${debugPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncDEBUG" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <appender-ref ref="DEBUG" /> + <includeCallerData>true</includeCallerData> + </appender> + <appender name="ERROR" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/error.log</file> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/error.log.%d{yyyy-MM-dd-HH-mm} + </fileNamePattern> + <maxHistory>1</maxHistory> + <cleanHistoryOnStart>true</cleanHistoryOnStart> + </rollingPolicy> + + <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>WARN</level> + </filter> + <encoder> + <pattern>${errorPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncERROR" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <appender-ref ref="ERROR"/> + </appender> + + <appender name="AUDIT" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/audit.log</file> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/audit.log.%d{yyyy-MM-dd} + </fileNamePattern> + </rollingPolicy> + <encoder> + <pattern>${auditPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncAUDIT" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="AUDIT" /> + </appender> + + <appender name="auth" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>DEBUG</level> + </filter> + <file>${logDirectory}/auth/auth.log</file> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/auth/auth.log.%d{yyyy-MM-dd} + </fileNamePattern> + </rollingPolicy> + <encoder> + <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ, UTC}[%thread] %-5level %logger{1024} - %msg%n</pattern> + </encoder> + </appender> + <appender name="asyncAUTH" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="auth" /> + </appender> + <!-- logback internals logging --> + + <logger name="ch.qos.logback.classic" level="WARN" /> + <logger name="ch.qos.logback.core" level="WARN" /> + + <logger name="com.jayway.jsonpath" level="WARN" /> + + <logger name="org.apache" level="OFF" /> + + <logger name="org.onap.aai" level="DEBUG" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + <logger name="org.onap.aai.aaf.auth" level="DEBUG" additivity="false"> + <appender-ref ref="asyncAUTH" /> + </logger> + <logger name="org.onap.aai.logging.ErrorLogHelper" level="WARN"> + <appender-ref ref="asyncERROR"/> + </logger> + + <root level="DEBUG"> + <appender-ref ref="STDOUT" /> + </root> +</configuration> |