2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
4 * Modifications Copyright (C) 2020 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;
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() throws HttpClientConfigException {
163 LOGGER.info("Running testAbbreviateDecisionResult");
165 // Create DecisionRequest
166 DecisionRequest request = new DecisionRequest();
167 request.setOnapName("DCAE");
168 request.setOnapComponent("PolicyHandler");
169 request.setOnapInstance("622431a4-9dea-4eae-b443-3b2164639c64");
170 request.setAction("configure");
171 Map<String, Object> resource = new HashMap<String, Object>();
172 resource.put("policy-id", "onap.scaleout.tca");
173 request.setResource(resource);
175 // Query decision API
176 DecisionResponse response = getDecision(request);
177 LOGGER.info("Decision Response {}", response);
179 assertFalse(response.getPolicies().isEmpty());
181 @SuppressWarnings("unchecked")
182 Map<String, Object> policy = (Map<String, Object>) response.getPolicies().get("onap.scaleout.tca");
183 assertTrue(policy.containsKey("type"));
184 assertFalse(policy.containsKey("properties"));
185 assertFalse(policy.containsKey("name"));
186 assertFalse(policy.containsKey("version"));
187 assertTrue(policy.containsKey("metadata"));
190 private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
191 final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
192 return new Main(XacmlPdpConfigParameters);
195 private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
200 * Performs the POST request to Decision API.
203 private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
205 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
206 Response response = client.post("", entityRequest, Collections.emptyMap());
208 assertEquals(200, response.getStatus());
209 return HttpClient.getBody(response, DecisionResponse.class);
216 private static HttpClient getNoAuthHttpClient()
217 throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
218 BusTopicParams clientParams = new BusTopicParams();
219 clientParams.setClientName("testName");
220 clientParams.setUseHttps(false);
221 clientParams.setAllowSelfSignedCerts(false);
222 clientParams.setHostname("localhost");
223 clientParams.setPort(port);
224 clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
225 clientParams.setUserName("healthcheck");
226 clientParams.setPassword("zb!XztG34");
227 clientParams.setManaged(true);
228 client = new JerseyClient(clientParams);
232 private static void copy(Path source, Path dest) {
234 LOGGER.info("Copying {} to {}", source, dest);
235 Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
236 } catch (IOException e) {
237 LOGGER.error("Failed to copy {} to {}", source, dest);
242 * Initializes the Monitoring application service.
244 * @param apps - the path to xacml.properties file
246 private static void startXacmlApplicationService(File apps)
247 throws XacmlApplicationException, CoderException, IOException {
248 LOGGER.info("****** Starting Xacml Application Service ******");
250 // Setup our temporary folder
252 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
253 new File(apps, "monitoring/" + filename).delete();
254 return appsFolder.newFile("apps/monitoring/" + filename);
256 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
257 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
259 // Load XacmlApplicationServiceProvider service
261 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
262 .load(XacmlApplicationServiceProvider.class);
264 // Look for our class instance and save it
266 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
267 for (XacmlApplicationServiceProvider application : applicationLoader) {
269 // Is it our service?
271 if (application instanceof MonitoringPdpApplication) {
273 // Should be the first and only one
275 assertThat(service).isNull();
276 service = application;
278 strDump.append(application.applicationName());
279 strDump.append(" supports ");
280 strDump.append(application.supportedPolicyTypes());
281 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
283 LOGGER.debug("{}", strDump);
285 // Tell it to initialize based on the properties file
286 // we just built for it.
288 service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);