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