Code Improvements-Vnfsdk-refrepo sonar issue fixes
[vnfsdk/refrepo.git] / vnfmarket-be / vnf-sdk-marketplace / src / main / java / org / onap / vnfsdk / marketplace / onboarding / hooks / validatelifecycle / LifecycleTestExceutor.java
1 /**
2  * Copyright 2017-2018 Huawei Technologies Co., Ltd.
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  */
16 package org.onap.vnfsdk.marketplace.onboarding.hooks.validatelifecycle;
17
18 import java.io.File;
19 import java.util.Map;
20
21 import org.apache.http.entity.ContentType;
22 import org.apache.http.entity.mime.MultipartEntityBuilder;
23 import org.onap.vnfsdk.marketplace.common.CommonConstant;
24 import org.onap.vnfsdk.marketplace.common.FileUtil;
25 import org.onap.vnfsdk.marketplace.msb.MsbDetails;
26 import org.onap.vnfsdk.marketplace.msb.MsbDetailsHolder;
27 import org.onap.vnfsdk.marketplace.onboarding.entity.OnBoradingRequest;
28 import org.onap.vnfsdk.marketplace.rest.RestConstant;
29 import org.onap.vnfsdk.marketplace.rest.RestResponse;
30 import org.onap.vnfsdk.marketplace.rest.RestfulClient;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import com.google.gson.Gson;
35 import com.google.gson.reflect.TypeToken;
36
37
38 /** CALL Flow: onBoardingHandler --> LifecycleTestHook--> LifecycleTestExecutor */
39 public class LifecycleTestExceutor {
40         private static final Logger logger = LoggerFactory.getLogger(LifecycleTestExceutor.class);
41         private static Gson gson = new Gson();
42         public static final String CATALOUGE_UPLOAD_URL_IN = "{0}:{1}/onapapi/catalog/v1/csars";
43
44         private LifecycleTestExceutor() {
45                 // Empty constructor
46         }
47
48         /**
49          * Interface to upload package to catalogue
50          * 
51          * @param onBoradFuncTestReq
52          * @return- csarId or null (in case of failure)
53          */
54         @SuppressWarnings("unchecked")
55         public static String uploadPackageToCatalouge(OnBoradingRequest onBoradFuncTestReq) {
56                 String packagePath = onBoradFuncTestReq.getPackagePath() + File.separator + onBoradFuncTestReq.getPackageName();
57                 logger.info("Package file path uploadPackageToCatalouge:{}" , packagePath);
58
59                 String catalougeCsarId = null;
60
61                 // Validate package path
62                 if (!FileUtil.validatePath(packagePath)) {
63                         logger.error("Failed to validate  package path");
64                         return catalougeCsarId;
65                 }
66
67                 MsbDetails oMsbDetails = MsbDetailsHolder.getMsbDetails();
68                 if (null == oMsbDetails) {
69                         logger.error("Failed to get MSB details during uploadPackageToCatalouge !!!");
70                         return catalougeCsarId;
71                 }
72
73                 File fileData = new File(packagePath);
74
75                 // Validate file
76                 if (!FileUtil.validateFile(fileData)) {
77                         logger.error("Failed to validate file information");
78                         return catalougeCsarId;
79                 }
80
81                 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
82                 builder.addBinaryBody("file", fileData, ContentType.MULTIPART_FORM_DATA, onBoradFuncTestReq.getPackageName());
83
84                 // IP and Port needs to be configured !!!
85                 RestResponse rsp = RestfulClient.post(oMsbDetails.getDefaultServer().getHost(),
86                                 Integer.parseInt(oMsbDetails.getDefaultServer().getPort()), CommonConstant.CATALOUGE_UPLOAD_URL,
87                                 builder.build());
88                 if (!checkValidResponse(rsp)) {
89                         logger.error("Failed to upload package to catalouge:{}" , rsp.getStatusCode());
90                         return catalougeCsarId;
91                 }
92
93                 logger.info("Response for uploadPackageToCatalouge :{}" , rsp.getResult());
94                 catalougeCsarId = getCsarIdValue(rsp.getResult());
95
96                 logger.info("CSARID for uploadPackageToCatalouge :{}" , catalougeCsarId);
97                 return catalougeCsarId;
98         }
99
100         /**
101          * Interface to execute lifecycle test
102          * 
103          * @param onBoradFuncTestReq,
104          *            oLifeCycleTestReq
105          * @return result of the test or null (in case of failure)
106          */
107         public static String execlifecycleTest(OnBoradingRequest onBoradFuncTestReq, LifeCycleTestReq oLifeCycleTestReq) { //NOSONAR
108
109                 String result = null;
110                 if ((null == onBoradFuncTestReq.getPackagePath()) || (null == onBoradFuncTestReq.getPackageName())) {
111                         logger.error("Package path or name is invalid");
112                         return result;
113                 }
114
115                 String packagePath = onBoradFuncTestReq.getPackagePath() + File.separator + onBoradFuncTestReq.getPackageName();
116                 logger.info("Package file path Function test:{}" , packagePath);
117
118                 // Validate package path
119                 if (!FileUtil.validatePath(packagePath)) {
120                         logger.error("Failed to validate  path");
121                         return result;
122                 }
123
124                 MsbDetails oMsbDetails = MsbDetailsHolder.getMsbDetails();
125                 if (null == oMsbDetails) {
126                         logger.error("Failed to get MSB details during execlifecycleTest !!!");
127                         return result;
128                 }
129
130                 String rawDataJson = "";
131                 //TBD - Use Gson - jackson has security issue//JsonUtil.toJson(oLifeCycleTestReq);
132
133                 RestResponse oResponse = RestfulClient.sendPostRequest(oMsbDetails.getDefaultServer().getHost(),
134                                 oMsbDetails.getDefaultServer().getPort(), CommonConstant.LifeCycleTest.LIFECYCLE_TEST_URL, rawDataJson);
135
136                 if (!checkValidResponse(oResponse)) {
137                         logger.error("execlifecycleTest response is faliure :{}" , oResponse.getStatusCode());
138                         return result;
139                 }
140
141                 result = oResponse.getResult();
142                 logger.info("Response execlifecycleTest :{}" , oResponse.getResult());
143                 return result;
144         }
145
146         /**
147          * Check Response is Valid
148          * 
149          * @param rsp
150          * @return valid(true) or invalid(false)
151          */
152         private static boolean checkValidResponse(RestResponse rsp) {
153                 return ((null != rsp.getStatusCode()) && (null != rsp.getResult())
154                                 && (RestConstant.RESPONSE_CODE_200 == rsp.getStatusCode()
155                                 || RestConstant.RESPONSE_CODE_201 == rsp.getStatusCode()));
156         }
157
158         /**
159          * Get csar Id value
160          *
161          * @param strJsonData
162          * @return empty(failure), or csarId(success)
163          */
164         private static String getCsarIdValue(String strJsonData) {
165                 /*
166            Gson will ignore the unknown fields and simply match the fields that it's able to.
167            ref: https://www.baeldung.com/gson-deserialization-guide
168            By default, Gson just ignores extra JSON elements that do not have matching Java fields.
169            ref: https://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html
170         */
171                 Map<String, String> dataMap = null;
172
173                 try {
174                         dataMap = gson.fromJson(strJsonData, new TypeToken<Map<String,String>>(){}.getType());
175                 } catch (Exception e) { //NOSONAR
176                         logger.error("Exception:Failed to upload package to catalouge:", e);
177                 }
178                 try {
179                         if (null != dataMap) {
180                                 return dataMap.get("csarId");
181                         }
182                 } catch (NullPointerException e) {
183                         logger.error("NullPointerException:Failed to get csarId", e);
184                 }
185                 return "";
186         }
187 }