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