Upgrade Java 17 in xacml-pdp
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / PolicyApiCallerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2021,2023 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdp.xacml.application.common;
23
24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.when;
30
31 import jakarta.ws.rs.Consumes;
32 import jakarta.ws.rs.GET;
33 import jakarta.ws.rs.HeaderParam;
34 import jakarta.ws.rs.Path;
35 import jakarta.ws.rs.PathParam;
36 import jakarta.ws.rs.Produces;
37 import jakarta.ws.rs.core.Response;
38 import java.io.IOException;
39 import java.util.Properties;
40 import java.util.UUID;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.onap.policy.common.endpoints.http.client.HttpClient;
46 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
50 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
51 import org.onap.policy.common.gson.GsonMessageBodyHandler;
52 import org.onap.policy.common.utils.network.NetworkUtil;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 public class PolicyApiCallerTest {
59     private static final String MY_TYPE = "my-type";
60
61     private static final String MY_VERSION = "1.0.0";
62
63     private static final Logger logger = LoggerFactory.getLogger(PolicyApiCallerTest.class);
64
65     private static final String CLIENT_NAME = "policy-api";
66     private static final String NOT_A_TYPE = "other-type";
67     private static final String INVALID_TYPE = "invalid";
68     private static final String UNKNOWN_TYPE = "unknown";
69
70     private static int port;
71     private static RestClientParameters clientParams;
72
73     private static HttpClient apiClient;
74
75     private PolicyApiCaller api;
76
77     /**
78      * Initializes {@link #clientParams} and starts a simple REST server to handle the
79      * test requests.
80      *
81      * @throws IOException if an error occurs
82      */
83     @BeforeClass
84     public static void setUpBeforeClass() throws Exception {
85         port = NetworkUtil.allocPort();
86
87         clientParams = mock(RestClientParameters.class);
88         when(clientParams.getClientName()).thenReturn("apiClient");
89         when(clientParams.getHostname()).thenReturn("localhost");
90         when(clientParams.getPort()).thenReturn(port);
91
92         Properties props = new Properties();
93         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
94
95         final String svcpfx =
96                         PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
97
98         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
99         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
100                         Integer.toString(clientParams.getPort()));
101         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
102                         ApiRestController.class.getName());
103         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
104         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
105         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
106         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
107                         GsonMessageBodyHandler.class.getName());
108
109         HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
110         apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
111
112         assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
113     }
114
115     @AfterClass
116     public static void tearDownAfterClass() {
117         HttpServletServerFactoryInstance.getServerFactory().destroy();
118     }
119
120     /**
121      * Resets {@link #clientParams} and populates {@link #api}.
122      *
123      * @throws PolicyApiException if an error occurs
124      */
125     @Before
126     public void setUp() throws PolicyApiException {
127         when(clientParams.getPort()).thenReturn(port);
128
129         api = new PolicyApiCaller(apiClient);
130     }
131
132     @Test
133     public void testGetPolicyType() throws Exception {
134
135         assertNotNull(api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)));
136
137         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(INVALID_TYPE, MY_VERSION)))
138                         .isInstanceOf(PolicyApiException.class);
139
140         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(UNKNOWN_TYPE, MY_VERSION)))
141                         .isInstanceOf(NotFoundException.class);
142
143         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(NOT_A_TYPE, MY_VERSION)))
144                         .isInstanceOf(PolicyApiException.class);
145
146         // connect to a port that has no server
147         RestClientParameters params2 = mock(RestClientParameters.class);
148         when(params2.getClientName()).thenReturn("apiClient");
149         when(params2.getHostname()).thenReturn("localhost");
150         when(params2.getPort()).thenReturn(NetworkUtil.allocPort());
151
152         HttpClient apiClient2 = HttpClientFactoryInstance.getClientFactory().build(params2);
153         api = new PolicyApiCaller(apiClient2);
154
155         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)))
156                         .isInstanceOf(PolicyApiException.class);
157     }
158
159     /**
160      * Simple REST server to handle test requests.
161      */
162
163     @Path("/policy/api/v1")
164     @Produces({"application/json", "application/yaml"})
165     @Consumes({"application/json", "application/yaml"})
166     public static class ApiRestController {
167
168         /**
169          * Retrieves the specified version of a particular policy type.
170          *
171          * @param policyTypeId ID of desired policy type
172          * @param versionId version of desired policy type
173          * @param requestId optional request ID
174          *
175          * @return the Response object containing the results of the API operation
176          */
177         @GET
178         @Path("/policytypes/{policyTypeId}/versions/{versionId}")
179         public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
180                         @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
181
182             assertEquals(MY_VERSION, versionId);
183
184             switch (policyTypeId) {
185                 case UNKNOWN_TYPE:
186                     logger.info("request for unknown policy type");
187                     return Response.status(Response.Status.NOT_FOUND).build();
188                 case INVALID_TYPE:
189                     logger.info("invalid request for policy type");
190                     return Response.status(Response.Status.BAD_REQUEST).build();
191                 case NOT_A_TYPE:
192                     logger.info("invalid request for policy type");
193                     return Response.status(Response.Status.OK).entity("string-type").build();
194                 default:
195                     logger.info("request for policy type={} version={}", policyTypeId, versionId);
196                     return Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();
197             }
198         }
199     }
200 }