Added the new versioning validation for policy and policy type
[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-2020 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2019 Nordix Foundation.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.api.main.rest;
24
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertTrue;
29
30 import java.io.File;
31 import java.lang.reflect.Constructor;
32 import java.lang.reflect.Modifier;
33 import java.security.SecureRandom;
34 import java.util.Base64;
35 import java.util.Collections;
36 import java.util.Properties;
37
38 import javax.net.ssl.SSLContext;
39 import javax.net.ssl.TrustManager;
40 import javax.ws.rs.client.Client;
41 import javax.ws.rs.client.ClientBuilder;
42 import javax.ws.rs.client.Entity;
43 import javax.ws.rs.client.Invocation;
44 import javax.ws.rs.client.WebTarget;
45 import javax.ws.rs.core.Response;
46
47 import org.glassfish.jersey.client.ClientProperties;
48 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
49 import org.junit.AfterClass;
50 import org.junit.Before;
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.models.base.PfModelException;
68 import org.onap.policy.models.errors.concepts.ErrorResponse;
69 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
70 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityKey;
71 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
72 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
73 import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy;
74
75 /**
76  * Class to perform unit test of {@link ApiRestServer}.
77  *
78  * @author Chenfei Gao (cgao@research.att.com)
79  */
80 public class TestApiRestServer {
81     private static final String ALIVE = "alive";
82     private static final String SELF = NetworkUtil.getHostname();
83     private static final String NAME = "Policy API";
84     private static final String APP_JSON = "application/json";
85     private static final String APP_YAML = "application/yaml";
86
87     private static final String HEALTHCHECK_ENDPOINT = "healthcheck";
88     private static final String STATISTICS_ENDPOINT = "statistics";
89
90     private static final String POLICYTYPES = "policytypes";
91     private static final String POLICYTYPES_TCA = "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app";
92     private static final String POLICYTYPES_COLLECTOR =
93             "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server";
94     private static final String POLICYTYPES_TCA_VERSION =
95             "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0";
96     private static final String POLICYTYPES_TCA_LATEST =
97             "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app/versions/latest";
98     private static final String POLICYTYPES_COLLECTOR_VERSION =
99             "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/1.0.0";
100     private static final String POLICYTYPES_COLLECTOR_LATEST =
101             "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server/versions/latest";
102
103     private static final String POLICYTYPES_TCA_POLICIES =
104             "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies";
105     private static final String POLICYTYPES_TCA_POLICIES_VCPE =
106             "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca";
107     private static final String POLICYTYPES_TCA_POLICIES_VCPE_VERSION1 = "policytypes/"
108             + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/1.0.0";
109     private static final String POLICYTYPES_TCA_POLICIES_VCPE_VERSION2 = "policytypes/"
110             + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/2.0.0";
111     private static final String POLICYTYPES_TCA_POLICIES_VCPE_LATEST = "policytypes/"
112             + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/latest";
113     private static final String POLICYTYPES_TCA_POLICIES_VCPE_DEPLOYED = "policytypes/"
114             + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/deployed";
115
116     private static final String GUARD_POLICYTYPE = "onap.policies.controlloop.Guard";
117     private static final String GUARD_POLICIES = "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies";
118     private static final String GUARD_POLICIES_VDNS_FL_LATEST =
119             "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.frequency.scaleout"
120                     + "/versions/latest";
121     private static final String GUARD_POLICIES_VDNS_FL_DEPLOYED =
122             "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.frequency.scaleout"
123                     + "/versions/deployed";
124     private static final String GUARD_POLICIES_VDNS_MINMAX_LATEST =
125             "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.minmax.scaleout"
126                     + "/versions/latest";
127     private static final String GUARD_POLICIES_VDNS_FL_VERSION = "policytypes/"
128             + "onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.frequency.scaleout/versions/1";
129     private static final String GUARD_POLICIES_VDNS_MINMAX_VERSION =
130             "policytypes/" + "onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.minmax.scaleout/versions/1";
131
132     private static final String OPS_POLICYTYPE = "onap.policies.controlloop.Operational";
133     private static final String OPS_POLICIES =
134             "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies";
135     private static final String OPS_POLICIES_VCPE_LATEST =
136             "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.restart"
137                     + "/versions/latest";
138     private static final String OPS_POLICIES_VCPE_DEPLOYED =
139             "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.restart"
140                     + "/versions/deployed";
141     private static final String OPS_POLICIES_VDNS_LATEST =
142             "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.scaleout"
143                     + "/versions/latest";
144     private static final String OPS_POLICIES_VFIREWALL_LATEST =
145             "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.modifyconfig"
146                     + "/versions/latest";
147     private static final String OPS_POLICIES_VCPE_VERSION = "policytypes/"
148             + "onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.restart/versions/1";
149     private static final String OPS_POLICIES_VDNS_VERSION = "policytypes/"
150             + "onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.scaleout/versions/1";
151     private static final String OPS_POLICIES_VFIREWALL_VERSION = "policytypes/"
152             + "onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.modifyconfig/versions/1";
153     private static final String POLICIES = "policies";
154
155     private static final String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
156
157     // @formatter:off
158     private static final String[] TOSCA_POLICY_RESOURCE_NAMES = {
159         "policies/vCPE.policy.monitoring.input.tosca.json",
160         "policies/vCPE.policy.monitoring.input.tosca.v2.yaml",
161         "policies/vDNS.policy.monitoring.input.tosca.json",
162         "policies/vDNS.policy.monitoring.input.tosca.v2.yaml",
163         "policies/vFirewall.policy.monitoring.input.tosca.json",
164         "policies/vFirewall.policy.monitoring.input.tosca.v2.yaml"
165     };
166
167     private static final String[] TOSCA_POLICIES_RESOURCE_NAMES = {
168         "policies/vCPE.policies.optimization.input.tosca.json",
169         "policies/vCPE.policies.optimization.input.tosca.v2.yaml"
170     };
171
172     private static final String[] TOSCA_POLICYTYPE_RESOURCE_NAMES = {
173         "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml",
174         "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
175         "policytypes/onap.policies.Optimization.yaml",
176         "policytypes/onap.policies.controlloop.Operational.yaml",
177         "policytypes/onap.policies.controlloop.guard.Blacklist.yaml",
178         "policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml",
179         "policytypes/onap.policies.controlloop.guard.MinMax.yaml",
180         "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
181         "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
182         "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
183         "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
184         "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
185         "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
186         "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
187         "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
188         "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
189         "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml"
190     };
191
192     private static final String[] LEGACY_GUARD_POLICY_RESOURCE_NAMES = {
193         "policies/vDNS.policy.guard.frequency.input.json",
194         "policies/vDNS.policy.guard.minmax.input.json"
195     };
196
197     private static final String[] LEGACY_GUARD_POLICY_NAMES = {
198         "guard.frequency.scaleout",
199         "guard.minmax.scaleout"
200     };
201
202     private static final String[] LEGACY_OPERATIONAL_POLICY_RESOURCE_NAMES = {
203         "policies/vCPE.policy.operational.input.json",
204         "policies/vDNS.policy.operational.input.json",
205         "policies/vFirewall.policy.operational.input.json"
206     };
207
208     private static final String[] LEGACY_OPERATIONAL_POLICY_NAMES = {
209         "operational.restart",
210         "operational.scaleout",
211         "operational.modifyconfig"
212     };
213
214     private static PolicyModelsProviderParameters providerParams;
215     private static ApiParameterGroup apiParamGroup;
216     private static PolicyProvider policyProvider;
217     private static PolicyTypeProvider policyTypeProvider;
218
219     // @formatter:on
220
221     private static final StandardCoder standardCoder = new StandardCoder();
222
223     private static int apiPort;
224     private static Main apiMain;
225
226     private static StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
227
228     /**
229      * Initializes parameters.
230      *
231      * @throws PfModelException the PfModel parsing exception
232      */
233     @BeforeClass
234     public static void setupParameters() throws PfModelException {
235         providerParams = new PolicyModelsProviderParameters();
236         providerParams.setDatabaseDriver("org.h2.Driver");
237         providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
238         providerParams.setDatabaseUser("policy");
239         providerParams.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
240         providerParams.setPersistenceUnit("ToscaConceptTest");
241         apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList());
242         ParameterService.register(apiParamGroup, true);
243
244         policyTypeProvider = new PolicyTypeProvider();
245         policyProvider = new PolicyProvider();
246     }
247
248     /**
249      * Set up test environemnt.
250      *
251      * @throws Exception on test setup exceptions
252      */
253     @BeforeClass
254     public static void beforeStartApiService() throws Exception {
255         apiPort = NetworkUtil.allocPort();
256
257         final String[] apiConfigParameters = new String[2];
258         final Properties systemProps = System.getProperties();
259         systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
260         systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
261         System.setProperties(systemProps);
262         new CommonTestData().makeParameters("src/test/resources/parameters/ApiConfigParameters_Https.json",
263                 "src/test/resources/parameters/ApiConfigParameters_HttpsXXX.json", apiPort);
264         apiConfigParameters[0] = "-c";
265         apiConfigParameters[1] = "src/test/resources/parameters/ApiConfigParameters_HttpsXXX.json";
266         apiMain = new Main(apiConfigParameters);
267     }
268
269     /**
270      * Method for cleanup after each test.
271      */
272     @AfterClass
273     public static void teardown() throws Exception {
274         policyTypeProvider.close();
275         policyProvider.close();
276
277         if (apiMain != null) {
278             apiMain.shutdown();
279         }
280     }
281
282     /**
283      * Clear the database before each test.
284      *
285      * @throws Exception on clearing exceptions
286      */
287     @Before
288     public void beforeClearDatabase() throws Exception {
289
290         Response rawResponse = readResource(POLICYTYPES, APP_JSON);
291         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
292
293         for (ToscaEntityKey policyTypeKey : response.getPolicyTypesAsMap().keySet()) {
294             if (GUARD_POLICYTYPE.equals(policyTypeKey.getName())
295                     || OPS_POLICYTYPE.equals(policyTypeKey.getName())) {
296                 deleteLegacyPolicies(LEGACY_GUARD_POLICY_NAMES, GUARD_POLICYTYPE);
297                 deleteLegacyPolicies(LEGACY_OPERATIONAL_POLICY_NAMES, OPS_POLICYTYPE);
298             } else {
299                 deleteToscaPolicies(policyTypeKey);
300             }
301
302             String deletePolicyTypePath =
303                     "policytypes/" + policyTypeKey.getName() + "/versions/" + policyTypeKey.getVersion();
304             deleteResource(deletePolicyTypePath, APP_JSON);
305         }
306     }
307
308     @Test
309     public void testApiStatisticsConstructorIsPrivate() {
310
311         try {
312             final Constructor<ApiStatisticsManager> constructor = ApiStatisticsManager.class.getDeclaredConstructor();
313             assertTrue(Modifier.isPrivate(constructor.getModifiers()));
314             constructor.setAccessible(true);
315             constructor.newInstance();
316
317         } catch (final Exception exp) {
318             assertTrue(exp.getCause().toString().contains("Instantiation of the class is not allowed"));
319         }
320     }
321
322     @Test
323     public void testCreatePolicyTypes() throws Exception {
324         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
325             Response rawResponse = createResource(POLICYTYPES, resrcName);
326             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
327             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
328             assertNotNull(response);
329             assertFalse(response.getPolicyTypes().isEmpty());
330         }
331
332         // Send a policy type with a null value to trigger an error
333         Response rawResponse = readResource(POLICYTYPES, APP_JSON);
334         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
335         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
336         String firstPolicyType = response.getPolicyTypes().keySet().iterator().next();
337         response.getPolicyTypes().put(firstPolicyType, null);
338         Response rawResponse2 = createResource(POLICYTYPES, standardCoder.encode(response));
339         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse2.getStatus());
340         ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class);
341         assertEquals("no policy types specified in the service template", errorResponse.getErrorMessage());
342     }
343
344     @Test
345     public void testCreatePolicies() throws Exception {
346         createPolicyTypes();
347
348         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
349             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
350             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
351         }
352
353         new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit();
354
355         // Send a policy with no policy type trigger an error
356         String toscaPolicy = ResourceUtils
357                 .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]);
358
359         toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.cdap.tca.hi.lo.app", "");
360         TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml");
361
362         Response rawResponse2 =
363                 createResource(POLICYTYPES_TCA_POLICIES, "src/test/resources/policies/BadTestPolicy.yaml");
364         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse2.getStatus());
365         ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class);
366         assertEquals("policy type id does not match", errorResponse.getErrorMessage());
367     }
368
369     @Test
370     public void testSimpleCreatePolicies() throws Exception {
371         testCreatePolicyTypes();
372
373         for (String resrcName : TOSCA_POLICIES_RESOURCE_NAMES) {
374             Response rawResponse = createResource(POLICIES, resrcName);
375             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
376         }
377
378         new File("src/test/resources/policies/BadTestPolicy.yaml").deleteOnExit();
379
380         // Send a policy with no policy type trigger an error
381         String toscaPolicy = ResourceUtils
382                 .getResourceAsString(TOSCA_POLICY_RESOURCE_NAMES[TOSCA_POLICIES_RESOURCE_NAMES.length - 1]);
383
384         toscaPolicy = toscaPolicy.replaceAll("onap.policies.monitoring.cdap.tca.hi.lo.app", "");
385         TextFileUtils.putStringAsTextFile(toscaPolicy, "src/test/resources/policies/BadTestPolicy.yaml");
386
387         Response rawResponse2 = createResource(POLICIES, "src/test/resources/policies/BadTestPolicy.yaml");
388         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse2.getStatus());
389         ErrorResponse errorResponse = rawResponse2.readEntity(ErrorResponse.class);
390         assertEquals("policy type NULL:0.0.0 for policy onap.restart.tca:2.0.0 does not exist",
391                 errorResponse.getErrorMessage());
392     }
393
394     @Test
395     public void testCreateGuardPolicies() throws Exception {
396         createPolicyTypes();
397
398         for (String resrcName : LEGACY_GUARD_POLICY_RESOURCE_NAMES) {
399             Response rawResponse = createGuardPolicy(GUARD_POLICIES, resrcName);
400             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
401         }
402     }
403
404     @Test
405     public void testCreateOperationalPolicies() throws Exception {
406         createPolicyTypes();
407
408         for (String resrcName : LEGACY_OPERATIONAL_POLICY_RESOURCE_NAMES) {
409             Response rawResponse = createOperationalPolicy(OPS_POLICIES, resrcName);
410             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
411         }
412     }
413
414     @Test
415     public void testHealthCheckSuccessJson() throws Exception {
416         testHealthCheckSuccess(APP_JSON);
417     }
418
419     @Test
420     public void testHealthCheckSuccessYaml() throws Exception {
421         testHealthCheckSuccess(APP_YAML);
422     }
423
424     private void testHealthCheckSuccess(String mediaType) throws Exception {
425         final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT, mediaType);
426         final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
427         validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
428     }
429
430     @Test
431     public void testApiStatistics_200_Json() throws Exception {
432         testApiStatistics_200(APP_JSON);
433     }
434
435     @Test
436     public void testApiStatistics_200_Yaml() throws Exception {
437         testApiStatistics_200(APP_YAML);
438     }
439
440     private void testApiStatistics_200(String mediaType) throws Exception {
441         Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType);
442         StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
443         validateStatisticsReport(report, 200);
444         updateApiStatistics();
445         invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType);
446         report = invocationBuilder.get(StatisticsReport.class);
447         validateStatisticsReport(report, 200);
448         ApiStatisticsManager.resetAllStatistics();
449     }
450
451     @Test
452     public void testReadPolicyTypesJson() throws Exception {
453         testReadPolicyTypes(APP_JSON);
454     }
455
456     @Test
457     public void testReadPolicyTypesYaml() throws Exception {
458         testReadPolicyTypes(APP_YAML);
459     }
460
461     private void testReadPolicyTypes(String mediaType) throws Exception {
462         createPolicyTypes();
463
464         Response rawResponse = readResource(POLICYTYPES, mediaType);
465         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
466         ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
467         assertFalse(response.getPolicyTypes().isEmpty());
468
469         rawResponse = readResource(POLICYTYPES_TCA, mediaType);
470         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
471
472         rawResponse = readResource(POLICYTYPES_TCA_VERSION, mediaType);
473         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
474
475         rawResponse = readResource(POLICYTYPES_TCA_LATEST, mediaType);
476         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
477
478         rawResponse = readResource(POLICYTYPES_COLLECTOR, mediaType);
479         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
480
481         rawResponse = readResource(POLICYTYPES_COLLECTOR_VERSION, mediaType);
482         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
483
484         rawResponse = readResource(POLICYTYPES_COLLECTOR_LATEST, mediaType);
485         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
486     }
487
488     @Test
489     public void testDeletePolicyTypeJson() throws Exception {
490         testDeletePolicyType(APP_JSON);
491     }
492
493     @Test
494     public void testDeletePolicyTypeYaml() throws Exception {
495         testDeletePolicyType(APP_YAML);
496     }
497
498     private void testDeletePolicyType(String mediaType) throws Exception {
499         createPolicyTypes();
500
501         Response rawResponse = deleteResource(POLICYTYPES_TCA_VERSION, mediaType);
502         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
503
504         rawResponse = readResource(POLICYTYPES_TCA_VERSION, mediaType);
505         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
506
507         rawResponse = deleteResource(POLICYTYPES_COLLECTOR_VERSION, mediaType);
508         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
509
510         rawResponse = readResource(POLICYTYPES_COLLECTOR_VERSION, mediaType);
511         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
512
513         rawResponse = readResource(POLICYTYPES_COLLECTOR, mediaType);
514         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
515
516         rawResponse = readResource(POLICYTYPES_COLLECTOR_LATEST, mediaType);
517         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
518         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
519         assertEquals("policy type with ID "
520                 + "onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server:null does not exist",
521                 errorResponse.getErrorMessage());
522     }
523
524     @Test
525     public void testReadPoliciesJson() throws Exception {
526         testReadPolicies(APP_JSON);
527     }
528
529     @Test
530     public void testReadPoliciesYaml() throws Exception {
531         testReadPolicies(APP_YAML);
532     }
533
534     private void testReadPolicies(String mediaType) throws Exception {
535         testCreatePolicies();
536
537         Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType);
538         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
539
540         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType);
541         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
542
543         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
544         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
545
546         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION2, mediaType);
547         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
548
549         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType);
550         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
551     }
552
553     @Test
554     public void testDeletePoliciesJson() throws Exception {
555         testDeletePolicies(APP_JSON);
556     }
557
558     @Test
559     public void testDeletePoliciesYaml() throws Exception {
560         testDeletePolicies(APP_YAML);
561     }
562
563     private void testDeletePolicies(String mediaType) throws Exception {
564         createPolicyTypes();
565
566         Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
567         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
568         ErrorResponse error = rawResponse.readEntity(ErrorResponse.class);
569         assertEquals(
570                 "policy with ID onap.restart.tca:1.0.0 and "
571                         + "type onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist",
572                 error.getErrorMessage());
573     }
574
575     @Test
576     public void testDeletePolicyVersionJson() throws Exception {
577         testDeletePolicyVersion(APP_JSON);
578     }
579
580     @Test
581     public void testDeletePolicyVersionYaml() throws Exception {
582         testDeletePolicyVersion(APP_YAML);
583     }
584
585     private void testDeletePolicyVersion(String mediaType) throws Exception {
586         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
587             Response rawResponse = createResource(POLICYTYPES, resrcName);
588             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
589             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
590             assertNotNull(response);
591             assertFalse(response.getPolicyTypes().isEmpty());
592         }
593         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
594             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
595             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
596         }
597         Response rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
598         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
599
600         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION1, mediaType);
601         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
602         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
603         assertEquals(
604                 "policy with ID onap.restart.tca:1.0.0 and type "
605                         + "onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist",
606                 errorResponse.getErrorMessage());
607
608         rawResponse = deleteResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION2, mediaType);
609         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
610
611         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_VERSION2, mediaType);
612         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
613         errorResponse = rawResponse.readEntity(ErrorResponse.class);
614         assertEquals(
615                 "policy with ID onap.restart.tca:2.0.0 and type "
616                         + "onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist",
617                 errorResponse.getErrorMessage());
618
619         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE, mediaType);
620         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
621         errorResponse = rawResponse.readEntity(ErrorResponse.class);
622         assertEquals(
623                 "policy with ID onap.restart.tca:null and type "
624                         + "onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist",
625                 errorResponse.getErrorMessage());
626
627         rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_LATEST, mediaType);
628         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
629         errorResponse = rawResponse.readEntity(ErrorResponse.class);
630         assertEquals(
631                 "policy with ID onap.restart.tca:null and type "
632                         + "onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 does not exist",
633                 errorResponse.getErrorMessage());
634     }
635
636     @Test
637     public void testGetAllVersionOfPolicyJson() throws Exception {
638         testGetAllVersionOfPolicy(APP_JSON);
639     }
640
641     @Test
642     public void testGetAllVersionOfPolicyYaml() throws Exception {
643         testGetAllVersionOfPolicy(APP_YAML);
644     }
645
646     private void testGetAllVersionOfPolicy(String mediaType) throws Exception {
647         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
648             Response rawResponse = createResource(POLICYTYPES, resrcName);
649             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
650             ToscaServiceTemplate response = rawResponse.readEntity(ToscaServiceTemplate.class);
651             assertNotNull(response);
652             assertFalse(response.getPolicyTypes().isEmpty());
653         }
654         for (String resrcName : TOSCA_POLICY_RESOURCE_NAMES) {
655             Response rawResponse = createResource(POLICYTYPES_TCA_POLICIES, resrcName);
656             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
657         }
658         Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES, mediaType);
659         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
660     }
661
662     @Test
663     public void testReadGuardPoliciesJson() throws Exception {
664         testReadGuardPolicies(APP_JSON);
665     }
666
667     @Test
668     public void testReadGuardPoliciesYaml() throws Exception {
669         testReadGuardPolicies(APP_YAML);
670     }
671
672     private void testReadGuardPolicies(String mediaType) throws Exception {
673         createGuardPolicies();
674
675         Response rawResponse = readResource(GUARD_POLICIES_VDNS_FL_LATEST, mediaType);
676         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
677
678         rawResponse = readResource(GUARD_POLICIES_VDNS_FL_VERSION, mediaType);
679         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
680
681         rawResponse = readResource(GUARD_POLICIES_VDNS_MINMAX_LATEST, mediaType);
682         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
683
684         rawResponse = readResource(GUARD_POLICIES_VDNS_MINMAX_VERSION, mediaType);
685         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
686     }
687
688     @Test
689     public void testReadOperationalPoliciesJson() throws Exception {
690         testReadOperationalPolicies(APP_JSON);
691     }
692
693     @Test
694     public void testReadOperationalPoliciesYaml() throws Exception {
695         testReadOperationalPolicies(APP_YAML);
696     }
697
698     private void testReadOperationalPolicies(String mediaType) throws Exception {
699         createOperationalPolicies();
700
701         Response rawResponse = readResource(OPS_POLICIES_VCPE_LATEST, mediaType);
702         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
703
704         rawResponse = readResource(OPS_POLICIES_VCPE_VERSION, mediaType);
705         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
706
707         rawResponse = readResource(OPS_POLICIES_VDNS_LATEST, mediaType);
708         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
709
710         rawResponse = readResource(OPS_POLICIES_VDNS_VERSION, mediaType);
711         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
712
713         rawResponse = readResource(OPS_POLICIES_VFIREWALL_LATEST, mediaType);
714         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
715
716         rawResponse = readResource(OPS_POLICIES_VFIREWALL_VERSION, mediaType);
717         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
718     }
719
720     @Test
721     public void testDeleteGuardPolicyJson() throws Exception {
722         testDeleteGuardPolicy(APP_JSON);
723     }
724
725     @Test
726     public void testDeleteGuardPolicyYaml() throws Exception {
727         testDeleteGuardPolicy(APP_YAML);
728     }
729
730     private void testDeleteGuardPolicy(String mediaType) throws Exception {
731         createGuardPolicies();
732
733         Response rawResponse = deleteResource(GUARD_POLICIES_VDNS_FL_VERSION, mediaType);
734         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
735     }
736
737     @Test
738     public void testGetDeployedVersionsOfGuardPolicyJson() throws Exception {
739         testGetDeployedVersionsOfGuardPolicy(APP_JSON);
740     }
741
742     @Test
743     public void testGetDeployedVersionsOfGuardPolicyYaml() throws Exception {
744         testGetDeployedVersionsOfGuardPolicy(APP_YAML);
745     }
746
747     private void testGetDeployedVersionsOfGuardPolicy(String mediaType) throws Exception {
748         Response rawResponse = readResource(GUARD_POLICIES_VDNS_FL_DEPLOYED, mediaType);
749         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
750         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
751         assertEquals(
752                 "could not find policy with ID guard.frequency.scaleout and type "
753                         + "onap.policies.controlloop.guard.FrequencyLimiter:1.0.0 deployed in any pdp group",
754                 errorResponse.getErrorMessage());
755     }
756
757     @Test
758     public void testDeleteOperationalPolicyJson() throws Exception {
759         testDeleteOperationalPolicy(APP_JSON);
760     }
761
762     @Test
763     public void testDeleteOperationalPolicyYaml() throws Exception {
764         testDeleteOperationalPolicy(APP_YAML);
765     }
766
767     private void testDeleteOperationalPolicy(String mediaType) throws Exception {
768         createPolicyTypes();
769
770         Response rawResponse = deleteResource(OPS_POLICIES_VCPE_VERSION, mediaType);
771         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
772         ErrorResponse error = rawResponse.readEntity(ErrorResponse.class);
773         assertEquals("no policy found for policy: operational.restart:1", error.getErrorMessage());
774     }
775
776     @Test
777     public void testGetDeployedVersionsOfPolicyJson() throws Exception {
778         testGetDeployedVersionsOfPolicy(APP_JSON);
779     }
780
781     @Test
782     public void testGetDeployedVersionsOfPolicyYaml() throws Exception {
783         testGetDeployedVersionsOfPolicy(APP_YAML);
784     }
785
786     private void testGetDeployedVersionsOfPolicy(String mediaType) throws Exception {
787         Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_DEPLOYED, mediaType);
788         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
789         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
790         assertEquals(
791                 "could not find policy with ID onap.restart.tca and type "
792                         + "onap.policies.monitoring.cdap.tca.hi.lo.app:1.0.0 deployed in any pdp group",
793                 errorResponse.getErrorMessage());
794     }
795
796     @Test
797     public void testGetLatestVersionOfOperationalPolicyJson() throws Exception {
798         testGetLatestVersionOfOperationalPolicy(APP_JSON);
799     }
800
801     @Test
802     public void testGetLatestVersionOfOperationalPolicyYaml() throws Exception {
803         testGetLatestVersionOfOperationalPolicy(APP_YAML);
804     }
805
806     private void testGetLatestVersionOfOperationalPolicy(String mediaType) throws Exception {
807         Response rawResponse = readResource(OPS_POLICIES_VDNS_LATEST, mediaType);
808         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
809         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
810         assertEquals("no policy found for policy: operational.scaleout:null", errorResponse.getErrorMessage());
811     }
812
813     @Test
814     public void testGetSpecificVersionOfOperationalPolicyJson() throws Exception {
815         testGetSpecificVersionOfOperationalPolicy(APP_JSON);
816     }
817
818     @Test
819     public void testGetSpecificVersionOfOperationalPolicyYaml() throws Exception {
820         testGetSpecificVersionOfOperationalPolicy(APP_YAML);
821     }
822
823     private void testGetSpecificVersionOfOperationalPolicy(String mediaType) throws Exception {
824         Response rawResponse = readResource(OPS_POLICIES_VDNS_VERSION, mediaType);
825         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
826         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
827         assertEquals("no policy found for policy: operational.scaleout:1", errorResponse.getErrorMessage());
828     }
829
830     @Test
831     public void testGetDeployedVersionsOfOperationalPolicyJson() throws Exception {
832         testGetDeployedVersionsOfOperationalPolicy(APP_JSON);
833     }
834
835     @Test
836     public void testGetDeployedVersionsOfOperationalPolicyYaml() throws Exception {
837         testGetDeployedVersionsOfOperationalPolicy(APP_YAML);
838     }
839
840     private void testGetDeployedVersionsOfOperationalPolicy(String mediaType) throws Exception {
841         Response rawResponse = readResource(OPS_POLICIES_VCPE_DEPLOYED, mediaType);
842         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
843         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
844         assertEquals(
845                 "could not find policy with ID operational.restart and type "
846                         + "onap.policies.controlloop.Operational:1.0.0 deployed in any pdp group",
847                 errorResponse.getErrorMessage());
848     }
849
850     @Test
851     public void testDeleteSpecificVersionOfOperationalPolicy() throws Exception {
852         createOperationalPolicies();
853
854         Response rawResponse = deleteResource(OPS_POLICIES_VDNS_VERSION, APP_JSON);
855         assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
856
857         rawResponse = deleteResource(OPS_POLICIES_VDNS_VERSION, APP_YAML);
858         assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
859         ErrorResponse errorResponse = rawResponse.readEntity(ErrorResponse.class);
860         assertEquals("no policy found for policy: operational.scaleout:1", errorResponse.getErrorMessage());
861     }
862
863     private Response createResource(String endpoint, String resourceName) throws Exception {
864
865         String mediaType = APP_JSON; // default media type
866         ToscaServiceTemplate rawServiceTemplate = new ToscaServiceTemplate();
867         if (resourceName.endsWith(".json")) {
868             rawServiceTemplate =
869                     standardCoder.decode(ResourceUtils.getResourceAsString(resourceName), ToscaServiceTemplate.class);
870         } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) {
871             mediaType = APP_YAML;
872             rawServiceTemplate = standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName),
873                     ToscaServiceTemplate.class);
874         }
875
876         final Invocation.Builder invocationBuilder;
877
878         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
879
880         Entity<ToscaServiceTemplate> entity = Entity.entity(rawServiceTemplate, mediaType);
881         return invocationBuilder.post(entity);
882     }
883
884     private Response createGuardPolicy(String endpoint, String resourceName) throws Exception {
885
886         String mediaType = APP_JSON; // default media type
887         LegacyGuardPolicyInput rawGuardPolicy = new LegacyGuardPolicyInput();
888         if (resourceName.endsWith(".json")) {
889             rawGuardPolicy =
890                     standardCoder.decode(ResourceUtils.getResourceAsString(resourceName), LegacyGuardPolicyInput.class);
891         } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) {
892             mediaType = APP_YAML;
893             rawGuardPolicy = standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName),
894                     LegacyGuardPolicyInput.class);
895         }
896
897         final Invocation.Builder invocationBuilder;
898
899         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
900
901         Entity<LegacyGuardPolicyInput> entity = Entity.entity(rawGuardPolicy, mediaType);
902         return invocationBuilder.post(entity);
903     }
904
905     private Response createOperationalPolicy(String endpoint, String resourceName) throws Exception {
906
907         String mediaType = APP_JSON; // default media type
908         LegacyOperationalPolicy rawOpsPolicy = new LegacyOperationalPolicy();
909         if (resourceName.endsWith(".json")) {
910             rawOpsPolicy = standardCoder.decode(ResourceUtils.getResourceAsString(resourceName),
911                     LegacyOperationalPolicy.class);
912         } else if (resourceName.endsWith(".yaml") || resourceName.endsWith(".yml")) {
913             mediaType = APP_YAML;
914             rawOpsPolicy = standardYamlCoder.decode(ResourceUtils.getResourceAsString(resourceName),
915                     LegacyOperationalPolicy.class);
916         }
917
918         final Invocation.Builder invocationBuilder;
919
920         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
921
922         Entity<LegacyOperationalPolicy> entity = Entity.entity(rawOpsPolicy, mediaType);
923         return invocationBuilder.post(entity);
924     }
925
926     private Response readResource(String endpoint, String mediaType) throws Exception {
927
928         final Invocation.Builder invocationBuilder;
929
930         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
931
932         return invocationBuilder.get();
933
934     }
935
936     private Response deleteResource(String endpoint, String mediaType) throws Exception {
937
938         final Invocation.Builder invocationBuilder;
939
940         invocationBuilder = sendHttpsRequest(endpoint, mediaType);
941
942         return invocationBuilder.delete();
943     }
944
945     private void createPolicyTypes() throws Exception {
946         for (String resrcName : TOSCA_POLICYTYPE_RESOURCE_NAMES) {
947             Response rawResponse = createResource(POLICYTYPES, resrcName);
948             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
949         }
950     }
951
952     private void createGuardPolicies() throws Exception {
953         createPolicyTypes();
954
955         for (String resrcName : LEGACY_GUARD_POLICY_RESOURCE_NAMES) {
956             Response rawResponse = createGuardPolicy(GUARD_POLICIES, resrcName);
957             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
958         }
959     }
960
961     private void createOperationalPolicies() throws Exception {
962         createPolicyTypes();
963
964         for (String resrcName : LEGACY_OPERATIONAL_POLICY_RESOURCE_NAMES) {
965             Response rawResponse = createOperationalPolicy(OPS_POLICIES, resrcName);
966             assertEquals(Response.Status.OK.getStatusCode(), rawResponse.getStatus());
967         }
968     }
969
970     private Invocation.Builder sendHttpsRequest(final String endpoint, String mediaType) throws Exception {
971
972         final TrustManager[] noopTrustManager = NetworkUtil.getAlwaysTrustingManager();
973
974         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
975         sc.init(null, noopTrustManager, new SecureRandom());
976         final ClientBuilder clientBuilder =
977                 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
978         final Client client = clientBuilder.build();
979         final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
980         client.register(feature);
981
982         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
983         if (APP_JSON.equalsIgnoreCase(mediaType)) {
984             client.register(GsonMessageBodyHandler.class);
985         } else if (APP_YAML.equalsIgnoreCase(mediaType)) {
986             client.register(YamlMessageBodyHandler.class);
987         }
988
989         final WebTarget webTarget = client.target("https://localhost:" + apiPort + "/policy/api/v1/" + endpoint);
990
991         final Invocation.Builder invocationBuilder = webTarget.request(mediaType);
992
993         if (!NetworkUtil.isTcpPortOpen("localhost", apiPort, 60, 1000L)) {
994             throw new IllegalStateException("cannot connect to port " + apiPort);
995         }
996         return invocationBuilder;
997     }
998
999     private void updateApiStatistics() {
1000
1001         ApiStatisticsManager.updateTotalApiCallCount();
1002         ApiStatisticsManager.updateApiCallSuccessCount();
1003         ApiStatisticsManager.updateApiCallFailureCount();
1004         ApiStatisticsManager.updateTotalPolicyGetCount();
1005         ApiStatisticsManager.updateTotalPolicyPostCount();
1006         ApiStatisticsManager.updateTotalPolicyTypeGetCount();
1007         ApiStatisticsManager.updateTotalPolicyTypePostCount();
1008         ApiStatisticsManager.updatePolicyGetSuccessCount();
1009         ApiStatisticsManager.updatePolicyGetFailureCount();
1010         ApiStatisticsManager.updatePolicyPostSuccessCount();
1011         ApiStatisticsManager.updatePolicyPostFailureCount();
1012         ApiStatisticsManager.updatePolicyTypeGetSuccessCount();
1013         ApiStatisticsManager.updatePolicyTypeGetFailureCount();
1014         ApiStatisticsManager.updatePolicyTypePostSuccessCount();
1015         ApiStatisticsManager.updatePolicyTypePostFailureCount();
1016     }
1017
1018     private void validateStatisticsReport(final StatisticsReport report, final int code) {
1019
1020         assertEquals(code, report.getCode());
1021     }
1022
1023     private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
1024             final String message, final HealthCheckReport report) {
1025
1026         assertEquals(name, report.getName());
1027         assertEquals(url, report.getUrl());
1028         assertEquals(healthy, report.isHealthy());
1029         assertEquals(code, report.getCode());
1030         assertEquals(message, report.getMessage());
1031     }
1032
1033     private void deleteToscaPolicies(ToscaEntityKey policyTypeKey) throws Exception {
1034
1035         String getPoliciesPath =
1036                 "policytypes/" + policyTypeKey.getName() + "/versions/" + policyTypeKey.getVersion() + "/policies";
1037
1038         Response rawPolicyResponse = readResource(getPoliciesPath, APP_JSON);
1039         if (Response.Status.OK.getStatusCode() == rawPolicyResponse.getStatus()) {
1040             ToscaServiceTemplate policyResponse = rawPolicyResponse.readEntity(ToscaServiceTemplate.class);
1041
1042             for (ToscaEntityKey policyKey : policyResponse.getToscaTopologyTemplate().getPoliciesAsMap().keySet()) {
1043                 String deletePolicyPath =
1044                         "policytypes/" + policyTypeKey.getName() + "/versions/" + policyTypeKey.getVersion()
1045                                 + "/policies/" + policyKey.getName() + "/versions/" + policyKey.getVersion();
1046                 deleteResource(deletePolicyPath, APP_JSON);
1047             }
1048         }
1049     }
1050
1051     private void deleteLegacyPolicies(String[] legacyPolicyNames, String legacyPolicyType) throws Exception {
1052
1053         for (String policyName : legacyPolicyNames) {
1054             String policyPath =
1055                     "policytypes/" + legacyPolicyType + "/versions/1.0.0/policies/" + policyName + "/versions/1";
1056             if (Response.Status.OK.getStatusCode() == readResource(policyPath, APP_JSON).getStatus()) {
1057                 deleteResource(policyPath, APP_JSON);
1058             }
1059         }
1060     }
1061 }