Unique identifier for test execution
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / externaltesting-rest / externaltesting-rest-services / src / main / java / org / openecomp / sdcrests / externaltesting / rest / services / ExternalTestingImpl.java
1 /*
2  * Copyright © 2019 iconectiv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain 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 implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  * ============LICENSE_END=========================================================
16  * Modifications copyright (c) 2019 Nokia
17  * ================================================================================
18  */
19
20 package org.openecomp.sdcrests.externaltesting.rest.services;
21
22 import com.fasterxml.jackson.core.type.TypeReference;
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.stream.Collectors;
30 import javax.inject.Named;
31 import javax.ws.rs.core.Response;
32 import org.apache.commons.io.IOUtils;
33 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
34 import org.openecomp.core.externaltesting.api.ClientConfiguration;
35 import org.openecomp.core.externaltesting.api.ExternalTestingManager;
36 import org.openecomp.core.externaltesting.api.RemoteTestingEndpointDefinition;
37 import org.openecomp.core.externaltesting.api.TestErrorBody;
38 import org.openecomp.core.externaltesting.api.VtpTestExecutionOutput;
39 import org.openecomp.core.externaltesting.api.VtpTestExecutionRequest;
40 import org.openecomp.core.externaltesting.api.VtpTestExecutionResponse;
41 import org.openecomp.core.externaltesting.errors.ExternalTestingException;
42 import org.openecomp.sdc.logging.api.Logger;
43 import org.openecomp.sdc.logging.api.LoggerFactory;
44 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
45 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
46 import org.openecomp.sdcrests.externaltesting.rest.ExternalTesting;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.context.annotation.Scope;
49 import org.springframework.http.HttpStatus;
50 import org.springframework.stereotype.Service;
51
52 @SuppressWarnings("unused")
53 @Named
54 @Service("externaltesting")
55 @Scope(value = "prototype")
56 public class ExternalTestingImpl implements ExternalTesting {
57
58     private final ExternalTestingManager testingManager;
59     private static final int REQUEST_ID_LENGTH = 8;
60     private static final String TESTING_INTERNAL_ERROR = "SDC-TEST-005";
61     private final VendorSoftwareProductManager vendorSoftwareProductManager =
62             VspManagerFactory.getInstance().createInterface();
63     private static final Logger logger = LoggerFactory.getLogger(ExternalTestingImpl.class);
64
65     public ExternalTestingImpl(@Autowired ExternalTestingManager testingManager) {
66         this.testingManager = testingManager;
67     }
68
69     /**
70      * Return the configuration of the feature to the client.
71      *
72      * @return JSON response content.
73      */
74     @Override
75     public Response getConfig() {
76         try {
77             return Response.ok(testingManager.getConfig()).build();
78         } catch (ExternalTestingException e) {
79             return convertTestingException(e);
80         }
81     }
82
83     /**
84      * To enable automated functional testing, allow
85      * a put for the client configuration.
86      *
87      * @return JSON response content.
88      */
89     @Override
90     public Response setConfig(ClientConfiguration config) {
91         try {
92             return Response.ok(testingManager.setConfig(config)).build();
93         } catch (ExternalTestingException e) {
94             return convertTestingException(e);
95         }
96     }
97
98
99     /**
100      * Return the test tree structure created by the testing manager.
101      *
102      * @return JSON response content.
103      */
104     @Override
105     public Response getTestCasesAsTree() {
106         try {
107             return Response.ok(testingManager.getTestCasesAsTree()).build();
108         } catch (ExternalTestingException e) {
109             return convertTestingException(e);
110         }
111     }
112
113     @Override
114     public Response getEndpoints() {
115         try {
116             return Response.ok(testingManager.getEndpoints()).build();
117         } catch (ExternalTestingException e) {
118             return convertTestingException(e);
119         }
120     }
121
122     /**
123      * To enable automated functional testing, allow a put of the endpoints.
124      *
125      * @return JSON response content.
126      */
127     @Override
128     public Response setEndpoints(List<RemoteTestingEndpointDefinition> endpoints) {
129         try {
130             return Response.ok(testingManager.setEndpoints(endpoints)).build();
131         } catch (ExternalTestingException e) {
132             return convertTestingException(e);
133         }
134     }
135
136     @Override
137     public Response getScenarios(String endpoint) {
138         try {
139             return Response.ok(testingManager.getScenarios(endpoint)).build();
140         } catch (ExternalTestingException e) {
141             return convertTestingException(e);
142         }
143
144     }
145
146     @Override
147     public Response getTestsuites(String endpoint, String scenario) {
148         try {
149             return Response.ok(testingManager.getTestSuites(endpoint, scenario)).build();
150         } catch (ExternalTestingException e) {
151             return convertTestingException(e);
152         }
153     }
154
155     @Override
156     public Response getTestcases(String endpoint, String scenario) {
157         try {
158             return Response.ok(testingManager.getTestCases(endpoint, scenario)).build();
159         } catch (ExternalTestingException e) {
160             return convertTestingException(e);
161         }
162     }
163
164     @Override
165     public Response getTestcase(String endpoint, String scenario, String testsuite, String testcase) {
166         try {
167             return Response.ok(testingManager.getTestCase(endpoint, scenario, testsuite, testcase)).build();
168         } catch (ExternalTestingException e) {
169             return convertTestingException(e);
170         }
171     }
172
173     @Override
174     public Response execute(String vspId, String vspVersionId, String requestId, List<Attachment> files,
175             String testDataString) {
176         try {
177             List<VtpTestExecutionRequest> req = getVtpTestExecutionRequestObj(testDataString);
178             Map<String, byte[]> fileMap = getFileMap(files);
179             List<VtpTestExecutionResponse> vtpTestExecutionResponses =
180                     testingManager.execute(req, vspId, vspVersionId, requestId, fileMap);
181             return Response.status(HttpStatus.OK.value()).entity(vtpTestExecutionResponses).build();
182         } catch (ExternalTestingException e) {
183             return convertTestingException(e);
184         }
185
186     }
187
188     @Override
189     public Response getValidationResult(String requestId, List<String> endPoints) {
190         try {
191             List<VtpTestExecutionResponse> resultsFromVtp = new ArrayList<>();
192             for (String endPoint : endPoints) {
193                 List<VtpTestExecutionOutput> vtpTestExecutionOutput =
194                         testingManager.getExecutionIds(endPoint, requestId);
195                 List<String> execIds = vtpTestExecutionOutput.stream().map(VtpTestExecutionOutput::getExecutionId)
196                                                .collect(Collectors.toList());
197                 List<VtpTestExecutionResponse> resultFromVtp = getVtpResultbyExecutionId(execIds, endPoint);
198                 resultsFromVtp.addAll(resultFromVtp);
199             }
200             return Response.status(HttpStatus.OK.value()).entity(resultsFromVtp).build();
201         } catch (ExternalTestingException e) {
202             return convertTestingException(e);
203         }
204     }
205
206     private List<VtpTestExecutionRequest> getVtpTestExecutionRequestObj(String testDataString) {
207         try {
208             return new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true).reader()
209                            .forType(new TypeReference<List<VtpTestExecutionRequest>>() { }).readValue(testDataString);
210         } catch (IOException e) {
211             throw new ExternalTestingException(TESTING_INTERNAL_ERROR, 500, e.getMessage(), e);
212
213         }
214     }
215
216     private List<VtpTestExecutionResponse> getVtpResultbyExecutionId(List<String> executionIds, String endPoint) {
217         List<VtpTestExecutionResponse> vtpTestExecutionResponses = new ArrayList<>();
218         executionIds.stream().forEach(executionId -> {
219             VtpTestExecutionResponse executionResult = testingManager.getExecution(endPoint, executionId);
220             vtpTestExecutionResponses.add(executionResult);
221         });
222         return vtpTestExecutionResponses;
223     }
224
225
226     @Override
227     public Response getExecution(String endpoint, String executionId) {
228         try {
229             return Response.ok(testingManager.getExecution(endpoint, executionId)).build();
230         } catch (ExternalTestingException e) {
231             return convertTestingException(e);
232         }
233     }
234
235     private Map<String, byte[]> getFileMap(List<Attachment> files) {
236         if (files != null && !files.isEmpty()) {
237
238             return files.stream().collect(
239                     Collectors.toMap(attachment -> attachment.getDataHandler().getName(), attachment -> {
240                         try {
241                             return IOUtils.toByteArray(attachment.getDataHandler().getInputStream());
242                         } catch (IOException e) {
243                             throw new ExternalTestingException(TESTING_INTERNAL_ERROR, 500, e.getMessage(), e);
244                         }
245                     }));
246         }
247
248         return null;
249     }
250
251     private Response convertTestingException(ExternalTestingException e) {
252         if (logger.isErrorEnabled()) {
253             logger.error("testing exception {} {} {}", e.getMessageCode(), e.getHttpStatus(), e.getDetail(), e);
254         }
255         TestErrorBody body = new TestErrorBody(e.getMessageCode(), e.getHttpStatus(), e.getDetail());
256         return Response.status(e.getHttpStatus()).entity(body).build();
257     }
258 }