d416cd3b3027278a1b3d0c6fd71381633d9fa8ed
[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 = new XacmlPdpParameterGroup("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());
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() {
162
163         LOGGER.info("Running testAbbreviateDecisionResult");
164
165         try {
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);
175
176             // Query decision API
177             DecisionResponse response = getDecision(request);
178             LOGGER.info("Decision Response {}", response);
179
180             assertFalse(response.getPolicies().isEmpty());
181
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"));
189
190         } catch (Exception e) {
191             LOGGER.error("Exception {}", e);
192             fail("testAbbreviateDecisionResult failed due to: " + e.getLocalizedMessage());
193         }
194     }
195
196     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
197         final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
198         return new Main(XacmlPdpConfigParameters);
199     }
200
201     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
202         main.shutdown();
203     }
204
205     /**
206      * Performs the POST request to Decision API.
207      *
208      */
209     private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
210
211         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
212         Response response = client.post("", entityRequest, Collections.emptyMap());
213
214         assertEquals(200, response.getStatus());
215         return HttpClient.getBody(response, DecisionResponse.class);
216     }
217
218     /**
219      * Create HttpClient.
220      *
221      */
222     private static HttpClient getNoAuthHttpClient()
223             throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
224         BusTopicParams clientParams = new BusTopicParams();
225         clientParams.setClientName("testName");
226         clientParams.setSerializationProvider(GsonMessageBodyHandler.class.getName());
227         clientParams.setUseHttps(false);
228         clientParams.setAllowSelfSignedCerts(false);
229         clientParams.setHostname("localhost");
230         clientParams.setPort(port);
231         clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
232         clientParams.setUserName("healthcheck");
233         clientParams.setPassword("zb!XztG34");
234         clientParams.setManaged(true);
235         client = new JerseyClient(clientParams);
236         return client;
237     }
238
239     private static void copy(Path source, Path dest) {
240         try {
241             LOGGER.info("Copying {} to {}", source, dest);
242             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
243         } catch (IOException e) {
244             LOGGER.error("Failed to copy {} to {}", source, dest);
245         }
246     }
247
248     /**
249      * Initializes the Monitoring application service.
250      *
251      * @param apps - the path to xacml.properties file
252      */
253     private static void startXacmlApplicationService(File apps)
254             throws XacmlApplicationException, CoderException, IOException {
255         LOGGER.info("****** Starting Xacml Application Service ******");
256         //
257         // Setup our temporary folder
258         //
259         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
260             new File(apps, "monitoring/" + filename).delete();
261             return appsFolder.newFile("apps/monitoring/" + filename);
262         };
263         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
264                 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
265         //
266         // Load XacmlApplicationServiceProvider service
267         //
268         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
269                 .load(XacmlApplicationServiceProvider.class);
270         //
271         // Look for our class instance and save it
272         //
273         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
274         for (XacmlApplicationServiceProvider application : applicationLoader) {
275             //
276             // Is it our service?
277             //
278             if (application instanceof MonitoringPdpApplication) {
279                 //
280                 // Should be the first and only one
281                 //
282                 assertThat(service).isNull();
283                 service = application;
284             }
285             strDump.append(application.applicationName());
286             strDump.append(" supports ");
287             strDump.append(application.supportedPolicyTypes());
288             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
289         }
290         LOGGER.debug("{}", strDump);
291         //
292         // Tell it to initialize based on the properties file
293         // we just built for it.
294         //
295         service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);
296     }
297 }