2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 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.gson.GsonMessageBodyHandler;
57 import org.onap.policy.common.utils.coder.CoderException;
58 import org.onap.policy.common.utils.coder.StandardCoder;
59 import org.onap.policy.common.utils.network.NetworkUtil;
60 import org.onap.policy.models.decisions.concepts.DecisionRequest;
61 import org.onap.policy.models.decisions.concepts.DecisionResponse;
62 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
63 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
64 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
65 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
66 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
67 import org.onap.policy.pdpx.main.parameters.CommonTestData;
68 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
69 import org.onap.policy.pdpx.main.startstop.Main;
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 = new XacmlPdpParameterGroup("XacmlPdpGroup", rest, policyApiParameters,
123 topicParameterGroup, apps.getAbsolutePath());
124 StandardCoder gson = new StandardCoder();
125 File fileParams = appsFolder.newFile("params.json");
126 String jsonParams = gson.encode(params);
127 LOGGER.info("Creating new params: {}", jsonParams);
128 Files.write(fileParams.toPath(), jsonParams.getBytes());
132 main = startXacmlPdpService(fileParams);
134 // Make sure it is running
136 if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
137 throw new IllegalStateException("Cannot connect to port " + port);
142 client = getNoAuthHttpClient();
149 public static void after() throws PolicyXacmlPdpException {
150 stopXacmlPdpService(main);
155 * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
156 * should have been removed from the response.
159 public void testAbbreviateDecisionResult() {
161 LOGGER.info("Running testAbbreviateDecisionResult");
164 // Create DecisionRequest
165 DecisionRequest request = new DecisionRequest();
166 request.setOnapName("DCAE");
167 request.setOnapComponent("PolicyHandler");
168 request.setOnapInstance("622431a4-9dea-4eae-b443-3b2164639c64");
169 request.setAction("configure");
170 Map<String, Object> resource = new HashMap<String, Object>();
171 resource.put("policy-id", "onap.scaleout.tca");
172 request.setResource(resource);
174 // Query decision API
175 DecisionResponse response = getDecision(request);
176 LOGGER.info("Decision Response {}", response);
178 assertFalse(response.getPolicies().isEmpty());
180 @SuppressWarnings("unchecked")
181 Map<String, Object> policy = (Map<String, Object>) response.getPolicies().get("onap.scaleout.tca");
182 assertTrue(policy.containsKey("type"));
183 assertFalse(policy.containsKey("properties"));
184 assertFalse(policy.containsKey("name"));
185 assertFalse(policy.containsKey("version"));
186 assertTrue(policy.containsKey("metadata"));
188 } catch (Exception e) {
189 LOGGER.error("Exception {}", e);
190 fail("testAbbreviateDecisionResult failed due to: " + e.getLocalizedMessage());
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 BusTopicParams clientParams = new BusTopicParams();
223 clientParams.setClientName("testName");
224 clientParams.setSerializationProvider(GsonMessageBodyHandler.class.getName());
225 clientParams.setUseHttps(false);
226 clientParams.setAllowSelfSignedCerts(false);
227 clientParams.setHostname("localhost");
228 clientParams.setPort(port);
229 clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
230 clientParams.setUserName("healthcheck");
231 clientParams.setPassword("zb!XztG34");
232 clientParams.setManaged(true);
233 client = new JerseyClient(clientParams);
237 private static void copy(Path source, Path dest) {
239 LOGGER.info("Copying {} to {}", source, dest);
240 Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
241 } catch (IOException e) {
242 LOGGER.error("Failed to copy {} to {}", source, dest);
247 * Initializes the Monitoring application service.
249 * @param apps - the path to xacml.properties file
251 private static void startXacmlApplicationService(File apps)
252 throws XacmlApplicationException, CoderException, IOException {
253 LOGGER.info("****** Starting Xacml Application Service ******");
255 // Setup our temporary folder
257 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
258 new File(apps, "monitoring/" + filename).delete();
259 return appsFolder.newFile("apps/monitoring/" + filename);
261 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
262 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
264 // Load XacmlApplicationServiceProvider service
266 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
267 .load(XacmlApplicationServiceProvider.class);
269 // Look for our class instance and save it
271 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
272 for (XacmlApplicationServiceProvider application : applicationLoader) {
274 // Is it our service?
276 if (application instanceof MonitoringPdpApplication) {
278 // Should be the first and only one
280 assertThat(service).isNull();
281 service = application;
283 strDump.append(application.applicationName());
284 strDump.append(" supports ");
285 strDump.append(application.supportedPolicyTypes());
286 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
288 LOGGER.debug("{}", strDump);
290 // Tell it to initialize based on the properties file
291 // we just built for it.
293 service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);