09dec4389ab7367bdd0d4e61ba1b5a4eff010ff6
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.bpmn.infrastructure.workflow.serviceTask;
22
23 import com.fasterxml.jackson.annotation.JsonInclude;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.http.client.ClientProtocolException;
28 import org.apache.http.client.methods.CloseableHttpResponse;
29 import org.apache.http.client.methods.HttpGet;
30 import org.apache.http.client.methods.HttpPost;
31 import org.apache.http.entity.ContentType;
32 import org.apache.http.entity.StringEntity;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.apache.http.impl.client.HttpClients;
35 import org.apache.http.util.EntityUtils;
36 import org.camunda.bpm.engine.delegate.DelegateExecution;
37 import org.json.JSONObject;
38 import org.onap.msb.sdk.discovery.common.RouteException;
39 import org.onap.msb.sdk.httpclient.RestServiceCreater;
40 import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;
41 import org.openecomp.mso.bpmn.core.BaseTask;
42 import org.openecomp.mso.bpmn.core.PropertyConfiguration;
43 import org.openecomp.mso.bpmn.infrastructure.workflow.serviceTask.client.GenericResourceApi;
44 import org.openecomp.mso.logger.MessageEnum;
45 import org.openecomp.mso.logger.MsoLogger;
46 import org.openecomp.mso.requestsdb.RequestsDatabase;
47 import org.openecomp.mso.requestsdb.ResourceOperationStatus;
48
49 import java.io.IOException;
50 import java.util.HashMap;
51 import java.util.Map;
52
53 /**
54  * Created by 10112215 on 2017/9/16.
55  */
56 public abstract class AbstractSdncOperationTask extends BaseTask {
57
58     private static final String DEFAULT_MSB_IP = "127.0.0.1";
59     private static final int DEFAULT_MSB_Port = 80;
60     private static final String SDCADAPTOR_INPUTS = "resourceParameters";
61     public static final String ONAP_IP = "ONAP_IP";
62     private RequestsDatabase requestsDB = RequestsDatabase.getInstance();
63
64     private static final String postBodyTemplate = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://org.openecomp.mso/requestsdb\"><soapenv:Header/><soapenv:Body>\n"+
65             "     <ns:updateResourceOperationStatus>\n"+
66             "                <errorCode>$errorCode</errorCode>\n"+
67             "                <jobId>$jobId</jobId>\n"+
68             "                <operType>$operType</operType>\n"+
69             "                <operationId>$operationId</operationId>\n"+
70             "                <progress>$progress</progress>\n"+
71             "                <resourceTemplateUUID>$resourceTemplateUUID</resourceTemplateUUID>\n"+
72             "                <serviceId>$serviceId</serviceId>\n"+
73             "                <status>$status</status>\n"+
74             "                <statusDescription>$statusDescription</statusDescription>\n"+
75             "     </ns:updateResourceOperationStatus></soapenv:Body></soapenv:Envelope>";
76
77
78     private void updateResOperStatus(ResourceOperationStatus resourceOperationStatus) throws RouteException {
79         String url = "http://mso:8080/dbadapters/RequestsDbAdapter";
80         HttpPost httpPost = new HttpPost(url);
81         httpPost.addHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
82         httpPost.addHeader("Content-type", "application/soap+xml");
83         String postBody = getStringBody(resourceOperationStatus);
84         httpPost.setEntity(new StringEntity(postBody, ContentType.APPLICATION_XML));
85         httpPost(url, httpPost);
86
87         //requestsDB.updateResOperStatus(resourceOperationStatus);
88     }
89
90     protected String getPostbody(Object inputEntity) {
91         ObjectMapper objectMapper = new ObjectMapper();
92         String postBody = null;
93         try {
94             objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
95             postBody = objectMapper.writeValueAsString(inputEntity);
96         } catch (JsonProcessingException e) {
97             e.printStackTrace();
98         }
99         return postBody;
100     }
101
102     protected void httpPost(String url, HttpPost httpPost) throws RouteException {
103         CloseableHttpClient httpClient = HttpClients.createDefault();
104         String result;
105         boolean var15 = false;
106
107         String errorMsg;
108         label91: {
109             try {
110                 var15 = true;
111                 CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
112                 result = EntityUtils.toString(closeableHttpResponse.getEntity());
113                 LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, result.toString(), "SDNC", "");
114                 if(closeableHttpResponse.getStatusLine().getStatusCode() != 200) {
115                     throw new RouteException(result, "SERVICE_GET_ERR");
116                 }
117
118                 closeableHttpResponse.close();
119                 var15 = false;
120                 break label91;
121             } catch (IOException var19) {
122                 errorMsg = url + ":httpPostWithJSON connect faild";
123                 throwsRouteException(errorMsg, var19, "POST_CONNECT_FAILD");
124                 var15 = false;
125             } finally {
126                 if(var15) {
127                     try {
128                         httpClient.close();
129                     } catch (IOException var16) {
130                         String errorMsg1 = url + ":close  httpClient faild";
131                         throwsRouteException(errorMsg1, var16, "CLOSE_CONNECT_FAILD");
132                     }
133
134                 }
135             }
136
137             try {
138                 httpClient.close();
139             } catch (IOException var17) {
140                 errorMsg = url + ":close  httpClient faild";
141                 throwsRouteException(errorMsg, var17, "CLOSE_CONNECT_FAILD");
142             }
143         }
144
145         try {
146             httpClient.close();
147         } catch (IOException var18) {
148             errorMsg = url + ":close  httpClient faild";
149             throwsRouteException(errorMsg, var18, "CLOSE_CONNECT_FAILD");
150         }
151     }
152
153     private static void throwsRouteException(String errorMsg, Exception e, String errorCode) throws RouteException {
154         String msg = errorMsg + ".errorMsg:" + e.getMessage();
155         throw new RouteException(errorMsg, errorCode);
156     }
157
158     private String getStringBody(ResourceOperationStatus resourceOperationStatus) {
159         String postBody = new String(postBodyTemplate);
160         postBody.replace("$errorCode", resourceOperationStatus.getErrorCode());
161         postBody.replace("$jobId", resourceOperationStatus.getJobId());
162         postBody.replace("$operType", resourceOperationStatus.getOperType());
163         postBody.replace("$operationId", resourceOperationStatus.getOperationId());
164         postBody.replace("$progress", resourceOperationStatus.getProgress());
165         postBody.replace("$resourceTemplateUUID", resourceOperationStatus.getResourceTemplateUUID());
166         postBody.replace("$serviceId", resourceOperationStatus.getServiceId());
167         postBody.replace("$status", resourceOperationStatus.getStatus());
168         postBody.replace("$statusDescription", resourceOperationStatus.getStatusDescription());
169         return postBody;
170     }
171
172     private ResourceOperationStatus getResourceOperationStatus(String serviceId, String operationId, String resourceTemplateUUID) throws RouteException {
173         String url = "http://mso:8080/dbadapters/RequestsDbAdapter";
174         HttpGet httpGet = new HttpGet(url);
175         httpGet.setHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
176         httpGet.setHeader("Content-type", "application/soap+xml");
177         String result = httpGet(url, httpGet);
178         ResourceOperationStatus resourceOperationStatus = getResourceOperationStatusFromXmlString(result);
179
180         return resourceOperationStatus;
181
182         //return requestsDB.getResourceOperationStatus(serviceId, operationId, resourceTemplateUUID);
183     }
184
185     private String httpGet(String url, HttpGet httpGet) throws RouteException {
186         boolean var16 = false;
187         CloseableHttpClient httpClient = HttpClients.createDefault();
188         String result="";
189         String errorMsg;
190         label109: {
191             label110: {
192                 try {
193                     var16 = true;
194                     CloseableHttpResponse e = httpClient.execute(httpGet);
195                     result = EntityUtils.toString(e.getEntity());
196                     if(e.getStatusLine().getStatusCode() != 200) {
197                         throw new RouteException(result, "SERVICE_GET_ERR");
198                     }
199
200                     e.close();
201                     var16 = false;
202                     break label110;
203                 } catch (ClientProtocolException var21) {
204                     errorMsg = url + ":httpGetWithJSON connect faild";
205                     throwsRouteException(errorMsg, var21, "GET_CONNECT_FAILD");
206                     var16 = false;
207                 } catch (IOException var22) {
208                     errorMsg = url + ":httpGetWithJSON connect faild";
209                     throwsRouteException(errorMsg, var22, "GET_CONNECT_FAILD");
210                     var16 = false;
211                     break label109;
212                 } finally {
213                     if(var16) {
214                         try {
215                             httpClient.close();
216                         } catch (IOException var17) {
217                             String errorMsg1 = url + ":close  httpClient faild";
218                             throwsRouteException(errorMsg1, var17, "CLOSE_CONNECT_FAILD");
219                         }
220
221                     }
222                 }
223
224                 try {
225                     httpClient.close();
226                 } catch (IOException var19) {
227                     errorMsg = url + ":close  httpClient faild";
228                     throwsRouteException(errorMsg, var19, "CLOSE_CONNECT_FAILD");
229                 }
230
231             }
232
233             try {
234                 httpClient.close();
235             } catch (IOException var20) {
236                 errorMsg = url + ":close  httpClient faild";
237                 throwsRouteException(errorMsg, var20, "CLOSE_CONNECT_FAILD");
238             }
239
240         }
241
242         try {
243             httpClient.close();
244         } catch (IOException var18) {
245             errorMsg = url + ":close  httpClient faild";
246             throwsRouteException(errorMsg, var18, "CLOSE_CONNECT_FAILD");
247         }
248         return result;
249     }
250
251     private ResourceOperationStatus getResourceOperationStatusFromXmlString(String result) {
252         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus();
253         resourceOperationStatus.setErrorCode(getValueByName("errorCode", result));
254         resourceOperationStatus.setJobId(getValueByName("jobId", result));
255         resourceOperationStatus.setOperType(getValueByName("operType", result));
256         resourceOperationStatus.setOperationId(getValueByName("operationId", result));
257         resourceOperationStatus.setProgress(getValueByName("progress", result));
258         resourceOperationStatus.setResourceTemplateUUID(getValueByName("resourceTemplateUUID", result));
259         resourceOperationStatus.setServiceId(getValueByName("serviceId", result));
260         resourceOperationStatus.setStatus(getValueByName("status", result));
261         resourceOperationStatus.setStatusDescription(getValueByName("statusDescription", result));
262         return resourceOperationStatus;
263     }
264
265     private String getValueByName(String Name, String xml) {
266         String start = "<" + Name + ">";
267         String end = "</" + Name + ">";
268         return xml.substring(xml.indexOf(start), xml.indexOf(end)).replace(start, "");
269     }
270
271     protected static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
272
273     @Override
274     public void execute(DelegateExecution execution) {
275         GenericResourceApi genericResourceApiClient = getGenericResourceApiClient(execution);
276 //        updateProgress(execution, RequestsDbConstant.Status.PROCESSING, null, "10", "execute begin!");
277         Map<String, String> inputs = getInputs(execution);
278 //        updateProgress(execution, null, null, "30", "getGenericResourceApiClient finished!");
279         try {
280             sendRestrequestAndHandleResponse(execution, inputs, genericResourceApiClient);
281             execution.setVariable("SDNCA_SuccessIndicator", true);
282 //            updateProgress(execution, RequestsDbConstant.Status.FINISHED, null, RequestsDbConstant.Progress.ONE_HUNDRED, "execute finished!");
283         } catch (Exception e) {
284             e.printStackTrace();
285             execution.setVariable("SDNCA_SuccessIndicator", false);
286         }
287     }
288
289     protected Map<String, String> getInputs(DelegateExecution execution) {
290         Map<String, String> inputs = new HashMap<>();
291         String json = (String) execution.getVariable(SDCADAPTOR_INPUTS);
292         JSONObject jsonObject = new JSONObject(json);
293         JSONObject paras = jsonObject.getJSONObject("additionalParamForNs");
294
295         while (paras.keys().hasNext()) {
296             String key = paras.keys().next();
297             inputs.put(key, paras.getString(key));
298         }
299 /*        if (paras.keys().hasNext()) {
300             paras.keySet().stream().forEach(key -> inputs.put(key, paras.getString((String) key)));
301         }*/
302         return inputs;
303     }
304
305     public abstract void sendRestrequestAndHandleResponse(DelegateExecution execution,
306                                                           Map<String, String> inputs,
307                                                           GenericResourceApi genericResourceApiClient) throws Exception;
308
309     public void updateProgress(DelegateExecution execution,
310                                String status,
311                                String errorCode,
312                                String progress,
313                                String statusDescription) {
314         String serviceId = (String) execution.getVariable("serviceId");
315         String operationId = (String) execution.getVariable("operationId");
316         String resourceTemplateUUID = (String) execution.getVariable("resourceUUID");
317         try {
318             ResourceOperationStatus resourceOperationStatus = getResourceOperationStatus(serviceId, operationId, resourceTemplateUUID);
319             if (!StringUtils.isBlank(status)) {
320                 resourceOperationStatus.setStatus(status);
321             }
322             if (!StringUtils.isBlank(errorCode)) {
323                 resourceOperationStatus.setErrorCode(errorCode);
324             }
325             if (!StringUtils.isBlank(progress)) {
326                 resourceOperationStatus.setProgress(progress);
327             }
328             if (!StringUtils.isBlank(statusDescription)) {
329                 resourceOperationStatus.setStatusDescription(statusDescription);
330             }
331             updateResOperStatus(resourceOperationStatus);
332         } catch (Exception exception) {
333             System.out.println(exception);
334             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " updateProgress catch exception: ", "", this.getTaskName(), MsoLogger.ErrorCode.UnknownError, exception.getClass().toString());
335         }
336     }
337
338
339     protected boolean isSend2SdncDirectly() {
340         Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("topology.properties");
341         if (properties != null) {
342             String sdncIp = properties.get("sdnc-ip");
343             String sdncPort = properties.get("sdnc-port");
344             if (!StringUtils.isBlank(sdncIp) && isIp(sdncIp) && !StringUtils.isBlank(sdncPort)) {
345                 return true;
346             }
347         }
348         return false;
349     }
350
351     protected String getSdncIp() {
352         String sdncIp = null;
353         Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("topology.properties");
354         if (properties != null) {
355             sdncIp = properties.get("sdnc-ip");
356         }
357         return StringUtils.isBlank(sdncIp) || !isIp(sdncIp) ? null : sdncIp;
358     }
359
360     protected String getSdncPort() {
361         String sdncIp = null;
362         Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("topology.properties");
363         if (properties != null) {
364             sdncIp = properties.get("sdnc-port");
365         }
366         return StringUtils.isBlank(sdncIp) ? null : sdncIp;
367     }
368
369     private GenericResourceApi getGenericResourceApiClient(DelegateExecution execution) {
370 //        updateProgress(execution, null, null, "20", "getGenericResourceApiClient begin!");
371         String msbIp = System.getenv().get(ONAP_IP);
372         int msbPort = DEFAULT_MSB_Port;
373         Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("topology.properties");
374         if (properties != null) {
375             if (StringUtils.isBlank(msbIp) || !isIp(msbIp)) {
376                 msbIp = properties.get("msb-ip");
377                 if (StringUtils.isBlank(msbIp)) {
378                     msbIp = getString(properties, "msb.address", DEFAULT_MSB_IP);
379                 }
380             }
381             String strMsbPort = properties.get("msb-port");
382             if (StringUtils.isBlank(strMsbPort)) {
383                 strMsbPort = getString(properties, "msb.port", String.valueOf(DEFAULT_MSB_Port));
384             }
385             msbPort = Integer.valueOf(strMsbPort);
386         }
387         MSBServiceClient msbClient = new MSBServiceClient(msbIp, msbPort);
388         RestServiceCreater restServiceCreater = new RestServiceCreater(msbClient);
389         return restServiceCreater.createService(GenericResourceApi.class);
390     }
391
392     protected boolean isIp(String msbIp) {
393         return !StringUtils.isBlank(msbIp) && msbIp.split("\\.").length == 4;
394     }
395
396     private String getString(Map<String, String> properties, String name, String defaultValue) {
397         String vlaue = properties.get(name);
398         try {
399             if (!StringUtils.isBlank(vlaue)) {
400                 return vlaue;
401             }
402         } catch (Exception e) {
403             System.out.println(e);
404             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " getMsbIp catch exception: ", "", this.getTaskName(), MsoLogger.ErrorCode.UnknownError, e.getClass().toString());
405         }
406         return defaultValue;
407     }
408
409     private Integer getInteger(DelegateExecution execution, String name, Integer defaultValue) {
410         Integer vlaue = (Integer) execution.getVariable(name);
411         try {
412             if (vlaue != null) {
413                 return vlaue;
414             }
415         } catch (Exception e) {
416             System.out.println(e);
417             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " getMsbIp catch exception: ", "", this.getTaskName(), MsoLogger.ErrorCode.UnknownError, e.getClass().toString());
418         }
419         return defaultValue;
420     }
421
422     public String getProcessKey(DelegateExecution execution) {
423         return execution.getProcessEngineServices().getRepositoryService().getProcessDefinition(execution.getProcessDefinitionId()).getKey();
424     }
425 }