Migrate policy api startup & config, controller to springboot
[policy/api.git] / main / src / test / java / org / onap / policy / api / main / rest / TestApiRestServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
4  *  Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
6  *  Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.api.main.rest;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertFalse;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertNull;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.security.SecureRandom;
35 import java.util.List;
36 import java.util.Map;
37 import javax.net.ssl.SSLContext;
38 import javax.net.ssl.TrustManager;
39 import javax.ws.rs.client.Client;
40 import javax.ws.rs.client.ClientBuilder;
41 import javax.ws.rs.client.Entity;
42 import javax.ws.rs.client.Invocation;
43 import javax.ws.rs.client.WebTarget;
44 import javax.ws.rs.core.Response;
45 import javax.ws.rs.core.Response.Status;
46 import org.glassfish.jersey.client.ClientProperties;
47 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
48 import org.junit.BeforeClass;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.onap.policy.api.main.PolicyApiApplication;
52 import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
53 import org.onap.policy.common.endpoints.report.HealthCheckReport;
54 import org.onap.policy.common.gson.GsonMessageBodyHandler;
55 import org.onap.policy.common.utils.coder.StandardCoder;
56 import org.onap.policy.common.utils.coder.StandardYamlCoder;
57 import org.onap.policy.common.utils.network.NetworkUtil;
58 import org.onap.policy.common.utils.resources.ResourceUtils;
59 import org.onap.policy.common.utils.resources.TextFileUtils;
60 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
61 import org.onap.policy.models.errors.concepts.ErrorResponse;
62 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.boot.test.context.SpringBootTest;
65 import org.springframework.boot.web.server.LocalServerPort;
66 import org.springframework.test.annotation.DirtiesContext;
67 import org.springframework.test.annotation.DirtiesContext.ClassMode;
68 import org.springframework.test.context.ActiveProfiles;
69 import org.springframework.test.context.DynamicPropertyRegistry;
70 import org.springframework.test.context.DynamicPropertySource;
71 import org.springframework.test.context.junit4.SpringRunner;
72
73 /**
74  * Class to perform unit test of {@link ApiRestController}.
75  *
76  * @author Chenfei Gao (cgao@research.att.com)
77  */
78 @RunWith(SpringRunner.class)
79 @SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
80 @ActiveProfiles("test")
81 @DirtiesContext(classMode = ClassMode.AFTER_CLASS)
82 public class TestApiRestServer {
83
84     private static final String ALIVE = "alive";
85     private static final String SELF = NetworkUtil.getHostname();
86     private static final String NAME = "Policy API";
87     private static final String APP_JSON = "application/json";
88     private static final String APP_YAML = "application/yaml";
89
90     private static final String HEALTHCHECK_ENDPOINT = "healthcheck";
91     private static final String STATISTICS_ENDPOINT = "statistics";
92
93     private static final String OP_POLICY_NAME_VCPE = "operational.restart";
94
95     private static final String POLICYTYPES = "policytypes";
96     private static final String POLICYTYPES_TCA = "policytypes/onap.policies.monitoring.tcagen2";
97     private static final String POLICYTYPES_COLLECTOR =
98             "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server";
99     private static final String POLICYTYPES_TCA_VERSION = "policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0";
100     private static final String POLICYTYPES_TCA_LATEST = "policytypes/onap.policies.monitoring.tcagen2/versions/latest";
101     private static final String POLICYTYPES_COLLECTOR_VERSION =
102             "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/1.0.0";
103     private static final String POLICYTYPES_COLLECTOR_LATEST =
104             "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/latest";
105
106     private static final String POLICYTYPES_DROOLS = "policytypes/onap.policies.controlloop.operational.common.Drools";
107     private static final String POLICYTYPES_DROOLS_VERSION = POLICYTYPES_DROOLS + "/versions/1.0.0";
108     private static final String POLICYTYPES_DROOLS_VERSION_LATEST = POLICYTYPES_DROOLS + "/versions/latest";
109
110     private static final String POLICYTYPES_NAMING_VERSION = POLICYTYPES + "/onap.policies.Naming/versions/1.0.0";
111
112     private static final String POLICYTYPES_TCA_POLICIES =
113             "policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0/policies";
114     private static final String POLICYTYPES_TCA_POLICIES_VCPE =
115             "policytypes/onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca";
116     private static final String POLICYTYPES_TCA_POLICIES_VCPE_VERSION1 =
117             "policytypes/" + "onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca/versions/1.0.0";
118     private static final String POLICYTYPES_TCA_POLICIES_VCPE_LATEST = "policytypes/"
119             + "onap.policies.monitoring.tcagen2/versions/1.0.0/policies/onap.restart.tca/versions/latest";
120
121     private static final String POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION =
122             POLICYTYPES_DROOLS_VERSION + "/policies/" + OP_POLICY_NAME_VCPE + "/versions/1.0.0";
123
124     private static final String POLICIES = "policies";
125
126     // @formatter:off
127     private static final String[] TOSCA_POLICY_RESOURCE_NAMES = {"policies/vCPE.policy.monitoring.input.tosca.json",
128         "policies/vCPE.policy.monitoring.input.tosca.yaml", "policies/vDNS.policy.monitoring.input.tosca.json",
129         "policies/vDNS.policy.monitoring.input.tosca.v2.yaml"};
130
131     private static final String[] TOSCA_POLICIES_RESOURCE_NAMES = {
132         "policies/vCPE.policies.optimization.input.tosca.json", "policies/vCPE.policies.optimization.input.tosca.yaml"};
133
134     private static final String TOSCA_POLICYTYPE_OP_RESOURCE =
135         "policytypes/onap.policies.controlloop.operational.Common.yaml";
136
137     private static final String[] TOSCA_POLICYTYPE_RESOURCE_NAMES = {
138         "policytypes/onap.policies.monitoring.tcagen2.yaml",
139         "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
140         "policytypes/onap.policies.controlloop.operational.common.Drools.yaml",
141         "policytypes/onap.policies.controlloop.guard.Common.yaml",
142         "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml",
143         "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml",
144         "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml",
145         "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
146         "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
147         "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
148         "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
149         "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
150         "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
151         "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
152         "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
153         "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
154         "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml"};
155
156     private static final String TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON =
157         "policies/vCPE.policy.operational.input.tosca.json";
158
159     private static final String TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML =
160         "policies/vCPE.policy.operational.input.tosca.yaml";
161
162     private static final String POLICIES_VCPE_VERSION1 = "policies/onap.restart.tca/versions/1.0.0";
163     // @formatter:on
164
165     private static final StandardCoder standardCoder = new StandardCoder();
166     private static StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
167     private static SelfSignedKeyStore keystore;
168
169     @LocalServerPort
170     private int apiPort;
171
172     @Autowired
173     private ApiStatisticsManager mgr;
174
175     /**
176      * Initializes parameters and set up test environment.
177      *
178      * @throws IOException on I/O exceptions
179      * @throws InterruptedException if interrupted
180      */
181     @BeforeClass
182     public static void setupParameters() throws IOException, InterruptedException {
183         keystore = new SelfSignedKeyStore();
184     }
185
186     @DynamicPropertySource
187     static void registerPgProperties(DynamicPropertyRegistry registry) {
188         registry.add("server.ssl.enabled", () -> "true");
189         registry.add("server.ssl.key-store", () -> keystore.getKeystoreName());
190         registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD);
191         registry.add("server.ssl.key-store-type", () -> "PKCS12");
192         registry.add("server.ssl.key-alias", () -> "policy@policy.onap.org");
193         registry.add("server.ssl.key-password", () -> SelfSignedKeyStore.PRIVATE_KEY_PASSWORD);
194     }
195
196     @Test
197     public void testCreatePolicyTypes() throws Exception {
198         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
199             Response rawResponse = createResource(POLICYTYPES, resrcName);
200             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
201             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
202             assertNotNull(response);
203             assertFalse(response.getPolicyTypes().isEmpty());
204         }
205
206         // Send a policy type with a null value to trigger an error
207         Response rawResponse = readResource(POLICYTYPES, APP_JSON);
208         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
209         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
210         String firstPolicyType = response.getPolicyTypes().keySet().iterator().next();
211         response.getPolicyTypes().put(firstPolicyType, null);
212         Response rawResponse2 = createResource(POLICYTYPES, standardCoder.encode(response));
213         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse2.getStatus());
214         ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class);
215         assertEquals("no policy types specified on service template", errorResponse.getErrorMessage());
216     }
217
218     @Test
219     public void testCreatePolicies() throws Exception {
220         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
221             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
222             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
223         }
224
225         new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit();
226
227         // Send a policy with no policy type trigger an error
228         String toscaPolicy = ResourceUtils
229                 .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]);
230
231         toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.tcagen2", "IDontExist");
232         TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml");
233
234         Response rawResponse2 =
235                 createResource(POLICYTYPES_TCA_POLICIES, "src/test/resources/policies/BadTestPolicy.yaml");
236         assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse2.getStatus());
237         ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class);
238         assertThat(errorResponse.getErrorMessage())
239                 .contains("item \"entity\" value \"onap.restart.tca:1.0.0\" INVALID, does not equal existing entity");
240     }
241
242     @Test
243     public void testSimpleCreatePolicies() throws Exception {
244         for (String resrcName : TOSCA_POLICIES_RESOURCE_NAMES) {
245             Response rawResponse = createResource(POLICIES, resrcName);
246             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
247         }
248
249         new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit();
250
251         // Send a policy with no policy type trigger an error
252         String toscaPolicy = ResourceUtils
253                 .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]);
254
255         toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.tcagen2", "IDontExist");
256         toscaPolicy = toscaPolicy.replaceAll("onap.restart.tca", "onap.restart.tca.IDontExist");
257         TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml");
258
259         Response rawResponse2 = createResource(POLICIES, "src/test/resources/policies/BadTestPolicy.yaml");
260         ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class);
261         assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), rawResponse2.getStatus());
262         assertThat(errorResponse.getErrorMessage())
263                 .contains("item \"policy type\" value \"IDontExist:1.0.0\" INVALID, not found");
264     }
265
266     @SuppressWarnings("unchecked")
267     @Test
268     public void testToscaCompliantOpDroolsPolicies() throws Exception {
269         Response rawResponse = createResource(POLICYTYPES, TOSCA_POLICYTYPE_OP_RESOURCE);
270         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
271
272         rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, APP_JSON);
273         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
274
275         rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_JSON);
276         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
277
278         rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML);
279         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
280
281         rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON);
282         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
283
284         rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON);
285         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
286
287         rawResponse = createResource(POLICIES, TOSCA_POLICY_OP_DROOLS_VCPE_RESOURSE_YAML);
288         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
289
290         rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON);
291         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
292
293         rawResponse = readResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_YAML);
294         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
295
296         ToscaServiceTemplate toscaVcpeSt = rawResponse.readEntity(ToscaServiceTemplate.class);
297         assertEquals(1, toscaVcpeSt.getToscaTopologyTemplate().getPolicies().size());
298         assertEquals(OP_POLICY_NAME_VCPE,
299                 toscaVcpeSt.getToscaTopologyTemplate().getPolicies().get(0).get(OP_POLICY_NAME_VCPE).getName());
300
301         Map<String, Object> props =
302                 toscaVcpeSt.getToscaTopologyTemplate().getPolicies().get(0).get(OP_POLICY_NAME_VCPE).getProperties();
303         assertNotNull(props);
304
305         List<Object> operations = (List<Object>) props.get("operations");
306         assertEquals(1, operations.size());
307         assertEquals(props.get("trigger"), ((Map<String, Object>) operations.get(0)).get("id"));
308
309         Map<String, Object> operation =
310                 (Map<String, Object>) ((Map<String, Object>) operations.get(0)).get("operation");
311         assertEquals("APPC", operation.get("actor"));
312         assertEquals("Restart", operation.get("operation"));
313
314         rawResponse = deleteResource(POLICYTYPES_DROOLS_POLICIES_VCPE_VERSION, APP_JSON);
315         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
316     }
317
318     @Test
319     public void testHealthCheckSuccessJson() throws Exception {
320         testHealthCheckSuccess(APP_JSON);
321     }
322
323     @Test
324     public void testHealthCheckSuccessYaml() throws Exception {
325         testHealthCheckSuccess(APP_YAML);
326     }
327
328     private void testHealthCheckSuccess(String mediaType) throws Exception {
329         final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT, mediaType);
330         final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
331         validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
332     }
333
334     @Test
335     public void testApiStatistics_200_Json() throws Exception {
336         testApiStatistics_200(APP_JSON);
337     }
338
339     @Test
340     public void testApiStatistics_200_Yaml() throws Exception {
341         testApiStatistics_200(APP_YAML);
342     }
343
344     private void testApiStatistics_200(String mediaType) throws Exception {
345         Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType);
346         StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
347         validateStatisticsReport(report, 200);
348         updateApiStatistics();
349         invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType);
350         report = invocationBuilder.get(StatisticsReport.class);
351         validateStatisticsReport(report, 200);
352         // ApiStatisticsManager.resetAllStatistics();
353     }
354
355     @Test
356     public void testReadPolicyTypesJson() throws Exception {
357         testReadPolicyTypes(APP_JSON);
358     }
359
360     @Test
361     public void testReadPolicyTypesYaml() throws Exception {
362         testReadPolicyTypes(APP_YAML);
363     }
364
365     private void testReadPolicyTypes(String mediaType) throws Exception {
366         Response rawResponse = readResource("policytypes/onap.policies.optimization.resource.HpaPolicy", mediaType);
367         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
368         ToscaServiceTemplate namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
369         assertNotNull(namingServiceTemplate);
370         assertEquals(3, namingServiceTemplate.getPolicyTypesAsMap().size());
371         assertEquals(5, namingServiceTemplate.getDataTypesAsMap().size());
372
373         rawResponse = readResource(POLICYTYPES, mediaType);
374         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
375         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
376         assertFalse(response.getPolicyTypes().isEmpty());
377
378         rawResponse = readResource(POLICYTYPES_TCA, mediaType);
379         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
380
381         rawResponse = readResource(POLICYTYPES_TCA_VERSION, mediaType);
382         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
383
384         rawResponse = readResource(POLICYTYPES_TCA_LATEST, mediaType);
385         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
386
387         rawResponse = readResource(POLICYTYPES_COLLECTOR, mediaType);
388         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
389
390         rawResponse = readResource(POLICYTYPES_COLLECTOR_VERSION, mediaType);
391         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
392
393         rawResponse = readResource(POLICYTYPES_COLLECTOR_LATEST, mediaType);
394         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
395
396         rawResponse = readResource(POLICYTYPES_DROOLS, mediaType);
397         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
398
399         rawResponse = readResource(POLICYTYPES_DROOLS_VERSION, mediaType);
400         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
401
402         rawResponse = readResource(POLICYTYPES_DROOLS_VERSION_LATEST, mediaType);
403         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
404
405         rawResponse = readResource(POLICYTYPES_NAMING_VERSION, mediaType);
406         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
407     }
408
409     @Test
410     public void testDeletePolicyTypeJson() throws Exception {
411         testDeletePolicyType(APP_JSON);
412     }
413
414     @Test
415     public void testDeletePolicyTypeYaml() throws Exception {
416         testDeletePolicyType(APP_YAML);
417     }
418
419     private void testDeletePolicyType(String mediaType) throws Exception {
420         Response rawResponse = deleteResource("policytypes/onap.policies.IDoNotExist/versions/1.0.0", mediaType);
421         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
422
423         rawResponse = createResource(POLICYTYPES, "policytypes/onap.policies.Test.yaml");
424         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
425
426         rawResponse = readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType);
427         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
428
429         rawResponse = deleteResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType);
430         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
431
432         rawResponse = readResource("policytypes/onap.policies.Test/versions/1.0.0", mediaType);
433         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
434     }
435
436     @Test
437     public void testReadPoliciesJson() throws Exception {
438         testReadPolicies(APP_JSON);
439     }
440
441     @Test
442     public void testReadPoliciesYaml() throws Exception {
443         testReadPolicies(APP_YAML);
444     }
445
446     private void testReadPolicies(String mediaType) throws Exception {
447         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
448             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
449             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
450         }
451
452         Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType);
453         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
454
455         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType);
456         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
457
458         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
459         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
460
461         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType);
462         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
463
464         rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
465         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
466
467     }
468
469     @Test
470     public void testNamingPolicyGet() throws Exception {
471
472         Response rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/"
473                 + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON);
474         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
475
476         rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/"
477                 + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0?mode=referenced", APP_JSON);
478         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
479
480         ToscaServiceTemplate namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
481         assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size());
482         assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size());
483         assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size());
484
485         rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/"
486                 + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest?mode=referenced", APP_JSON);
487         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
488
489         namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
490         assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size());
491         assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size());
492         assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size());
493
494         rawResponse =
495                 readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies?mode=referenced", APP_JSON);
496         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
497
498         namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
499         assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size());
500         assertEquals(1, namingServiceTemplate.getPolicyTypesAsMap().size());
501         assertEquals(3, namingServiceTemplate.getDataTypesAsMap().size());
502
503         rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/"
504                 + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/1.0.0", APP_JSON);
505         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
506
507         namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
508
509         assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size());
510         assertNull(namingServiceTemplate.getPolicyTypes());
511         assertNull(namingServiceTemplate.getDataTypes());
512
513         rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/"
514                 + "policies/SDNC_Policy.ONAP_NF_NAMING_TIMESTAMP/versions/latest", APP_JSON);
515         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
516
517         namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
518         assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size());
519         assertNull(namingServiceTemplate.getPolicyTypes());
520         assertNull(namingServiceTemplate.getDataTypes());
521
522         rawResponse = readResource("policytypes/onap.policies.Naming/versions/1.0.0/policies", APP_JSON);
523         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
524
525         namingServiceTemplate = rawResponse.readEntity(ToscaServiceTemplate.class);
526         assertEquals(1, namingServiceTemplate.getToscaTopologyTemplate().getPoliciesAsMap().size());
527         assertNull(namingServiceTemplate.getPolicyTypes());
528         assertNull(namingServiceTemplate.getDataTypes());
529     }
530
531     @Test
532     public void testDeletePoliciesJson() throws Exception {
533         testDeletePolicies(APP_JSON);
534     }
535
536     @Test
537     public void testDeletePoliciesYaml() throws Exception {
538         testDeletePolicies(APP_YAML);
539     }
540
541     private void testDeletePolicies(String mediaType) throws Exception {
542         Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
543         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
544         ErrorResponse error = rawResponse.readEntity(ErrorResponse.class);
545         assertEquals("policy onap.restart.tca:1.0.0 not found", error.getErrorMessage());
546     }
547
548     @Test
549     public void testDeletePolicyVersionJson() throws Exception {
550         testDeletePolicyVersion(APP_JSON);
551     }
552
553     @Test
554     public void testDeletePolicyVersionYaml() throws Exception {
555         testDeletePolicyVersion(APP_YAML);
556     }
557
558     private void testDeletePolicyVersion(String mediaType) throws Exception {
559         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
560             Response rawResponse = createResource(POLICYTYPES, resrcName);
561             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
562             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
563             assertNotNull(response);
564             assertFalse(response.getPolicyTypes().isEmpty());
565         }
566         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
567             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
568             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
569         }
570         Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
571         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
572
573         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
574         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
575         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
576         assertEquals("policies for onap.restart.tca:1.0.0 do not exist", errorResponse.getErrorMessage());
577
578         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType);
579         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
580         errorResponse = rawResponse.readEntity(ErrorResponse.class);
581         assertEquals("policies for onap.restart.tca:null do not exist", errorResponse.getErrorMessage());
582
583         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType);
584         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
585         errorResponse = rawResponse.readEntity(ErrorResponse.class);
586         assertEquals("policies for onap.restart.tca:null do not exist", errorResponse.getErrorMessage());
587     }
588
589     @Test
590     public void testGetAllVersionOfPolicyJson() throws Exception {
591         testGetAllVersionOfPolicy(APP_JSON);
592     }
593
594     @Test
595     public void testGetAllVersionOfPolicyYaml() throws Exception {
596         testGetAllVersionOfPolicy(APP_YAML);
597     }
598
599     private void testGetAllVersionOfPolicy(String mediaType) throws Exception {
600         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
601             Response rawResponse = createResource(POLICYTYPES, resrcName);
602             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
603             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
604             assertNotNull(response);
605             assertFalse(response.getPolicyTypes().isEmpty());
606         }
607         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
608             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
609             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
610         }
611         Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType);
612         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
613     }
614
615     @Test
616     public void testGetPoliciesJson() throws Exception {
617         getPolicies(APP_JSON);
618     }
619
620     @Test
621     public void testGetPoliciesYaml() throws Exception {
622         getPolicies(APP_YAML);
623     }
624
625     private void getPolicies(String mediaType) throws Exception {
626         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
627             Response rawResponse = createResource(POLICYTYPES, resrcName);
628             assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
629             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
630             assertThat(response).isNotNull();
631             assertThat(response.getPolicyTypes()).isNotEmpty();
632         }
633         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
634             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
635             assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
636         }
637         Response rawResponse = readResource(POLICIES, mediaType);
638         assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
639         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
640         assertThat(response.getToscaTopologyTemplate().getPolicies()).isNotEmpty();
641     }
642
643     @Test
644     public void testGetSpecificPolicyJson() throws Exception {
645         getSpecificPolicy(APP_JSON);
646     }
647
648     @Test
649     public void testGetSpecificPolicyYaml() throws Exception {
650         getSpecificPolicy(APP_YAML);
651     }
652
653     private void getSpecificPolicy(String mediaType) throws Exception {
654         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
655             Response rawResponse = createResource(POLICYTYPES, resrcName);
656             assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
657             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
658             assertThat(response).isNotNull();
659             assertThat(response.getPolicyTypes()).isNotEmpty();
660         }
661         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
662             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
663             assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
664         }
665         Response rawResponse = readResource(POLICIES_VCPE_VERSION1, mediaType);
666         assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
667         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
668         assertThat(response.getToscaTopologyTemplate().getPolicies()).hasSize(1);
669     }
670
671     @Test
672     public void testDeleteSpecificPolicy() throws Exception {
673         Response rawResponse;
674         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
675             rawResponse = createResource(POLICYTYPES, resrcName);
676             assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
677             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
678             assertThat(response).isNotNull();
679             assertThat(response.getPolicyTypes()).isNotEmpty();
680         }
681         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
682             rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
683             assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
684         }
685
686         rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON);
687         assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
688
689         // delete a particular policy
690         rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON);
691         assertThat(rawResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
692
693         rawResponse = readResource(POLICIES_VCPE_VERSION1, APP_JSON);
694         assertThat(rawResponse.getStatus()).isEqualTo(Status.NOT_FOUND.getStatusCode());
695
696         rawResponse = deleteResource(POLICIES_VCPE_VERSION1, APP_JSON);
697         assertThat(rawResponse.getStatus()).isEqualTo(Status.NOT_FOUND.getStatusCode());
698
699     }
700
701
702     private Response createResource(String endpoint, String resourceName) throws Exception {
703
704         String mediaType = APP_JSON; // default media type
705         ToscaServiceTemplate rawServiceTemplate = new ToscaServiceTemplate();
706         if (resourceName.endsWith(".json")) {
707             rawServiceTemplate =
708                     standardCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class);
709         } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) {
710             mediaType = APP_YAML;
711             rawServiceTemplate = standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName),
712                     ToscaServiceTemplate.class);
713         }
714
715         final Invocation.Builder invocationBuilder;
716
717         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
718
719         Entity<ToscaServiceTemplate> entity = Entity.entity(rawServiceTemplate, mediaType);
720         return invocationBuilder.post(entity);
721     }
722
723     private Response readResource(String endpoint, String mediaType) throws Exception {
724
725         final Invocation.Builder invocationBuilder;
726
727         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
728
729         return invocationBuilder.get();
730
731     }
732
733     private Response deleteResource(String endpoint, String mediaType) throws Exception {
734
735         final Invocation.Builder invocationBuilder;
736
737         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
738
739         return invocationBuilder.delete();
740     }
741
742     private Invocation.Builder sendHttpsRequest(final String endpoint, String mediaType) throws Exception {
743
744         final TrustManager[] noopTrustManager = NetworkUtil.getAlwaysTrustingManager();
745
746         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
747         sc.init(null, noopTrustManager, new SecureRandom());
748         final ClientBuilder clientBuilder =
749                 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
750         final Client client = clientBuilder.build();
751         final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34");
752         client.register(feature);
753
754         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
755         if (APP_JSON.equalsIgnoreCase(mediaType)) {
756             client.register(GsonMessageBodyHandler.class);
757         } else if (APP_YAML.equalsIgnoreCase(mediaType)) {
758             client.register(YamlMessageBodyHandler.class);
759         }
760
761         final WebTarget webTarget = client.target("https://localhost:" + apiPort + "/policy/api/v1/" + endpoint);
762
763         final Invocation.Builder invocationBuilder = webTarget.request(mediaType);
764
765         if (!NetworkUtil.isTcpPortOpen("localhost", apiPort, 60, 1000L)) {
766             throw new IllegalStateException("cannot connect to port " + apiPort);
767         }
768         return invocationBuilder;
769     }
770
771     private void updateApiStatistics() {
772         mgr.updateTotalApiCallCount();
773         mgr.updateApiCallSuccessCount();
774         mgr.updateApiCallFailureCount();
775         mgr.updateTotalPolicyGetCount();
776         mgr.updateTotalPolicyPostCount();
777         mgr.updateTotalPolicyTypeGetCount();
778         mgr.updateTotalPolicyTypePostCount();
779         mgr.updatePolicyGetSuccessCount();
780         mgr.updatePolicyGetFailureCount();
781         mgr.updatePolicyPostSuccessCount();
782         mgr.updatePolicyPostFailureCount();
783         mgr.updatePolicyTypeGetSuccessCount();
784         mgr.updatePolicyTypeGetFailureCount();
785         mgr.updatePolicyTypePostSuccessCount();
786         mgr.updatePolicyTypePostFailureCount();
787     }
788
789     private void validateStatisticsReport(final StatisticsReport report, final int code) {
790
791         assertEquals(code, report.getCode());
792     }
793
794     private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
795             final String message, final HealthCheckReport report) {
796
797         assertEquals(name, report.getName());
798         assertEquals(url, report.getUrl());
799         assertEquals(healthy, report.isHealthy());
800         assertEquals(code, report.getCode());
801         assertEquals(message, report.getMessage());
802     }
803 }