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