2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4 * Modifications Copyright (C) 2020,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.pdpx.main.rest;
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertTrue;
29 import jakarta.ws.rs.client.Entity;
30 import jakarta.ws.rs.core.MediaType;
31 import jakarta.ws.rs.core.Response;
33 import java.io.IOException;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.nio.file.StandardCopyOption;
38 import java.security.KeyManagementException;
39 import java.security.NoSuchAlgorithmException;
40 import java.util.Collections;
41 import java.util.HashMap;
43 import java.util.Properties;
44 import java.util.ServiceLoader;
45 import org.junit.AfterClass;
46 import org.junit.BeforeClass;
47 import org.junit.ClassRule;
48 import org.junit.Test;
49 import org.junit.rules.TemporaryFolder;
50 import org.onap.policy.common.endpoints.http.client.HttpClient;
51 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
52 import org.onap.policy.common.endpoints.http.client.internal.JerseyClient;
53 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
54 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
55 import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
56 import org.onap.policy.common.utils.coder.CoderException;
57 import org.onap.policy.common.utils.coder.StandardCoder;
58 import org.onap.policy.common.utils.network.NetworkUtil;
59 import org.onap.policy.models.decisions.concepts.DecisionRequest;
60 import org.onap.policy.models.decisions.concepts.DecisionResponse;
61 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
62 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
63 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
64 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
65 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
66 import org.onap.policy.pdpx.main.parameters.CommonTestData;
67 import org.onap.policy.pdpx.main.parameters.XacmlApplicationParameters;
68 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
69 import org.onap.policy.pdpx.main.startstop.Main;
70 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
71 import org.onap.policy.xacml.pdp.application.monitoring.MonitoringPdpApplication;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 public class TestAbbreviateDecisionResults {
77 private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
79 private static int port;
80 private static Main main;
81 private static HttpClient client;
82 private static CommonTestData testData = new CommonTestData();
84 private static Properties properties = new Properties();
85 private static File propertiesFile;
86 private static XacmlApplicationServiceProvider service;
88 private static RestClientParameters policyApiParameters;
91 public static final TemporaryFolder appsFolder = new TemporaryFolder();
94 * BeforeClass setup environment.
96 * @throws IOException Cannot create temp apps folder
97 * @throws Exception exception if service does not start
100 public static void beforeClass() throws Exception {
101 port = NetworkUtil.allocPort();
103 // Copy test directory over of the application directories
105 Path src = Paths.get("src/test/resources/apps");
106 File apps = appsFolder.newFolder("apps");
107 Files.walk(src).forEach(source -> {
108 copy(source, apps.toPath().resolve(src.relativize(source)));
111 // Start the Monitoring Application
112 startXacmlApplicationService(apps);
114 // Load monitoring policy
115 TestUtils.loadPolicies("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml", service);
117 // Create parameters for XacmlPdPService
118 RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port),
119 RestServerParameters.class);
120 policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
121 TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false),
122 TopicParameterGroup.class);
123 final XacmlApplicationParameters xacmlApplicationParameters =
124 testData.toObject(testData.getXacmlapplicationParametersMap(false,
125 apps.getAbsolutePath().toString()), XacmlApplicationParameters.class);
126 XacmlPdpParameterGroup params =
127 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
128 topicParameterGroup, xacmlApplicationParameters);
129 StandardCoder gson = new StandardCoder();
130 File fileParams = appsFolder.newFile("params.json");
131 String jsonParams = gson.encode(params);
132 LOGGER.info("Creating new params: {}", jsonParams);
133 Files.write(fileParams.toPath(), jsonParams.getBytes());
137 main = startXacmlPdpService(fileParams);
138 XacmlPdpActivator.getCurrent().enableApi();
140 // Make sure it is running
142 if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
143 throw new IllegalStateException("Cannot connect to port " + port);
148 client = getNoAuthHttpClient();
155 public static void after() throws PolicyXacmlPdpException {
156 stopXacmlPdpService(main);
161 * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
162 * should have been removed from the response.
165 public void testAbbreviateDecisionResult() throws HttpClientConfigException {
167 LOGGER.info("Running testAbbreviateDecisionResult");
169 // Create DecisionRequest
170 DecisionRequest request = new DecisionRequest();
171 request.setOnapName("DCAE");
172 request.setOnapComponent("PolicyHandler");
173 request.setOnapInstance("622431a4-9dea-4eae-b443-3b2164639c64");
174 request.setAction("configure");
175 Map<String, Object> resource = new HashMap<String, Object>();
176 resource.put("policy-id", "onap.scaleout.tca");
177 request.setResource(resource);
179 // Query decision API
180 DecisionResponse response = getDecision(request);
181 LOGGER.info("Decision Response {}", response);
183 assertFalse(response.getPolicies().isEmpty());
185 @SuppressWarnings("unchecked")
186 Map<String, Object> policy = (Map<String, Object>) response.getPolicies().get("onap.scaleout.tca");
187 assertTrue(policy.containsKey("type"));
188 assertFalse(policy.containsKey("properties"));
189 assertFalse(policy.containsKey("name"));
190 assertFalse(policy.containsKey("version"));
191 assertTrue(policy.containsKey("metadata"));
194 private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
195 final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
196 return new Main(XacmlPdpConfigParameters);
199 private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
204 * Performs the POST request to Decision API.
207 private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
209 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
210 Response response = client.post("", entityRequest, Collections.emptyMap());
212 assertEquals(200, response.getStatus());
213 return HttpClient.getBody(response, DecisionResponse.class);
220 private static HttpClient getNoAuthHttpClient()
221 throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
222 RestClientParameters clientParams = new RestClientParameters();
223 clientParams.setClientName("testName");
224 clientParams.setUseHttps(false);
225 clientParams.setAllowSelfSignedCerts(false);
226 clientParams.setHostname("localhost");
227 clientParams.setPort(port);
228 clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
229 clientParams.setUserName("healthcheck");
230 clientParams.setPassword("zb!XztG34");
231 clientParams.setManaged(true);
232 client = new JerseyClient(clientParams);
236 private static void copy(Path source, Path dest) {
238 LOGGER.info("Copying {} to {}", source, dest);
239 Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
240 } catch (IOException e) {
241 LOGGER.error("Failed to copy {} to {}", source, dest);
246 * Initializes the Monitoring application service.
248 * @param apps - the path to xacml.properties file
250 private static void startXacmlApplicationService(File apps)
251 throws XacmlApplicationException, CoderException, IOException {
252 LOGGER.info("****** Starting Xacml Application Service ******");
254 // Setup our temporary folder
256 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
257 new File(apps, "monitoring/" + filename).delete();
258 return appsFolder.newFile("apps/monitoring/" + filename);
260 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
261 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
263 // Load XacmlApplicationServiceProvider service
265 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
266 .load(XacmlApplicationServiceProvider.class);
268 // Look for our class instance and save it
270 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
271 for (XacmlApplicationServiceProvider application : applicationLoader) {
273 // Is it our service?
275 if (application instanceof MonitoringPdpApplication) {
277 // Should be the first and only one
279 assertThat(service).isNull();
280 service = application;
282 strDump.append(application.applicationName());
283 strDump.append(" supports ");
284 strDump.append(application.supportedPolicyTypes());
285 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
287 LOGGER.debug("{}", strDump);
289 // Tell it to initialize based on the properties file
290 // we just built for it.
292 service.initialize(propertiesFile.toPath().getParent(), null);