Change RestServerParameters to BusTopicParams
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / TestAbbreviateDecisionResults.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2021 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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdpx.main.rest;
23
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;
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.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;
73
74 public class TestAbbreviateDecisionResults {
75
76     private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
77
78     private static int port;
79     private static Main main;
80     private static HttpClient client;
81     private static CommonTestData testData = new CommonTestData();
82
83     private static Properties properties = new Properties();
84     private static File propertiesFile;
85     private static XacmlApplicationServiceProvider service;
86
87     private static BusTopicParams policyApiParameters;
88
89     @ClassRule
90     public static final TemporaryFolder appsFolder = new TemporaryFolder();
91
92     /**
93      * BeforeClass setup environment.
94      *
95      * @throws IOException Cannot create temp apps folder
96      * @throws Exception   exception if service does not start
97      */
98     @BeforeClass
99     public static void beforeClass() throws Exception {
100         port = NetworkUtil.allocPort();
101         //
102         // Copy test directory over of the application directories
103         //
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)));
108         });
109
110         // Start the Monitoring Application
111         startXacmlApplicationService(apps);
112
113         // Load monitoring policy
114         TestUtils.loadPolicies("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml", service);
115
116         // Create parameters for XacmlPdPService
117         RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port),
118                 RestServerParameters.class);
119         policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), BusTopicParams.class);
120         TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false),
121                 TopicParameterGroup.class);
122         XacmlPdpParameterGroup params =
123                 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", 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());
130         //
131         // Start the service
132         //
133         main = startXacmlPdpService(fileParams);
134         XacmlPdpActivator.getCurrent().startXacmlRestController();
135         //
136         // Make sure it is running
137         //
138         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
139             throw new IllegalStateException("Cannot connect to port " + port);
140         }
141         //
142         // Create a client
143         //
144         client = getNoAuthHttpClient();
145     }
146
147     /**
148      * Clean up.
149      */
150     @AfterClass
151     public static void after() throws PolicyXacmlPdpException {
152         stopXacmlPdpService(main);
153         client.shutdown();
154     }
155
156     /**
157      * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
158      * should have been removed from the response.
159      */
160     @Test
161     public void testAbbreviateDecisionResult() throws HttpClientConfigException {
162
163         LOGGER.info("Running testAbbreviateDecisionResult");
164
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);
174
175         // Query decision API
176         DecisionResponse response = getDecision(request);
177         LOGGER.info("Decision Response {}", response);
178
179         assertFalse(response.getPolicies().isEmpty());
180
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"));
188     }
189
190     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
191         final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
192         return new Main(XacmlPdpConfigParameters);
193     }
194
195     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
196         main.shutdown();
197     }
198
199     /**
200      * Performs the POST request to Decision API.
201      *
202      */
203     private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
204
205         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
206         Response response = client.post("", entityRequest, Collections.emptyMap());
207
208         assertEquals(200, response.getStatus());
209         return HttpClient.getBody(response, DecisionResponse.class);
210     }
211
212     /**
213      * Create HttpClient.
214      *
215      */
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);
229         return client;
230     }
231
232     private static void copy(Path source, Path dest) {
233         try {
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);
238         }
239     }
240
241     /**
242      * Initializes the Monitoring application service.
243      *
244      * @param apps - the path to xacml.properties file
245      */
246     private static void startXacmlApplicationService(File apps)
247             throws XacmlApplicationException, CoderException, IOException {
248         LOGGER.info("****** Starting Xacml Application Service ******");
249         //
250         // Setup our temporary folder
251         //
252         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
253             new File(apps, "monitoring/" + filename).delete();
254             return appsFolder.newFile("apps/monitoring/" + filename);
255         };
256         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
257                 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
258         //
259         // Load XacmlApplicationServiceProvider service
260         //
261         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
262                 .load(XacmlApplicationServiceProvider.class);
263         //
264         // Look for our class instance and save it
265         //
266         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
267         for (XacmlApplicationServiceProvider application : applicationLoader) {
268             //
269             // Is it our service?
270             //
271             if (application instanceof MonitoringPdpApplication) {
272                 //
273                 // Should be the first and only one
274                 //
275                 assertThat(service).isNull();
276                 service = application;
277             }
278             strDump.append(application.applicationName());
279             strDump.append(" supports ");
280             strDump.append(application.supportedPolicyTypes());
281             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
282         }
283         LOGGER.debug("{}", strDump);
284         //
285         // Tell it to initialize based on the properties file
286         // we just built for it.
287         //
288         service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);
289     }
290 }