[RECV-94] Separate docker/robot invoking
[validation.git] / ui / src / main / java / org / akraino / validation / ui / client / nexus / NexusExecutorClient.java
1 /*
2  * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may
5  * not use this file except in compliance with the License. You may obtain
6  * a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13  * implied. See the License for the specific language governing
14  * permissions and limitations under the License.
15  */
16 package org.akraino.validation.ui.client.nexus;
17
18 import java.io.IOException;
19 import java.net.HttpURLConnection;
20 import java.net.InetSocketAddress;
21 import java.net.Proxy;
22 import java.net.URL;
23 import java.security.KeyManagementException;
24 import java.security.NoSuchAlgorithmException;
25 import java.security.cert.X509Certificate;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.net.ssl.HostnameVerifier;
31 import javax.net.ssl.HttpsURLConnection;
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.SSLSession;
34 import javax.net.ssl.TrustManager;
35 import javax.net.ssl.X509TrustManager;
36
37 import org.akraino.validation.ui.client.nexus.resources.RobotTestResult;
38 import org.akraino.validation.ui.client.nexus.resources.WrapperRobotTestResult;
39 import org.akraino.validation.ui.data.BlueprintLayer;
40 import org.apache.commons.httpclient.HttpException;
41 import org.json.JSONObject;
42 import org.json.XML;
43 import org.jsoup.Jsoup;
44 import org.jsoup.nodes.Document;
45 import org.jsoup.nodes.Element;
46 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
47
48 import com.fasterxml.jackson.core.JsonParseException;
49 import com.fasterxml.jackson.databind.DeserializationFeature;
50 import com.fasterxml.jackson.databind.JsonMappingException;
51 import com.fasterxml.jackson.databind.ObjectMapper;
52 import com.sun.jersey.api.client.Client;
53 import com.sun.jersey.api.client.ClientHandlerException;
54 import com.sun.jersey.api.client.ClientResponse;
55 import com.sun.jersey.api.client.UniformInterfaceException;
56 import com.sun.jersey.api.client.WebResource;
57 import com.sun.jersey.api.client.config.ClientConfig;
58 import com.sun.jersey.api.client.config.DefaultClientConfig;
59 import com.sun.jersey.api.json.JSONConfiguration;
60 import com.sun.jersey.client.urlconnection.HTTPSProperties;
61 import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory;
62 import com.sun.jersey.client.urlconnection.URLConnectionClientHandler;
63
64 public final class NexusExecutorClient {
65
66     private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(NexusExecutorClient.class);
67
68     private final Client client;
69     private final String baseurl;
70     private final HostnameVerifier hostnameVerifier;
71     private final TrustManager[] trustAll;
72
73     public NexusExecutorClient(String newBaseurl) {
74         this.baseurl = newBaseurl;
75         ClientConfig clientConfig = new DefaultClientConfig();
76         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
77         this.client = new Client(new URLConnectionClientHandler(new HttpURLConnectionFactory() {
78             Proxy proxy = null;
79
80             @Override
81             public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
82                 try {
83                     String proxyIp =
84                             System.getenv("NEXUS_PROXY").substring(0, System.getenv("NEXUS_PROXY").lastIndexOf(":"));
85                     String proxyPort =
86                             System.getenv("NEXUS_PROXY").substring(System.getenv("NEXUS_PROXY").lastIndexOf(":") + 1);
87                     proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, Integer.parseInt(proxyPort)));
88                     return (HttpURLConnection) url.openConnection(proxy);
89                 } catch (Exception ex) {
90                     return (HttpURLConnection) url.openConnection();
91                 }
92             }
93         }), clientConfig);
94         // Create all-trusting host name verifier
95         hostnameVerifier = new HostnameVerifier() {
96             @Override
97             public boolean verify(String hostname, SSLSession session) {
98                 return true;
99             }
100         };
101         // Create a trust manager that does not validate certificate chains
102         trustAll = new TrustManager[] {new X509TrustManager() {
103             @Override
104             public X509Certificate[] getAcceptedIssuers() {
105                 return null; // Not relevant.
106             }
107
108             @Override
109             public void checkClientTrusted(X509Certificate[] certs, String authType) {
110                 // Do nothing. Just allow them all.
111             }
112
113             @Override
114             public void checkServerTrusted(X509Certificate[] certs, String authType) {
115                 // Do nothing. Just allow them all.
116             }
117         }};
118     }
119
120     public String getBaseUrl() {
121         return this.baseurl;
122     }
123
124     public List<WrapperRobotTestResult> getRobotTestResults() throws ClientHandlerException, UniformInterfaceException,
125             JsonParseException, JsonMappingException, IOException, KeyManagementException, NoSuchAlgorithmException {
126         List<WrapperRobotTestResult> listOfwrappers = new ArrayList<WrapperRobotTestResult>();
127         LOGGER.info(EELFLoggerDelegate.applicationLogger, "Trying to get the blueprint layers");
128         setProperties();
129         WebResource webResource = this.client.resource(this.baseurl + "/");
130         LOGGER.debug(EELFLoggerDelegate.debugLogger, "Request URI of get: " + webResource.getURI().toString());
131         ClientResponse response = webResource.get(ClientResponse.class);
132         if (response.getStatus() != 200) {
133             throw new HttpException("Could not retrieve blueprint layers from Nexus. HTTP error code : "
134                     + response.getStatus() + " and message: " + response.getEntity(String.class));
135         }
136         Document document = Jsoup.parse(response.getEntity(String.class));
137         List<Element> elements =
138                 document.getElementsByTag("body").get(0).getElementsByTag("table").get(0).getElementsByTag("tr");
139         for (int i = 2; i < elements.size(); i++) {
140             String layer = elements.get(i).getElementsByTag("td").get(0).getElementsByTag("a").get(0).text();
141             layer = layer.substring(0, layer.length() - 1);
142             List<RobotTestResult> robotTestResults = getResultsOfALayer(this.baseurl + "/" + layer);
143             WrapperRobotTestResult wrapper = new WrapperRobotTestResult();
144             wrapper.setBlueprintLayer(BlueprintLayer.valueOf(layer.substring(0, 1).toUpperCase() + layer.substring(1)));
145             wrapper.setRobotTestResults(robotTestResults);
146             listOfwrappers.add(wrapper);
147         }
148         return listOfwrappers;
149     }
150
151     private List<RobotTestResult> getResultsOfALayer(String resultsUrl)
152             throws ClientHandlerException, UniformInterfaceException, JsonParseException, JsonMappingException,
153             IOException, KeyManagementException, NoSuchAlgorithmException {
154         List<RobotTestResult> robotTestResults = new ArrayList<RobotTestResult>();
155         LOGGER.info(EELFLoggerDelegate.applicationLogger, "Trying to get Robot Test Results");
156         setProperties();
157         WebResource webResource = this.client.resource(resultsUrl + "/");
158         LOGGER.debug(EELFLoggerDelegate.debugLogger, "Request URI of get: " + webResource.getURI().toString());
159         ClientResponse response = webResource.get(ClientResponse.class);
160         if (response.getStatus() != 200) {
161             throw new HttpException("Could not retrieve robot test results from Nexus. HTTP error code : "
162                     + response.getStatus() + " and message: " + response.getEntity(String.class));
163         }
164         Document document = Jsoup.parse(response.getEntity(String.class));
165         List<Element> elements = document.getElementsByTag("body").get(0).getElementsByTag("table").get(0)
166                 .getElementsByTag("tbody").get(0).getElementsByTag("tr");
167         for (int i = 2; i < elements.size(); i++) {
168             String testSuiteName = elements.get(i).getElementsByTag("td").get(0).getElementsByTag("a").get(0).text();
169             testSuiteName = testSuiteName.substring(0, testSuiteName.length() - 1);
170             webResource = this.client.resource(resultsUrl + "/" + testSuiteName + "/output.xml");
171             LOGGER.debug(EELFLoggerDelegate.debugLogger, "Request URI of get: " + webResource.getURI().toString());
172             response = webResource.get(ClientResponse.class);
173             if (response.getStatus() != 200) {
174                 throw new HttpException("Could not retrieve robot test result from Nexus. HTTP error code : "
175                         + response.getStatus() + " and message: " + response.getEntity(String.class));
176             }
177             String result = response.getEntity(String.class);
178             JSONObject xmlJSONObj = XML.toJSONObject(result);
179             ObjectMapper mapper = new ObjectMapper();
180             mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
181             RobotTestResult robotTestResult = mapper.readValue(xmlJSONObj.toString(), RobotTestResult.class);
182             robotTestResult.setName(testSuiteName);
183             robotTestResults.add(robotTestResult);
184         }
185         return robotTestResults;
186     }
187
188     private void setProperties() throws NoSuchAlgorithmException, KeyManagementException {
189         SSLContext sslContext = SSLContext.getInstance("SSL");
190         sslContext.init(null, this.trustAll, new java.security.SecureRandom());
191         HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
192         // Install the all-trusting host verifier
193         HttpsURLConnection.setDefaultHostnameVerifier(this.hostnameVerifier);
194         DefaultClientConfig config = new DefaultClientConfig();
195         Map<String, Object> properties = config.getProperties();
196         HTTPSProperties httpsProperties = new HTTPSProperties((str, sslSession) -> true, sslContext);
197         properties.put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, httpsProperties);
198     }
199
200 }