2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdpx.main.rest;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
30 import java.io.IOException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.nio.file.StandardCopyOption;
35 import java.security.KeyManagementException;
36 import java.security.NoSuchAlgorithmException;
37 import java.util.Collections;
38 import java.util.HashMap;
40 import java.util.Properties;
41 import java.util.ServiceLoader;
42 import javax.ws.rs.client.Entity;
43 import javax.ws.rs.core.MediaType;
44 import javax.ws.rs.core.Response;
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.event.comm.bus.internal.BusTopicParams;
51 import org.onap.policy.common.endpoints.http.client.HttpClient;
52 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
53 import org.onap.policy.common.endpoints.http.client.internal.JerseyClient;
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.XacmlPdpParameterGroup;
68 import org.onap.policy.pdpx.main.startstop.Main;
69 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
70 import org.onap.policy.xacml.pdp.application.monitoring.MonitoringPdpApplication;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
74 public class TestAbbreviateDecisionResults {
76 private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
78 private static int port;
79 private static Main main;
80 private static HttpClient client;
81 private static CommonTestData testData = new CommonTestData();
83 private static Properties properties = new Properties();
84 private static File propertiesFile;
85 private static XacmlApplicationServiceProvider service;
87 private static RestServerParameters policyApiParameters;
90 public static final TemporaryFolder appsFolder = new TemporaryFolder();
93 * BeforeClass setup environment.
95 * @throws IOException Cannot create temp apps folder
96 * @throws Exception exception if service does not start
99 public static void beforeClass() throws Exception {
100 port = NetworkUtil.allocPort();
102 // Copy test directory over of the application directories
104 Path src = Paths.get("src/test/resources/apps");
105 File apps = appsFolder.newFolder("apps");
106 Files.walk(src).forEach(source -> {
107 copy(source, apps.toPath().resolve(src.relativize(source)));
110 // Start the Monitoring Application
111 startXacmlApplicationService(apps);
113 // Load monitoring policy
114 TestUtils.loadPolicies("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml", service);
116 // Create parameters for XacmlPdPService
117 RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port),
118 RestServerParameters.class);
119 policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), RestServerParameters.class);
120 TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false),
121 TopicParameterGroup.class);
122 XacmlPdpParameterGroup params =
123 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", rest, policyApiParameters,
124 topicParameterGroup, apps.getAbsolutePath());
125 StandardCoder gson = new StandardCoder();
126 File fileParams = appsFolder.newFile("params.json");
127 String jsonParams = gson.encode(params);
128 LOGGER.info("Creating new params: {}", jsonParams);
129 Files.write(fileParams.toPath(), jsonParams.getBytes());
133 main = startXacmlPdpService(fileParams);
134 XacmlPdpActivator.getCurrent().startXacmlRestController();
136 // Make sure it is running
138 if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
139 throw new IllegalStateException("Cannot connect to port " + port);
144 client = getNoAuthHttpClient();
151 public static void after() throws PolicyXacmlPdpException {
152 stopXacmlPdpService(main);
157 * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
158 * should have been removed from the response.
161 public void testAbbreviateDecisionResult() {
163 LOGGER.info("Running testAbbreviateDecisionResult");
166 // Create DecisionRequest
167 DecisionRequest request = new DecisionRequest();
168 request.setOnapName("DCAE");
169 request.setOnapComponent("PolicyHandler");
170 request.setOnapInstance("622431a4-9dea-4eae-b443-3b2164639c64");
171 request.setAction("configure");
172 Map<String, Object> resource = new HashMap<String, Object>();
173 resource.put("policy-id", "onap.scaleout.tca");
174 request.setResource(resource);
176 // Query decision API
177 DecisionResponse response = getDecision(request);
178 LOGGER.info("Decision Response {}", response);
180 assertFalse(response.getPolicies().isEmpty());
182 @SuppressWarnings("unchecked")
183 Map<String, Object> policy = (Map<String, Object>) response.getPolicies().get("onap.scaleout.tca");
184 assertTrue(policy.containsKey("type"));
185 assertFalse(policy.containsKey("properties"));
186 assertFalse(policy.containsKey("name"));
187 assertFalse(policy.containsKey("version"));
188 assertTrue(policy.containsKey("metadata"));
190 } catch (Exception e) {
191 LOGGER.error("Exception {}", e);
192 fail("testAbbreviateDecisionResult failed due to: " + e.getLocalizedMessage());
196 private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
197 final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
198 return new Main(XacmlPdpConfigParameters);
201 private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
206 * Performs the POST request to Decision API.
209 private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
211 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
212 Response response = client.post("", entityRequest, Collections.emptyMap());
214 assertEquals(200, response.getStatus());
215 return HttpClient.getBody(response, DecisionResponse.class);
222 private static HttpClient getNoAuthHttpClient()
223 throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
224 BusTopicParams clientParams = new BusTopicParams();
225 clientParams.setClientName("testName");
226 clientParams.setUseHttps(false);
227 clientParams.setAllowSelfSignedCerts(false);
228 clientParams.setHostname("localhost");
229 clientParams.setPort(port);
230 clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
231 clientParams.setUserName("healthcheck");
232 clientParams.setPassword("zb!XztG34");
233 clientParams.setManaged(true);
234 client = new JerseyClient(clientParams);
238 private static void copy(Path source, Path dest) {
240 LOGGER.info("Copying {} to {}", source, dest);
241 Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
242 } catch (IOException e) {
243 LOGGER.error("Failed to copy {} to {}", source, dest);
248 * Initializes the Monitoring application service.
250 * @param apps - the path to xacml.properties file
252 private static void startXacmlApplicationService(File apps)
253 throws XacmlApplicationException, CoderException, IOException {
254 LOGGER.info("****** Starting Xacml Application Service ******");
256 // Setup our temporary folder
258 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
259 new File(apps, "monitoring/" + filename).delete();
260 return appsFolder.newFile("apps/monitoring/" + filename);
262 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
263 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
265 // Load XacmlApplicationServiceProvider service
267 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
268 .load(XacmlApplicationServiceProvider.class);
270 // Look for our class instance and save it
272 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
273 for (XacmlApplicationServiceProvider application : applicationLoader) {
275 // Is it our service?
277 if (application instanceof MonitoringPdpApplication) {
279 // Should be the first and only one
281 assertThat(service).isNull();
282 service = application;
284 strDump.append(application.applicationName());
285 strDump.append(" supports ");
286 strDump.append(application.supportedPolicyTypes());
287 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
289 LOGGER.debug("{}", strDump);
291 // Tell it to initialize based on the properties file
292 // we just built for it.
294 service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);