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;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
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;
41 import javax.ws.rs.client.Entity;
42 import javax.ws.rs.core.MediaType;
43 import javax.ws.rs.core.Response;
44 import javax.ws.rs.core.Response.Status;
46 import org.junit.AfterClass;
47 import org.junit.BeforeClass;
48 import org.junit.ClassRule;
49 import org.junit.Test;
50 import org.junit.rules.TemporaryFolder;
51 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
52 import org.onap.policy.common.endpoints.http.client.HttpClient;
53 import org.onap.policy.common.gson.GsonMessageBodyHandler;
54 import org.onap.policy.common.utils.network.NetworkUtil;
55 import org.onap.policy.models.decisions.concepts.DecisionRequest;
56 import org.onap.policy.models.decisions.concepts.DecisionResponse;
57 import org.onap.policy.models.errors.concepts.ErrorResponse;
58 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
59 import org.onap.policy.pdpx.main.parameters.RestServerBuilder;
60 import org.onap.policy.pdpx.main.parameters.RestServerParameters;
61 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
62 import org.onap.policy.pdpx.main.startstop.Main;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public class TestDecision {
68 private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
70 private static Main main;
71 private static HttpClient client;
74 public static final TemporaryFolder appsFolder = new TemporaryFolder();
77 * BeforeClass setup environment.
78 * @throws IOException Cannot create temp apps folder
79 * @throws Exception exception if service does not start
82 public static void beforeClass() throws Exception {
83 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
84 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
86 // Copy test directory over of the application directories
88 Path src = Paths.get("src/test/resources/apps");
89 File apps = appsFolder.newFolder("apps");
90 Files.walk(src).forEach(source -> {
91 copy(source, apps.toPath().resolve(src.relativize(source)));
94 // Get the parameters file correct.
96 RestServerParameters rest = new RestServerParameters(new RestServerBuilder()
97 .setHost("0.0.0.0").setPort(6969).setUserName("healthcheck").setPassword("zb!XztG34"));
98 XacmlPdpParameterGroup params = new XacmlPdpParameterGroup("XacmlPdpGroup", rest, apps.getAbsolutePath());
99 final Gson gson = new GsonBuilder().create();
100 File fileParams = appsFolder.newFile("params.json");
101 String jsonParams = gson.toJson(params);
102 LOGGER.info("Creating new params: {}", jsonParams);
103 Files.write(fileParams.toPath(), jsonParams.getBytes());
107 main = startXacmlPdpService(fileParams);
109 // Make sure it is running
111 if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 20, 1000L)) {
112 throw new IllegalStateException("Cannot connect to port 6969");
117 client = getNoAuthHttpClient();
121 public static void after() throws PolicyXacmlPdpException {
122 stopXacmlPdpService(main);
126 public void testDecision_UnsupportedAction() throws KeyManagementException, NoSuchAlgorithmException,
127 ClassNotFoundException {
129 LOGGER.info("Running test testDecision_UnsupportedAction");
131 DecisionRequest request = new DecisionRequest();
132 request.setOnapName("DROOLS");
133 request.setAction("foo");
134 Map<String, Object> guard = new HashMap<String, Object>();
135 guard.put("actor", "foo");
136 guard.put("recipe", "bar");
137 guard.put("target", "somevnf");
138 guard.put("clname", "phoneyloop");
139 request.setResource(guard);
141 ErrorResponse response = getErrorDecision(request);
142 LOGGER.info("Response {}", response);
143 assertThat(response.getResponseCode()).isEqualTo(Status.BAD_REQUEST);
144 assertThat(response.getErrorMessage()).isEqualToIgnoringCase("No application for action foo");
148 public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException,
149 ClassNotFoundException {
151 LOGGER.info("Running test testDecision_Guard");
153 DecisionRequest request = new DecisionRequest();
154 request.setOnapName("DROOLS");
155 request.setAction("guard");
156 Map<String, Object> guard = new HashMap<String, Object>();
157 guard.put("actor", "foo");
158 guard.put("recipe", "bar");
159 guard.put("target", "somevnf");
160 guard.put("clname", "phoneyloop");
161 request.setResource(guard);
163 DecisionResponse response = getDecision(request);
164 LOGGER.info("Response {}", response);
165 assertThat(response.getStatus()).isEqualTo("Permit");
168 private static Main startXacmlPdpService(File params) {
169 final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath(), "-p",
170 "parameters/topic.properties"};
171 return new Main(XacmlPdpConfigParameters);
174 private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
178 private DecisionResponse getDecision(DecisionRequest request) {
180 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
181 Response response = client.post("", entityRequest, Collections.emptyMap());
183 assertEquals(200, response.getStatus());
185 return HttpClient.getBody(response, DecisionResponse.class);
188 private ErrorResponse getErrorDecision(DecisionRequest request) {
190 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
191 Response response = client.post("", entityRequest, Collections.emptyMap());
193 assertEquals(400, response.getStatus());
195 return HttpClient.getBody(response, ErrorResponse.class);
198 private static HttpClient getNoAuthHttpClient()
199 throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
200 return HttpClient.factory.build(BusTopicParams.builder()
201 .clientName("testDecisionClient")
202 .serializationProvider(GsonMessageBodyHandler.class.getName())
203 .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(6969)
204 .basePath("policy/pdpx/v1/decision")
205 .userName("healthcheck").password("zb!XztG34").managed(true).build());
208 private static void copy(Path source, Path dest) {
210 LOGGER.info("Copying {} to {}", source, dest);
211 Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
212 } catch (IOException e) {
213 LOGGER.error("Failed to copy {} to {}", source, dest);