37a669d2a9a033fda346a8bfbba8c2a30df1488d
[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.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 RestServerParameters 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), 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());
129         //
130         // Start the service
131         //
132         main = startXacmlPdpService(fileParams);
133         //
134         // Make sure it is running
135         //
136         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
137             throw new IllegalStateException("Cannot connect to port " + port);
138         }
139         //
140         // Create a client
141         //
142         client = getNoAuthHttpClient();
143     }
144
145     /**
146      * Clean up.
147      */
148     @AfterClass
149     public static void after() throws PolicyXacmlPdpException {
150         stopXacmlPdpService(main);
151         client.shutdown();
152     }
153
154     /**
155      * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
156      * should have been removed from the response.
157      */
158     @Test
159     public void testAbbreviateDecisionResult() {
160
161         LOGGER.info("Running testAbbreviateDecisionResult");
162
163         try {
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);
173
174             // Query decision API
175             DecisionResponse response = getDecision(request);
176             LOGGER.info("Decision Response {}", response);
177
178             assertFalse(response.getPolicies().isEmpty());
179
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"));
187
188         } catch (Exception e) {
189             LOGGER.error("Exception {}", e);
190             fail("testAbbreviateDecisionResult failed due to: " + e.getLocalizedMessage());
191         }
192     }
193
194     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
195         final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
196         return new Main(XacmlPdpConfigParameters);
197     }
198
199     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
200         main.shutdown();
201     }
202
203     /**
204      * Performs the POST request to Decision API.
205      *
206      */
207     private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
208
209         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
210         Response response = client.post("", entityRequest, Collections.emptyMap());
211
212         assertEquals(200, response.getStatus());
213         return HttpClient.getBody(response, DecisionResponse.class);
214     }
215
216     /**
217      * Create HttpClient.
218      *
219      */
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);
234         return client;
235     }
236
237     private static void copy(Path source, Path dest) {
238         try {
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);
243         }
244     }
245
246     /**
247      * Initializes the Monitoring application service.
248      *
249      * @param apps - the path to xacml.properties file
250      */
251     private static void startXacmlApplicationService(File apps)
252             throws XacmlApplicationException, CoderException, IOException {
253         LOGGER.info("****** Starting Xacml Application Service ******");
254         //
255         // Setup our temporary folder
256         //
257         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
258             new File(apps, "monitoring/" + filename).delete();
259             return appsFolder.newFile("apps/monitoring/" + filename);
260         };
261         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
262                 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
263         //
264         // Load XacmlApplicationServiceProvider service
265         //
266         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
267                 .load(XacmlApplicationServiceProvider.class);
268         //
269         // Look for our class instance and save it
270         //
271         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
272         for (XacmlApplicationServiceProvider application : applicationLoader) {
273             //
274             // Is it our service?
275             //
276             if (application instanceof MonitoringPdpApplication) {
277                 //
278                 // Should be the first and only one
279                 //
280                 assertThat(service).isNull();
281                 service = application;
282             }
283             strDump.append(application.applicationName());
284             strDump.append(" supports ");
285             strDump.append(application.supportedPolicyTypes());
286             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
287         }
288         LOGGER.debug("{}", strDump);
289         //
290         // Tell it to initialize based on the properties file
291         // we just built for it.
292         //
293         service.initialize(propertiesFile.toPath().getParent(), policyApiParameters);
294     }
295 }