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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pdp.xacml.application.common;
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;
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;
58 public class PolicyApiCallerTest {
59 private static final String MY_TYPE = "my-type";
61 private static final String MY_VERSION = "1.0.0";
63 private static final Logger logger = LoggerFactory.getLogger(PolicyApiCallerTest.class);
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";
70 private static int port;
71 private static RestClientParameters clientParams;
73 private static HttpClient apiClient;
75 private PolicyApiCaller api;
78 * Initializes {@link #clientParams} and starts a simple REST server to handle the
81 * @throws IOException if an error occurs
84 public static void setUpBeforeClass() throws Exception {
85 port = NetworkUtil.allocPort();
87 clientParams = mock(RestClientParameters.class);
88 when(clientParams.getClientName()).thenReturn("apiClient");
89 when(clientParams.getHostname()).thenReturn("localhost");
90 when(clientParams.getPort()).thenReturn(port);
92 Properties props = new Properties();
93 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
96 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
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());
109 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
110 apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
112 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
116 public static void tearDownAfterClass() {
117 HttpServletServerFactoryInstance.getServerFactory().destroy();
121 * Resets {@link #clientParams} and populates {@link #api}.
123 * @throws PolicyApiException if an error occurs
126 public void setUp() throws PolicyApiException {
127 when(clientParams.getPort()).thenReturn(port);
129 api = new PolicyApiCaller(apiClient);
133 public void testGetPolicyType() throws Exception {
135 assertNotNull(api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)));
137 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(INVALID_TYPE, MY_VERSION)))
138 .isInstanceOf(PolicyApiException.class);
140 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(UNKNOWN_TYPE, MY_VERSION)))
141 .isInstanceOf(NotFoundException.class);
143 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(NOT_A_TYPE, MY_VERSION)))
144 .isInstanceOf(PolicyApiException.class);
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());
152 HttpClient apiClient2 = HttpClientFactoryInstance.getClientFactory().build(params2);
153 api = new PolicyApiCaller(apiClient2);
155 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)))
156 .isInstanceOf(PolicyApiException.class);
160 * Simple REST server to handle test requests.
163 @Path("/policy/api/v1")
164 @Produces({"application/json", "application/yaml"})
165 @Consumes({"application/json", "application/yaml"})
166 public static class ApiRestController {
169 * Retrieves the specified version of a particular policy type.
171 * @param policyTypeId ID of desired policy type
172 * @param versionId version of desired policy type
173 * @param requestId optional request ID
175 * @return the Response object containing the results of the API operation
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) {
182 assertEquals(MY_VERSION, versionId);
184 switch (policyTypeId) {
186 logger.info("request for unknown policy type");
187 return Response.status(Response.Status.NOT_FOUND).build();
189 logger.info("invalid request for policy type");
190 return Response.status(Response.Status.BAD_REQUEST).build();
192 logger.info("invalid request for policy type");
193 return Response.status(Response.Status.OK).entity("string-type").build();
195 logger.info("request for policy type={} version={}", policyTypeId, versionId);
196 return Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();