Merge "Adds basic stability tests for Policy API"
[policy/api.git] / main / src / test / java / org / onap / policy / api / main / rest / TestHttpsStatisticApiRestServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy API 
4  * ================================================================================ 
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
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.fail;
27
28 import java.security.KeyManagementException;
29 import java.security.NoSuchAlgorithmException;
30 import java.security.SecureRandom;
31 import java.security.cert.X509Certificate;
32 import java.util.Properties;
33
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.TrustManager;
36 import javax.net.ssl.X509TrustManager;
37
38 import javax.ws.rs.client.Client;
39 import javax.ws.rs.client.ClientBuilder;
40 import javax.ws.rs.client.Invocation;
41 import javax.ws.rs.client.WebTarget;
42 import javax.ws.rs.core.MediaType;
43
44 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
45 import org.junit.Test;
46 import org.onap.policy.api.main.exception.PolicyApiException;
47 import org.onap.policy.api.main.startstop.Main;
48 import org.onap.policy.common.utils.network.NetworkUtil;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * Class to perform unit test of API statistics via https set on API REST server.
54  */
55 public class TestHttpsStatisticApiRestServer {
56
57     private static final Logger LOGGER = LoggerFactory.getLogger(TestHttpsStatisticApiRestServer.class);
58     private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
59
60     @Test
61     public void testHttpsApiStatistic()
62         throws PolicyApiException, InterruptedException, KeyManagementException, NoSuchAlgorithmException {
63         final String reportString = "StatisticsReport [code=200, totalApiCallCount=0, apiCallSuccessCount=0, "
64             + "apiCallFailureCount=0, " + "totalPolicyGetCount=0, totalPolicyPostCount=0, " 
65             + "totalTemplateGetCount=0, totalTemplatePostCount=0, " 
66             + "policyGetSuccessCount=0, policyGetFailureCount=0, " 
67             + "policyPostSuccessCount=0, policyPostFailureCount=0, " 
68             + "templateGetSuccessCount=0, templateGetFailureCount=0, " 
69             + "templatePostSuccessCount=0, templatePostFailureCount=0]";
70         try {
71             final Main main = startApiService();
72             final StatisticsReport report = performStatisticCheck();
73             validateReport(200, 0, reportString, report);
74             stopApiService(main);
75         } catch (final Exception exp) {
76             LOGGER.error("testHttpsApiStatistic failed", exp);
77             fail("Test should not throw an exception");
78         }
79     }
80
81     private Main startApiService() {
82         final Properties systemProps = System.getProperties();
83         systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
84         systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
85         System.setProperties(systemProps);
86
87         final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_Https.json" };
88         return new Main(apiConfigParameters);
89     }
90
91     private void stopApiService(final Main main) throws PolicyApiException {
92         main.shutdown();
93     }
94
95     private StatisticsReport performStatisticCheck() throws Exception {
96
97         final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() {
98
99             @Override
100             public X509Certificate[] getAcceptedIssuers() {
101                 return new X509Certificate[0];
102             }
103
104             @Override
105             public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
106             }
107
108             @Override
109             public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
110             }
111         } };
112
113         final SSLContext sc = SSLContext.getInstance("TLSv1.2");
114         sc.init(null, noopTrustManager, new SecureRandom());
115         final ClientBuilder clientBuilder = 
116                 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
117         final Client client = clientBuilder.build();
118         final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
119         client.register(feature);
120
121         final WebTarget webTarget = client.target("https://localhost:6969/statistics");
122
123         final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
124         
125         if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
126             throw new IllegalStateException("cannot connect to port 6969");
127         }
128         return invocationBuilder.get(StatisticsReport.class);
129     }
130
131     private void validateReport(final int code, final int count, 
132             final String reportString, final StatisticsReport report) {
133         assertEquals(code, report.getCode());
134         assertEquals(count, report.getTotalApiCallCount());
135         assertEquals(count, report.getApiCallSuccessCount());
136         assertEquals(count, report.getApiCallFailureCount());
137         assertEquals(count, report.getTotalPolicyGetCount());
138         assertEquals(count, report.getTotalPolicyPostCount());
139         assertEquals(count, report.getTotalTemplateGetCount());
140         assertEquals(count, report.getTotalTemplatePostCount());
141         assertEquals(count, report.getPolicyGetSuccessCount());
142         assertEquals(count, report.getPolicyGetFailureCount());
143         assertEquals(count, report.getPolicyPostSuccessCount());
144         assertEquals(count, report.getPolicyPostFailureCount());
145         assertEquals(count, report.getTemplateGetSuccessCount());
146         assertEquals(count, report.getTemplateGetFailureCount());
147         assertEquals(count, report.getTemplatePostSuccessCount());
148         assertEquals(count, report.getTemplatePostFailureCount());
149         assertEquals(reportString, report.toString());
150     }
151 }