Changed Xacml-pdp to report pdp group defined in XacmlPdpParameters config file
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / TestAbbreviateDecisionResults.java
1 /*-
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdpx.main.rest;
22
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;
28
29 import java.io.File;
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;
39 import java.util.Map;
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.pdpx.main.startstop.XacmlPdpActivator;
71 import org.onap.policy.xacml.pdp.application.monitoring.MonitoringPdpApplication;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 public class TestAbbreviateDecisionResults {
76
77     private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
78
79     private static int port;
80     private static Main main;
81     private static HttpClient client;
82     private static CommonTestData testData = new CommonTestData();
83
84     private static Properties properties = new Properties();
85     private static File propertiesFile;
86     private static XacmlApplicationServiceProvider service;
87
88     private static RestServerParameters policyApiParameters;
89
90     @ClassRule
91     public static final TemporaryFolder appsFolder = new TemporaryFolder();
92
93     /**
94      * BeforeClass setup environment.
95      *
96      * @throws IOException Cannot create temp apps folder
97      * @throws Exception   exception if service does not start
98      */
99     @BeforeClass
100     public static void beforeClass() throws Exception {
101         port = NetworkUtil.allocPort();
102         //
103         // Copy test directory over of the application directories
104         //
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)));
109         });
110
111         // Start the Monitoring Application
112         startXacmlApplicationService(apps);
113
114         // Load monitoring policy
115         TestUtils.loadPolicies("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml", service);
116
117         // Create parameters for XacmlPdPService
118         RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port),
119                 RestServerParameters.class);
120         policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), RestServerParameters.class);
121         TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false),
122                 TopicParameterGroup.class);
123         XacmlPdpParameterGroup params =
124                 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", rest, policyApiParameters,
125                 topicParameterGroup, apps.getAbsolutePath());
126         StandardCoder gson = new StandardCoder();
127         File fileParams = appsFolder.newFile("params.json");
128         String jsonParams = gson.encode(params);
129         LOGGER.info("Creating new params: {}", jsonParams);
130         Files.write(fileParams.toPath(), jsonParams.getBytes());
131         //
132         // Start the service
133         //
134         main = startXacmlPdpService(fileParams);
135         XacmlPdpActivator.getCurrent().startXacmlRestController();
136         //
137         // Make sure it is running
138         //
139         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
140             throw new IllegalStateException("Cannot connect to port " + port);
141         }
142         //
143         // Create a client
144         //
145         client = getNoAuthHttpClient();
146     }
147
148     /**
149      * Clean up.
150      */
151     @AfterClass
152     public static void after() throws PolicyXacmlPdpException {
153         stopXacmlPdpService(main);
154         client.shutdown();
155     }
156
157     /**
158      * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
159      * should have been removed from the response.
160      */
161     @Test
162     public void testAbbreviateDecisionResult() {
163
164         LOGGER.info("Running testAbbreviateDecisionResult");
165
166         try {
167             // Create DecisionRequest
168             DecisionRequest request = new DecisionRequest();
169             request.setOnapName("DCAE");
170             request.setOnapComponent("PolicyHandler");
171             request.setOnapInstance("622431a4-9dea-4eae-b443-3b2164639c64");
172             request.setAction("configure");
173             Map<String, Object> resource = new HashMap<String, Object>();
174             resource.put("policy-id", "onap.scaleout.tca");
175             request.setResource(resource);
176
177             // Query decision API
178             DecisionResponse response = getDecision(request);
179             LOGGER.info("Decision Response {}", response);
180
181             assertFalse(response.getPolicies().isEmpty());
182
183             @SuppressWarnings("unchecked")
184             Map<String, Object> policy = (Map<String, Object>) response.getPolicies().get("onap.scaleout.tca");
185             assertTrue(policy.containsKey("type"));
186             assertFalse(policy.containsKey("properties"));
187             assertFalse(policy.containsKey("name"));
188             assertFalse(policy.containsKey("version"));
189             assertTrue(policy.containsKey("metadata"));
190
191         } catch (Exception e) {
192             LOGGER.error("Exception {}", e);
193             fail("testAbbreviateDecisionResult failed due to: " + e.getLocalizedMessage());
194         }
195     }
196
197     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
198         final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
199         return new Main(XacmlPdpConfigParameters);
200     }
201
202     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
203         main.shutdown();
204     }
205
206     /**
207      * Performs the POST request to Decision API.
208      *
209      */
210     private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
211
212         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
213         Response response = client.post("", entityRequest, Collections.emptyMap());
214
215         assertEquals(200, response.getStatus());
216         return HttpClient.getBody(response, DecisionResponse.class);
217     }
218
219     /**
220      * Create HttpClient.
221      *
222      */
223     private static HttpClient getNoAuthHttpClient()
224             throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
225         BusTopicParams clientParams = new BusTopicParams();
226         clientParams.setClientName("testName");
227         clientParams.setSerializationProvider(GsonMessageBodyHandler.class.getName());
228         clientParams.setUseHttps(false);
229         clientParams.setAllowSelfSignedCerts(false);
230         clientParams.setHostname("localhost");
231         clientParams.setPort(port);
232         clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
233         clientParams.setUserName("healthcheck");
234         clientParams.setPassword("zb!XztG34");
235         clientParams.setManaged(true);
236         client = new JerseyClient(clientParams);
237         return client;
238     }
239
240     private static void copy(Path source, Path dest) {
241         try {
242             LOGGER.info("Copying {} to {}", source, dest);
243             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
244         } catch (IOException e) {
245             LOGGER.error("Failed to copy {} to {}", source, dest);
246         }
247     }
248
249     /**
250      * Initializes the Monitoring application service.
251      *
252      * @param apps - the path to xacml.properties file
253      */
254     private static void startXacmlApplicationService(File apps)
255             throws XacmlApplicationException, CoderException, IOException {
256         LOGGER.info("****** Starting Xacml Application Service ******");
257         //
258         // Setup our temporary folder
259         //
260         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
261             new File(apps, "monitoring/" + filename).delete();
262             return appsFolder.newFile("apps/monitoring/" + filename);
263         };
264         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
265                 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
266         //
267         // Load XacmlApplicationServiceProvider service
268         //
269         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
270                 .load(XacmlApplicationServiceProvider.class);
271         //
272         // Look for our class instance and save it
273         //
274         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
275         for (XacmlApplicationServiceProvider application : applicationLoader) {
276             //
277             // Is it our service?
278             //
279             if (application instanceof MonitoringPdpApplication) {
280                 //
281                 // Should be the first and only one
282                 //
283                 assertThat(service).isNull();
284                 service = application;
285             }
286             strDump.append(application.applicationName());
287             strDump.append(" supports ");
288             strDump.append(application.supportedPolicyTypes());
289             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
290         }
291         LOGGER.debug("{}", strDump);
292         //
293         // Tell it to initialize based on the properties file
294         // we just built for it.
295         //
296         service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);
297     }
298 }