SLF4J adapter (in 'common') + call graph demo
[logging-analytics.git] / reference / slf4j-reference / src / test / java / org / onap / logging / ref / slf4j / common / ONAPLogAdapterTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.logging
4  * ================================================================================
5  * Copyright © 2018 Amdocs
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *    http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.logging.ref.slf4j.common;
23
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.UUID;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.slf4j.MDC;
31 import org.slf4j.event.Level;
32 import org.springframework.mock.web.MockHttpServletRequest;
33 import org.testng.Assert;
34 import org.testng.annotations.AfterMethod;
35 import org.testng.annotations.Test;
36
37 import static org.hamcrest.MatcherAssert.assertThat;
38 import static org.hamcrest.core.Is.is;
39 import static org.hamcrest.core.IsNull.notNullValue;
40 import static org.hamcrest.core.IsNull.nullValue;
41
42 /**
43  * Tests for {@link ONAPLogAdapter}.
44  */
45 public class ONAPLogAdapterTest {
46
47     /**
48      * Ensure that MDCs are cleared after each testcase.
49      */
50     @AfterMethod
51     public void resetMDCs() {
52         MDC.clear();
53     }
54
55     /**
56      * Test nullcheck.
57      */
58     @Test
59     public void testCheckNotNull() {
60
61         ONAPLogAdapter.checkNotNull("");
62
63         try {
64             ONAPLogAdapter.checkNotNull(null);
65             Assert.fail("Should throw NullPointerException");
66         }
67         catch (final NullPointerException e) {
68
69         }
70     }
71
72     /**
73      * Test defaulting of nulls.
74      */
75     @Test
76     public void testDefaultToEmpty() {
77         assertThat(ONAPLogAdapter.defaultToEmpty("123"), is("123"));
78         assertThat(ONAPLogAdapter.defaultToEmpty(Integer.valueOf(1984)), is("1984"));
79         assertThat(ONAPLogAdapter.defaultToEmpty(null), is(""));
80     }
81
82     /**
83      * Test defaulting of nulls.
84      */
85     @Test
86     public void testDefaultToUUID() {
87         assertThat(ONAPLogAdapter.defaultToUUID("123"), is("123"));
88         UUID.fromString(ONAPLogAdapter.defaultToUUID(null));
89     }
90
91     /**
92      * Test ENTERING.
93      */
94     @Test
95     public void testEntering() {
96
97         final Logger logger = LoggerFactory.getLogger(this.getClass());
98         final ONAPLogAdapter adapter = new ONAPLogAdapter(logger);
99         final MockHttpServletRequest http = new MockHttpServletRequest();
100         http.setRequestURI("uri123");
101         http.setServerName("local123");
102         http.setRemoteAddr("remote123");
103         http.addHeader("X-ONAP-RequestID", "request123");
104         http.addHeader("X-ONAP-InvocationID", "invocation123");
105         http.addHeader("X-ONAP-PartnerName", "partner123");
106
107         try {
108             adapter.getServiceDescriptor().setServiceName("uri123");
109             adapter.entering(http);
110             final Map<String, String> mdcs = MDC.getCopyOfContextMap();
111             assertThat(mdcs.get("RequestID"), is("request123"));
112             assertThat(mdcs.get("InvocationID"), is("invocation123"));
113             assertThat(mdcs.get("PartnerName"), is("partner123"));
114             assertThat(mdcs.get("ServiceName"), is("uri123"));
115             assertThat(mdcs.get("ServerFQDN"), is("local123"));
116             assertThat(mdcs.get("ClientIPAddress"), is("remote123"));
117         }
118         finally {
119             MDC.clear();
120         }
121     }
122
123     /**
124      * Test EXITING.
125      */
126     @Test
127     public void testExiting() {
128
129         final Logger logger = LoggerFactory.getLogger(this.getClass());
130         final ONAPLogAdapter adapter = new ONAPLogAdapter(logger);
131
132         try {
133             MDC.put("somekey", "somevalue");
134             assertThat(MDC.get("somekey"), is("somevalue"));
135             adapter.exiting();
136             assertThat(MDC.get("somekey"), nullValue());
137         }
138         finally {
139             MDC.clear();
140         }
141     }
142
143     /**
144      * Test INVOKE.
145      */
146     @Test
147     public void testInvokeSyncAsyncNull() {
148
149         final Logger logger = LoggerFactory.getLogger(this.getClass());
150         final ONAPLogAdapter adapter = new ONAPLogAdapter(logger);
151
152         final UUID syncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS);
153         assertThat(syncUUID, notNullValue());
154
155         final UUID asyncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS);
156         assertThat(asyncUUID, notNullValue());
157
158         final UUID agnosticUUID = adapter.invoke((ONAPLogConstants.InvocationMode)null);
159         assertThat(agnosticUUID, notNullValue());
160
161     }
162
163     /**
164      * Test INVOKE, with RequestAdapter.
165      */
166     @Test
167     public void testInvokeWithAdapter() throws Exception {
168
169         final Logger logger = LoggerFactory.getLogger(this.getClass());
170         final ONAPLogAdapter adapter = new ONAPLogAdapter(logger);
171
172         final Map<String, String> headers = new HashMap<>();
173         final ONAPLogAdapter.RequestBuilder builder = new ONAPLogAdapter.RequestBuilder<ONAPLogAdapter.RequestBuilder>() {
174             @Override
175             public ONAPLogAdapter.RequestBuilder setHeader(final String name, final String value) {
176                 headers.put(name, value);
177                 return this;
178             }
179         };
180
181         try {
182             final UUID uuid = adapter.invoke(builder, ONAPLogConstants.InvocationMode.SYNCHRONOUS);
183             assertThat(uuid, notNullValue());
184             assertThat(headers.get(ONAPLogConstants.Headers.INVOCATION_ID), is(uuid.toString()));
185             assertThat(headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME), is(true));
186             assertThat(headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID), is(true));
187         }
188         finally {
189             MDC.clear();
190         }
191     }
192
193     /**
194      * Exercise the contract, for a caller that's happy to have their
195      * service name automatically derived. (This validates nothing
196      * and achieves nothing; it's just to provide an example of minimal usage).
197      */
198     @Test
199     public void testContract() {
200
201         // Note no wrapper around HttpServletRequest, which will work for
202         // most invocations (since they come via HTTP), but otherwise
203         // can implement your own RequestAdapter.
204
205         final Logger logger = LoggerFactory.getLogger(this.getClass());
206         final ONAPLogAdapter adapter = new ONAPLogAdapter(logger);
207         final MockHttpServletRequest http = new MockHttpServletRequest();
208
209         // Immediately log ENTERING marker, with global MDCs.
210
211         adapter.entering(http);
212         try {
213
214             // Generate (and log) an invocationID, then use it to
215             // invoke another component.
216
217             final RESTClient client = new RESTClient();             // implements ONAPLogAdapter.RequestBuilder<RESTClient>.
218             adapter.invoke(client, ONAPLogConstants.InvocationMode.SYNCHRONOUS);
219             final RESTRequest request = null;                       // TODO: build real request.
220             final RESTResponse response = client.execute(request);  // TODO: handle real response.
221
222             // Set response details prior to #exiting.
223             // (Obviously there'd be errorhandling, etc. IRL).
224
225             adapter.getResponseDescriptor()
226                     .setResponseCode((String)null)
227                     .setResponseSeverity(Level.INFO)
228                     .setResponseStatus(ONAPLogConstants.ResponseStatus.COMPLETED);
229         }
230         finally {
231
232             // Return, logging EXIT marker, with response MDCs.
233
234             adapter.exiting();
235         }
236     }
237
238     /**
239      * Dummy class, for example code.
240      */
241     static class RESTClient implements ONAPLogAdapter.RequestBuilder<RESTClient> {
242
243         @Override
244         public RESTClient setHeader(final String name, final String value) {
245             return null;
246         }
247
248         RESTResponse execute(RESTRequest request) {
249             return null;
250         }
251     }
252
253     /**
254      * Dummy class, for example code.
255      */
256     static class RESTRequest {
257
258     }
259
260     /**
261      * Dummy class, for example code.
262      */
263     static class RESTResponse {
264
265     }
266 }