Use BidirectionalTopicClient from policy-common
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / test / java / org / onap / policy / controlloop / actorserviceprovider / impl / HttpOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actorserviceprovider.impl;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatCode;
25 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
26 import static org.assertj.core.api.Assertions.assertThatThrownBy;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertFalse;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertSame;
31 import static org.junit.Assert.assertTrue;
32 import static org.mockito.Mockito.spy;
33 import static org.mockito.Mockito.when;
34
35 import java.util.Collections;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.UUID;
39 import java.util.concurrent.CancellationException;
40 import java.util.concurrent.CompletableFuture;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.Future;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.TimeoutException;
45 import java.util.concurrent.atomic.AtomicReference;
46 import javax.ws.rs.Consumes;
47 import javax.ws.rs.DELETE;
48 import javax.ws.rs.GET;
49 import javax.ws.rs.POST;
50 import javax.ws.rs.PUT;
51 import javax.ws.rs.Path;
52 import javax.ws.rs.Produces;
53 import javax.ws.rs.client.Entity;
54 import javax.ws.rs.client.InvocationCallback;
55 import javax.ws.rs.core.MediaType;
56 import javax.ws.rs.core.Response;
57 import javax.ws.rs.core.Response.Status;
58 import lombok.Getter;
59 import lombok.Setter;
60 import org.junit.AfterClass;
61 import org.junit.Before;
62 import org.junit.BeforeClass;
63 import org.junit.Test;
64 import org.mockito.Mock;
65 import org.mockito.MockitoAnnotations;
66 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
67 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
68 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
69 import org.onap.policy.common.endpoints.http.client.HttpClient;
70 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
71 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
72 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
73 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
74 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
75 import org.onap.policy.common.gson.GsonMessageBodyHandler;
76 import org.onap.policy.common.utils.coder.CoderException;
77 import org.onap.policy.common.utils.network.NetworkUtil;
78 import org.onap.policy.controlloop.VirtualControlLoopEvent;
79 import org.onap.policy.controlloop.actorserviceprovider.Operation;
80 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
81 import org.onap.policy.controlloop.actorserviceprovider.Util;
82 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
83 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
84 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
85 import org.onap.policy.controlloop.policy.PolicyResult;
86
87 public class HttpOperationTest {
88
89     private static final IllegalStateException EXPECTED_EXCEPTION = new IllegalStateException("expected exception");
90     private static final String ACTOR = "my-actor";
91     private static final String OPERATION = "my-name";
92     private static final String HTTP_CLIENT = "my-client";
93     private static final String HTTP_NO_SERVER = "my-http-no-server-client";
94     private static final String MEDIA_TYPE_APPLICATION_JSON = "application/json";
95     private static final String BASE_URI = "oper";
96     private static final String PATH = "/my-path";
97     private static final String TEXT = "my-text";
98     private static final UUID REQ_ID = UUID.randomUUID();
99
100     /**
101      * {@code True} if the server should reject the request, {@code false} otherwise.
102      */
103     private static boolean rejectRequest;
104
105     // call counts of each method type in the server
106     private static int nget;
107     private static int npost;
108     private static int nput;
109     private static int ndelete;
110
111     @Mock
112     private HttpClient client;
113
114     @Mock
115     private Response response;
116
117     private VirtualControlLoopEvent event;
118     private ControlLoopEventContext context;
119     private ControlLoopOperationParams params;
120     private OperationOutcome outcome;
121     private AtomicReference<InvocationCallback<Response>> callback;
122     private Future<Response> future;
123     private HttpOperator operator;
124     private MyGetOperation<String> oper;
125
126     /**
127      * Starts the simulator.
128      */
129     @BeforeClass
130     public static void setUpBeforeClass() throws Exception {
131         // allocate a port
132         int port = NetworkUtil.allocPort();
133
134         /*
135          * Start the simulator. Must use "Properties" to configure it, otherwise the
136          * server will use the wrong serialization provider.
137          */
138         Properties svrprops = getServerProperties("my-server", port);
139         HttpServletServerFactoryInstance.getServerFactory().build(svrprops).forEach(HttpServletServer::start);
140
141         if (!NetworkUtil.isTcpPortOpen("localhost", port, 100, 100)) {
142             HttpServletServerFactoryInstance.getServerFactory().destroy();
143             throw new IllegalStateException("server is not running");
144         }
145
146         /*
147          * Start the clients, one to the server, and one to a non-existent server.
148          */
149         TopicParamsBuilder builder = BusTopicParams.builder().managed(true).hostname("localhost").basePath(BASE_URI)
150                         .serializationProvider(GsonMessageBodyHandler.class.getName());
151
152         HttpClientFactoryInstance.getClientFactory().build(builder.clientName(HTTP_CLIENT).port(port).build());
153
154         HttpClientFactoryInstance.getClientFactory()
155                         .build(builder.clientName(HTTP_NO_SERVER).port(NetworkUtil.allocPort()).build());
156     }
157
158     /**
159      * Destroys the Http factories and stops the appender.
160      */
161     @AfterClass
162     public static void tearDownAfterClass() {
163         HttpClientFactoryInstance.getClientFactory().destroy();
164         HttpServletServerFactoryInstance.getServerFactory().destroy();
165     }
166
167     /**
168      * Initializes fields, including {@link #oper}, and resets the static fields used by
169      * the REST server.
170      */
171     @Before
172     public void setUp() {
173         MockitoAnnotations.initMocks(this);
174
175         rejectRequest = false;
176         nget = 0;
177         npost = 0;
178         nput = 0;
179         ndelete = 0;
180
181         when(response.readEntity(String.class)).thenReturn(TEXT);
182         when(response.getStatus()).thenReturn(200);
183
184         event = new VirtualControlLoopEvent();
185         event.setRequestId(REQ_ID);
186
187         context = new ControlLoopEventContext(event);
188         params = ControlLoopOperationParams.builder().actor(ACTOR).operation(OPERATION).context(context).build();
189
190         outcome = params.makeOutcome();
191
192         callback = new AtomicReference<>();
193         future = new CompletableFuture<>();
194
195         operator = new HttpOperator(ACTOR, OPERATION) {
196             @Override
197             public Operation buildOperation(ControlLoopOperationParams params) {
198                 return null;
199             }
200
201             @Override
202             public HttpClient getClient() {
203                 return client;
204             }
205         };
206
207         initOper(operator, HTTP_CLIENT);
208
209         oper = new MyGetOperation<>(String.class);
210     }
211
212     @Test
213     public void testHttpOperator() {
214         assertEquals(ACTOR, oper.getActorName());
215         assertEquals(OPERATION, oper.getName());
216         assertEquals(ACTOR + "." + OPERATION, oper.getFullName());
217     }
218
219     @Test
220     public void testMakeHeaders() {
221         assertEquals(Collections.emptyMap(), oper.makeHeaders());
222     }
223
224     @Test
225     public void testMakePath() {
226         assertEquals(PATH, oper.makePath());
227     }
228
229     @Test
230     public void testMakeUrl() {
231         // use a real client
232         client = HttpClientFactoryInstance.getClientFactory().get(HTTP_CLIENT);
233
234         assertThat(oper.makeUrl()).endsWith("/" + BASE_URI + PATH);
235     }
236
237     @Test
238     public void testDoConfigureMapOfStringObject_testGetClient_testGetPath_testGetTimeoutMs() {
239
240         // use value from operator
241         assertEquals(1000L, oper.getTimeoutMs(null));
242         assertEquals(1000L, oper.getTimeoutMs(0));
243
244         // should use given value
245         assertEquals(20 * 1000L, oper.getTimeoutMs(20));
246
247         // indicate we have a timeout value
248         operator = spy(operator);
249         when(operator.getTimeoutMs()).thenReturn(30L);
250
251         oper = new MyGetOperation<String>(String.class);
252
253         // should use default
254         assertEquals(30L, oper.getTimeoutMs(null));
255         assertEquals(30L, oper.getTimeoutMs(0));
256
257         // should use given value
258         assertEquals(40 * 1000L, oper.getTimeoutMs(40));
259     }
260
261     /**
262      * Tests handleResponse() when it completes.
263      */
264     @Test
265     public void testHandleResponseComplete() throws Exception {
266         CompletableFuture<OperationOutcome> future2 = oper.handleResponse(outcome, PATH, cb -> {
267             callback.set(cb);
268             return future;
269         });
270
271         assertFalse(future2.isDone());
272         assertNotNull(callback.get());
273         callback.get().completed(response);
274
275         assertSame(outcome, future2.get(5, TimeUnit.SECONDS));
276
277         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
278     }
279
280     /**
281      * Tests handleResponse() when it fails.
282      */
283     @Test
284     public void testHandleResponseFailed() throws Exception {
285         CompletableFuture<OperationOutcome> future2 = oper.handleResponse(outcome, PATH, cb -> {
286             callback.set(cb);
287             return future;
288         });
289
290         assertFalse(future2.isDone());
291         assertNotNull(callback.get());
292         callback.get().failed(EXPECTED_EXCEPTION);
293
294         assertThatThrownBy(() -> future2.get(5, TimeUnit.SECONDS)).hasCause(EXPECTED_EXCEPTION);
295
296         // future and future2 may be completed in parallel so we must wait again
297         assertThatThrownBy(() -> future.get(5, TimeUnit.SECONDS)).isInstanceOf(CancellationException.class);
298         assertTrue(future.isCancelled());
299     }
300
301     /**
302      * Tests processResponse() when it's a success and the response type is a String.
303      */
304     @Test
305     public void testProcessResponseSuccessString() {
306         assertSame(outcome, oper.processResponse(outcome, PATH, response));
307         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
308     }
309
310     /**
311      * Tests processResponse() when it's a failure.
312      */
313     @Test
314     public void testProcessResponseFailure() {
315         when(response.getStatus()).thenReturn(555);
316         assertSame(outcome, oper.processResponse(outcome, PATH, response));
317         assertEquals(PolicyResult.FAILURE, outcome.getResult());
318     }
319
320     /**
321      * Tests processResponse() when the decoder succeeds.
322      */
323     @Test
324     public void testProcessResponseDecodeOk() throws CoderException {
325         when(response.readEntity(String.class)).thenReturn("10");
326
327         MyGetOperation<Integer> oper2 = new MyGetOperation<>(Integer.class);
328
329         assertSame(outcome, oper2.processResponse(outcome, PATH, response));
330         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
331     }
332
333     /**
334      * Tests processResponse() when the decoder throws an exception.
335      */
336     @Test
337     public void testProcessResponseDecodeExcept() throws CoderException {
338         MyGetOperation<Integer> oper2 = new MyGetOperation<>(Integer.class);
339
340         assertThatIllegalArgumentException().isThrownBy(() -> oper2.processResponse(outcome, PATH, response));
341     }
342
343     @Test
344     public void testPostProcessResponse() {
345         assertThatCode(() -> oper.postProcessResponse(outcome, PATH, null, null)).doesNotThrowAnyException();
346     }
347
348     @Test
349     public void testIsSuccess() {
350         when(response.getStatus()).thenReturn(200);
351         assertTrue(oper.isSuccess(response, null));
352
353         when(response.getStatus()).thenReturn(555);
354         assertFalse(oper.isSuccess(response, null));
355     }
356
357     /**
358      * Tests a GET.
359      */
360     @Test
361     public void testGet() throws Exception {
362         // use a real client
363         client = HttpClientFactoryInstance.getClientFactory().get(HTTP_CLIENT);
364
365         MyGetOperation<MyResponse> oper2 = new MyGetOperation<>(MyResponse.class);
366
367         OperationOutcome outcome = runOperation(oper2);
368         assertNotNull(outcome);
369         assertEquals(1, nget);
370         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
371     }
372
373     /**
374      * Tests a DELETE.
375      */
376     @Test
377     public void testDelete() throws Exception {
378         // use a real client
379         client = HttpClientFactoryInstance.getClientFactory().get(HTTP_CLIENT);
380
381         MyDeleteOperation oper2 = new MyDeleteOperation();
382
383         OperationOutcome outcome = runOperation(oper2);
384         assertNotNull(outcome);
385         assertEquals(1, ndelete);
386         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
387     }
388
389     /**
390      * Tests a POST.
391      */
392     @Test
393     public void testPost() throws Exception {
394         // use a real client
395         client = HttpClientFactoryInstance.getClientFactory().get(HTTP_CLIENT);
396
397         MyPostOperation oper2 = new MyPostOperation();
398
399         OperationOutcome outcome = runOperation(oper2);
400         assertNotNull(outcome);
401         assertEquals(1, npost);
402         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
403     }
404
405     /**
406      * Tests a PUT.
407      */
408     @Test
409     public void testPut() throws Exception {
410         // use a real client
411         client = HttpClientFactoryInstance.getClientFactory().get(HTTP_CLIENT);
412
413         MyPutOperation oper2 = new MyPutOperation();
414
415         OperationOutcome outcome = runOperation(oper2);
416         assertNotNull(outcome);
417         assertEquals(1, nput);
418         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
419     }
420
421     @Test
422     public void testMakeDecoder() {
423         assertNotNull(oper.makeCoder());
424     }
425
426     /**
427      * Gets server properties.
428      *
429      * @param name server name
430      * @param port server port
431      * @return server properties
432      */
433     private static Properties getServerProperties(String name, int port) {
434         final Properties props = new Properties();
435         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, name);
436
437         final String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + name;
438
439         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, Server.class.getName());
440         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
441         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, String.valueOf(port));
442         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
443         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "false");
444
445         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
446                         GsonMessageBodyHandler.class.getName());
447         return props;
448     }
449
450     /**
451      * Initializes the given operator.
452      *
453      * @param operator operator to be initialized
454      * @param clientName name of the client which it should use
455      */
456     private void initOper(HttpOperator operator, String clientName) {
457         operator.stop();
458
459         HttpParams params = HttpParams.builder().clientName(clientName).path(PATH).timeoutSec(1).build();
460         Map<String, Object> mapParams = Util.translateToMap(OPERATION, params);
461         operator.configure(mapParams);
462         operator.start();
463     }
464
465     /**
466      * Runs the operation.
467      *
468      * @param operator operator on which to start the operation
469      * @return the outcome of the operation, or {@code null} if it does not complete in
470      *         time
471      */
472     private <T> OperationOutcome runOperation(HttpOperation<T> operator)
473                     throws InterruptedException, ExecutionException, TimeoutException {
474
475         CompletableFuture<OperationOutcome> future = operator.start();
476
477         return future.get(5, TimeUnit.SECONDS);
478     }
479
480     @Getter
481     @Setter
482     public static class MyRequest {
483         private String input = "some input";
484     }
485
486     @Getter
487     @Setter
488     public static class MyResponse {
489         private String output = "some output";
490     }
491
492     private class MyGetOperation<T> extends HttpOperation<T> {
493         public MyGetOperation(Class<T> responseClass) {
494             super(HttpOperationTest.this.params, HttpOperationTest.this.operator, responseClass);
495         }
496
497         @Override
498         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
499             Map<String, Object> headers = makeHeaders();
500
501             headers.put("Accept", MediaType.APPLICATION_JSON);
502             String url = makeUrl();
503
504             logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
505
506             // @formatter:off
507             return handleResponse(outcome, url,
508                 callback -> operator.getClient().get(callback, makePath(), headers));
509             // @formatter:on
510         }
511     }
512
513     private class MyPostOperation extends HttpOperation<MyResponse> {
514         public MyPostOperation() {
515             super(HttpOperationTest.this.params, HttpOperationTest.this.operator, MyResponse.class);
516         }
517
518         @Override
519         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
520
521             MyRequest request = new MyRequest();
522
523             Entity<MyRequest> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
524
525             Map<String, Object> headers = makeHeaders();
526
527             headers.put("Accept", MediaType.APPLICATION_JSON);
528             String url = makeUrl();
529
530             logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
531
532             // @formatter:off
533             return handleResponse(outcome, url,
534                 callback -> operator.getClient().post(callback, makePath(), entity, headers));
535             // @formatter:on
536         }
537     }
538
539     private class MyPutOperation extends HttpOperation<MyResponse> {
540         public MyPutOperation() {
541             super(HttpOperationTest.this.params, HttpOperationTest.this.operator, MyResponse.class);
542         }
543
544         @Override
545         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
546
547             MyRequest request = new MyRequest();
548
549             Entity<MyRequest> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
550
551             Map<String, Object> headers = makeHeaders();
552
553             headers.put("Accept", MediaType.APPLICATION_JSON);
554             String url = makeUrl();
555
556             logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
557
558             // @formatter:off
559             return handleResponse(outcome, url,
560                 callback -> operator.getClient().put(callback, makePath(), entity, headers));
561             // @formatter:on
562         }
563     }
564
565     private class MyDeleteOperation extends HttpOperation<String> {
566         public MyDeleteOperation() {
567             super(HttpOperationTest.this.params, HttpOperationTest.this.operator, String.class);
568         }
569
570         @Override
571         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
572             Map<String, Object> headers = makeHeaders();
573
574             headers.put("Accept", MediaType.APPLICATION_JSON);
575             String url = makeUrl();
576
577             logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
578
579             // @formatter:off
580             return handleResponse(outcome, url,
581                 callback -> operator.getClient().delete(callback, makePath(), headers));
582             // @formatter:on
583         }
584     }
585
586     /**
587      * Simulator.
588      */
589     @Path("/" + BASE_URI)
590     @Produces(MEDIA_TYPE_APPLICATION_JSON)
591     @Consumes(value = {MEDIA_TYPE_APPLICATION_JSON})
592     public static class Server {
593
594         /**
595          * Generates a response to a GET.
596          *
597          * @return resulting response
598          */
599         @GET
600         @Path(PATH)
601         public Response getRequest() {
602             ++nget;
603
604             if (rejectRequest) {
605                 return Response.status(Status.BAD_REQUEST).build();
606
607             } else {
608                 return Response.status(Status.OK).entity(new MyResponse()).build();
609             }
610         }
611
612         /**
613          * Generates a response to a POST.
614          *
615          * @param request incoming request
616          * @return resulting response
617          */
618         @POST
619         @Path(PATH)
620         public Response postRequest(MyRequest request) {
621             ++npost;
622
623             if (rejectRequest) {
624                 return Response.status(Status.BAD_REQUEST).build();
625
626             } else {
627                 return Response.status(Status.OK).entity(new MyResponse()).build();
628             }
629         }
630
631         /**
632          * Generates a response to a PUT.
633          *
634          * @param request incoming request
635          * @return resulting response
636          */
637         @PUT
638         @Path(PATH)
639         public Response putRequest(MyRequest request) {
640             ++nput;
641
642             if (rejectRequest) {
643                 return Response.status(Status.BAD_REQUEST).build();
644
645             } else {
646                 return Response.status(Status.OK).entity(new MyResponse()).build();
647             }
648         }
649
650         /**
651          * Generates a response to a DELETE.
652          *
653          * @return resulting response
654          */
655         @DELETE
656         @Path(PATH)
657         public Response deleteRequest() {
658             ++ndelete;
659
660             if (rejectRequest) {
661                 return Response.status(Status.BAD_REQUEST).build();
662
663             } else {
664                 return Response.status(Status.OK).entity(new MyResponse()).build();
665             }
666         }
667     }
668 }