Replaced hardcoded value with constant defined
[appc.git] / appc-adapters / appc-chef-adapter / appc-chef-adapter-bundle / src / main / java / org / onap / appc / adapter / chef / impl / ChefAdapterImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2019 IBM
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24 package org.onap.appc.adapter.chef.impl;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import java.util.Arrays;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import org.apache.commons.lang.StringUtils;
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 import org.onap.appc.adapter.chef.ChefAdapter;
36 import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
37 import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
38 import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
41
42 /**
43  * This class implements the {@link ChefAdapter} interface. This interface
44  * defines the behaviors that our service provides.
45  */
46 public class ChefAdapterImpl implements ChefAdapter {
47
48     // chef server Initialize variable
49     private String username = StringUtils.EMPTY;
50     private String clientPrivatekey = StringUtils.EMPTY;
51     private String chefserver = StringUtils.EMPTY;
52     private String serverAddress = StringUtils.EMPTY;
53     private String organizations = StringUtils.EMPTY;
54
55     @SuppressWarnings("nls")
56     public static final String MDC_ADAPTER = "adapter";
57
58     @SuppressWarnings("nls")
59     public static final String MDC_SERVICE = "service";
60
61     @SuppressWarnings("nls")
62     public static final String OUTCOME_FAILURE = "failure";
63
64     @SuppressWarnings("nls")
65     public static final String OUTCOME_SUCCESS = "success";
66
67     @SuppressWarnings("nls")
68     public static final String PROPERTY_PROVIDER = "provider";
69
70     @SuppressWarnings("nls")
71     public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
72
73     @SuppressWarnings("nls")
74     public static final String PROPERTY_PROVIDER_NAME = "name";
75
76     @SuppressWarnings("nls")
77     public static final String PROPERTY_PROVIDER_TENANT = "tenant";
78
79     @SuppressWarnings("nls")
80     public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
81
82     @SuppressWarnings("nls")
83     public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
84
85     @SuppressWarnings("nls")
86     public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
87
88     @SuppressWarnings("nls")
89     public static final String PROPERTY_PROVIDER_TYPE = "type";
90
91     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
92
93     private static final String CANNOT_FIND_PRIVATE_KEY_STR = "Cannot find the private key in the APPC file system, please load the private key to ";
94
95     private static final String POSTING_REQUEST_JSON_ERROR_STR = "Error posting request due to invalid JSON block: ";
96     private static final String POSTING_REQUEST_ERROR_STR = "Error posting request: ";
97     private static final String CHEF_CLIENT_RESULT_CODE_STR = "chefClientResult.code";
98     private static final String CHEF_SERVER_RESULT_CODE_STR = "chefServerResult.code";
99     private static final String CHEF_CLIENT_RESULT_MSG_STR = "chefClientResult.message";
100     private static final String CHEF_SERVER_RESULT_MSG_STR = "chefServerResult.message";
101     private static final String CHEF_ACTION_STR = "chefAction";
102     private static final String NODE_LIST_STR = "NodeList";
103     private static final Integer STATUS_OK = 200;
104     private static final Integer STATUS_PUSHJOBCHECK = 201;
105     private static final Integer PUSHJOBSTATUS= 202;
106     private static final Integer KEY_NOTFOUND = 500;
107     private static final Integer NO_ENVIRONMENT = 404;
108     private static final Integer APPC_ERRORCODE = 401;
109
110     private final ChefApiClientFactory chefApiClientFactory;
111     private final PrivateKeyChecker privateKeyChecker;
112
113     ChefAdapterImpl(ChefApiClientFactory chefApiClientFactory, PrivateKeyChecker privateKeyChecker) {
114         this.chefApiClientFactory = chefApiClientFactory;
115         this.privateKeyChecker = privateKeyChecker;
116         logger.info("Initialize Chef Adapter");
117     }
118
119     @SuppressWarnings("nls")
120     @Override
121     public void vnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
122         int code;
123         logger.info("environment of VNF-C");
124         chefInfo(params, ctx);
125         String env = params.get("Environment");
126         logger.info("Environmnet" + env);
127         if (env.equals(StringUtils.EMPTY)) {
128             chefServerResult(ctx, STATUS_OK, "Skip Environment block ");
129         } else {
130             String message;
131             if (privateKeyChecker.doesExist(clientPrivatekey)) {
132                 try {
133                     JSONObject envJ = new JSONObject(env);
134                     String envName = envJ.getString("name");
135                     // update the details of an environment on the Chef server.
136                     ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
137                             clientPrivatekey);
138                     ChefResponse chefResponse = chefApiClient.put("/environments/" + envName, env);
139                     code = chefResponse.getStatusCode();
140                     message = chefResponse.getBody();
141                     if (code == NO_ENVIRONMENT) {
142                         // need create a new environment
143                         chefResponse = chefApiClient.post("/environments", env);
144                         code = chefResponse.getStatusCode();
145                         message = chefResponse.getBody();
146                         logger.info("requestbody {}", chefResponse.getBody());
147                     }
148                     chefServerResult(ctx, code, message);
149                 } catch (JSONException e) {
150                     code = APPC_ERRORCODE;
151                     logger.error(POSTING_REQUEST_JSON_ERROR_STR, e);
152                     doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
153                 } catch (Exception e) {
154                     code = APPC_ERRORCODE;
155                     logger.error(POSTING_REQUEST_ERROR_STR + "vnfcEnvironment", e);
156                     doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcEnvironment" + e.getMessage());
157                 }
158             } else {
159                 code = KEY_NOTFOUND;
160                 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
161                 doFailure(ctx, code, message);
162             }
163         }
164     }
165
166     @SuppressWarnings("nls")
167     @Override
168     public void vnfcNodeobjects(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
169         logger.info("update the nodeObjects of VNF-C");
170         int code;
171         try {
172             chefInfo(params, ctx);
173             String nodeListS = params.get(NODE_LIST_STR);
174             String nodeS = params.get("Node");
175             if (StringUtils.isNotBlank(nodeListS) && StringUtils.isNotBlank(nodeS)) {
176                 nodeListS = nodeListS.replace("[", StringUtils.EMPTY);
177                 nodeListS = nodeListS.replace("]", StringUtils.EMPTY);
178                 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
179                 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
180                 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
181                 code = STATUS_OK;
182                 String message = null;
183                 if (privateKeyChecker.doesExist(clientPrivatekey)) {
184                     ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username,
185                             clientPrivatekey);
186
187                     for (String nodeName : nodes) {
188                         JSONObject nodeJ = new JSONObject(nodeS);
189                         nodeJ.remove("name");
190                         nodeJ.put("name", nodeName);
191                         String nodeObject = nodeJ.toString();
192                         logger.info(nodeObject);
193                         ChefResponse chefResponse = cac.put("/nodes/" + nodeName, nodeObject);
194                         code = chefResponse.getStatusCode();
195                         message = chefResponse.getBody();
196                         if (code != STATUS_OK) {
197                             break;
198                         }
199                     }
200                 } else {
201                     code = KEY_NOTFOUND;
202                     message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
203                     doFailure(ctx, code, message);
204                 }
205                 chefServerResult(ctx, code, message);
206             } else {
207                 throw new SvcLogicException("Missing Mandatory param(s) Node , NodeList ");
208             }
209         } catch (JSONException e) {
210             code = APPC_ERRORCODE;
211             logger.error(POSTING_REQUEST_JSON_ERROR_STR + "vnfcNodeobjects", e);
212             doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + "vnfcNodeobjects" + e.getMessage());
213         } catch (Exception e) {
214             code = APPC_ERRORCODE;
215             logger.error(POSTING_REQUEST_ERROR_STR + "vnfcNodeobjects", e);
216             doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcNodeobjects" + e.getMessage());
217         }
218     }
219
220     @Override
221     public void vnfcPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
222         int code;
223         try {
224             chefInfo(params, ctx);
225             String nodeList = params.get(NODE_LIST_STR);
226             if (StringUtils.isNotBlank(nodeList)) {
227                 String isCallback = params.get("CallbackCapable");
228                 String chefAction = "/pushy/jobs";
229                 // need work on this
230                 String pushRequest;
231                 if ("true".equals(isCallback)) {
232                     String requestId = params.get("RequestId");
233                     String callbackUrl = params.get("CallbackUrl");
234                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
235                             + nodeList + "," + "\"env\": {\"RequestId\": \"" + requestId + "\", \"CallbackUrl\": \""
236                             + callbackUrl + "\"}," + "\"capture_output\": true" + "}";
237                 } else {
238                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
239                             + nodeList + "," + "\"env\": {}," + "\"capture_output\": true" + "}";
240                 }
241                 ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
242                 ChefResponse chefResponse = cac.post(chefAction, pushRequest);
243                 code = chefResponse.getStatusCode();
244                 logger.info("pushRequest:" + pushRequest);
245                 logger.info("requestbody: {}", chefResponse.getBody());
246                 String message = chefResponse.getBody();
247                 if (code == STATUS_PUSHJOBCHECK) {
248                     int startIndex = message.indexOf("jobs") + 5;
249                     int endIndex = message.length() - 2;
250                     String jobID = message.substring(startIndex, endIndex);
251                     ctx.setAttribute("jobID", jobID);
252                     logger.info(jobID);
253                 }
254                 chefServerResult(ctx, code, message);
255             } else {
256                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
257             }
258         } catch (Exception e) {
259             code = APPC_ERRORCODE;
260             logger.error(POSTING_REQUEST_ERROR_STR + "vnfcPushJob", e);
261             doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcPushJob" + e.getMessage());
262         }
263     }
264
265     @SuppressWarnings("nls")
266     @Override
267     public void fetchResults(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
268         int code = STATUS_OK;
269         try {
270             chefInfo(params, ctx);
271             String nodeListS = params.get(NODE_LIST_STR);
272             if (StringUtils.isNotBlank(nodeListS)) {
273                 nodeListS = nodeListS.replace("[", StringUtils.EMPTY);
274                 nodeListS = nodeListS.replace("]", StringUtils.EMPTY);
275                 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
276                 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
277                 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
278                 JSONObject result = new JSONObject();
279                 String returnMessage = StringUtils.EMPTY;
280
281                 for (String node : nodes) {
282                     String chefAction = "/nodes/" + node;
283                     String message;
284                     if (privateKeyChecker.doesExist(clientPrivatekey)) {
285                         ChefResponse chefResponse = getApiMethod(chefAction);
286                         code = chefResponse.getStatusCode();
287                         message = chefResponse.getBody();
288                     } else {
289                         code = KEY_NOTFOUND;
290                         message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
291                         doFailure(ctx, code, message);
292                     }
293                     if (code == STATUS_OK) {
294                         JSONObject nodeResult = new JSONObject();
295                         JSONObject allNodeData = new JSONObject(message);
296                         allNodeData = allNodeData.getJSONObject("normal");
297                         String attribute = "PushJobOutput";
298
299                         String resultData = allNodeData.optString(attribute, null);
300                         if (resultData == null) {
301                             resultData = Optional.ofNullable(allNodeData.optJSONObject(attribute))
302                                     .map(p -> p.toString()).orElse(null);
303                             if (resultData == null) {
304                                 resultData = Optional.ofNullable(allNodeData.optJSONArray(attribute))
305                                         .map(p -> p.toString()).orElse(null);
306
307                                 if (resultData == null) {
308                                     code = KEY_NOTFOUND;
309                                     returnMessage = "Cannot find " + attribute;
310                                     break;
311                                 }
312                             }
313                         }
314                         nodeResult.put(attribute, resultData);
315                         result.put(node, nodeResult);
316                         returnMessage = result.toString();
317                     } else {
318                         code = KEY_NOTFOUND;
319                         returnMessage = message + " Cannot access: " + node;
320                         doFailure(ctx, code, message);
321                         break;
322                     }
323                 }
324
325                 chefServerResult(ctx, code, returnMessage);
326             } else {
327                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
328             }
329         } catch (JSONException e) {
330             code = APPC_ERRORCODE;
331             logger.error(POSTING_REQUEST_JSON_ERROR_STR + "fetchResults", e);
332             doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + "fetchResults" + e.getMessage());
333         } catch (Exception e) {
334             code = APPC_ERRORCODE;
335             logger.error(POSTING_REQUEST_ERROR_STR + "fetchResults", e);
336             doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "fetchResults" + e.getMessage());
337         }
338     }
339
340     private ChefResponse getApiMethod(String chefAction) {
341         ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
342         return cac.get(chefAction);
343     }
344
345     /**
346      * build node object
347      */
348     @SuppressWarnings("nls")
349     @Override
350     public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
351         logger.info("nodeObejctBuilder");
352         String name = params.get("nodeobject.name");
353         String normal = params.get("nodeobject.normal");
354         String overrides = params.get("nodeobject.overrides");
355         String defaults = params.get("nodeobject.defaults");
356         String runList = params.get("nodeobject.run_list");
357         String chefEnvironment = params.get("nodeobject.chef_environment");
358         String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
359                 + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
360                 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
361                 + chefEnvironment + "\",}";
362         logger.info(nodeObject);
363         ctx.setAttribute("chef.nodeObject", nodeObject);
364     }
365
366     /**
367      * send get request to chef server
368      */
369     private void chefInfo(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
370
371         username = params.get("username");
372         serverAddress = params.get("serverAddress");
373         organizations = params.get("organizations");
374         if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(serverAddress)
375                 && StringUtils.isNotBlank(organizations)) {
376             chefserver = "https://" + serverAddress + "/organizations/" + organizations;
377             clientPrivatekey = "/opt/onap/appc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
378             logger.info(" clientPrivatekey  " + clientPrivatekey);
379         } else {
380             doFailure(ctx, APPC_ERRORCODE, "Missing mandatory param(s) such as username, serverAddress, organizations");
381         }
382     }
383
384     @SuppressWarnings("nls")
385     @Override
386     public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
387         String allConfigData = params.get("allConfig");
388         String key = params.get("key");
389         String dgContext = params.get("dgContext");
390         JSONObject jsonConfig = new JSONObject(allConfigData);
391         String contextData = fetchContextData(key, jsonConfig);
392         ctx.setAttribute(dgContext, contextData);
393     }
394
395     private String fetchContextData(String key, JSONObject jsonConfig) {
396         try {
397             return jsonConfig.getString(key);
398         } catch (Exception e) {
399             logger.error("Failed getting string value corresponding to " + key + ". Trying to fetch nested json object",
400                     e);
401             try {
402                 return jsonConfig.getJSONObject(key).toString();
403             } catch (Exception ex) {
404                 logger.error("Failed getting json object corresponding to " + key + ". Trying to fetch array", ex);
405                 return jsonConfig.getJSONArray(key).toString();
406             }
407         }
408     }
409
410     @SuppressWarnings("nls")
411     @Override
412     public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
413         String string1 = params.get("String1");
414         String string2 = params.get("String2");
415         String dgContext = params.get("dgContext");
416         String contextData = string1 + string2;
417         ctx.setAttribute(dgContext, contextData);
418     }
419
420     /**
421      * Send GET request to chef server
422      */
423     @SuppressWarnings("nls")
424
425     @Override
426     public void chefGet(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
427         logger.info("chef get method");
428         chefInfo(params, ctx);
429         String chefAction = params.get(CHEF_ACTION_STR);
430         int code;
431         String message;
432         if (privateKeyChecker.doesExist(clientPrivatekey)) {
433             ChefResponse chefResponse = getApiMethod(chefAction);
434             code = chefResponse.getStatusCode();
435             message = chefResponse.getBody();
436         } else {
437             code = KEY_NOTFOUND;
438             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
439         }
440         chefServerResult(ctx, code, message);
441     }
442
443     /**
444      * Send PUT request to chef server
445      */
446     @SuppressWarnings("nls")
447
448     @Override
449     public void chefPut(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
450         chefInfo(params, ctx);
451         String chefAction = params.get(CHEF_ACTION_STR);
452         String chefNodeStr = params.get("chefRequestBody");
453         int code;
454         String message;
455         if (privateKeyChecker.doesExist(clientPrivatekey)) {
456             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
457                     clientPrivatekey);
458             ChefResponse chefResponse = chefApiClient.put(chefAction, chefNodeStr);
459             code = chefResponse.getStatusCode();
460             message = chefResponse.getBody();
461         } else {
462             code = KEY_NOTFOUND;
463             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
464         }
465         logger.info(code + "   " + message);
466         chefServerResult(ctx, code, message);
467     }
468
469     /**
470      * send Post request to chef server
471      */
472     @Override
473     public void chefPost(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
474         chefInfo(params, ctx);
475         logger.info("chef Post method");
476         logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
477         String chefNodeStr = params.get("chefRequestBody");
478         String chefAction = params.get(CHEF_ACTION_STR);
479         int code;
480         String message;
481         // should load pem from somewhere else
482         if (privateKeyChecker.doesExist(clientPrivatekey)) {
483             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
484                     clientPrivatekey);
485             // need pass path into it
486             // "/nodes/testnode"
487             ChefResponse chefResponse = chefApiClient.post(chefAction, chefNodeStr);
488             code = chefResponse.getStatusCode();
489             message = chefResponse.getBody();
490         } else {
491             code = KEY_NOTFOUND;
492             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
493         }
494         logger.info(code + "   " + message);
495         chefServerResult(ctx, code, message);
496     }
497
498     /**
499      * send delete request to chef server
500      */
501     @Override
502     public void chefDelete(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
503         logger.info("chef delete method");
504         chefInfo(params, ctx);
505         String chefAction = params.get(CHEF_ACTION_STR);
506         int code;
507         String message;
508         if (privateKeyChecker.doesExist(clientPrivatekey)) {
509             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
510                     clientPrivatekey);
511             ChefResponse chefResponse = chefApiClient.delete(chefAction);
512             code = chefResponse.getStatusCode();
513             message = chefResponse.getBody();
514         } else {
515             code = KEY_NOTFOUND;
516             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
517         }
518         logger.info(code + "   " + message);
519         chefServerResult(ctx, code, message);
520     }
521
522     /**
523      * Trigger target vm run chef
524      */
525     @Override
526     public void trigger(Map<String, String> params, SvcLogicContext svcLogicContext) {
527         logger.info("Run trigger method");
528         String tVmIp = params.get("ip");
529         try {
530             ChefResponse chefResponse = chefApiClientFactory.create(tVmIp, organizations).get("");
531             chefClientResult(svcLogicContext, chefResponse.getStatusCode(), chefResponse.getBody());
532             svcLogicContext.setAttribute("chefAgent.code", STATUS_OK.toString());
533         } catch (Exception e) {
534             logger.error("An error occurred when executing trigger method", e);
535             svcLogicContext.setAttribute("chefAgent.code", KEY_NOTFOUND.toString());
536             svcLogicContext.setAttribute("chefAgent.message", e.toString());
537         }
538     }
539
540     @SuppressWarnings("nls")
541     @Override
542     public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
543         int code;
544         try {
545             chefInfo(params, ctx);
546             String jobID = params.get("jobid");
547             String retry = params.get("retryTimes");
548             String intrva = params.get("retryInterval");
549             if (StringUtils.isNotBlank(jobID) && StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
550
551                 int retryTimes = Integer.parseInt(params.get("retryTimes"));
552                 int retryInterval = Integer.parseInt(params.get("retryInterval"));
553                 String chefAction = "/pushy/jobs/" + jobID;
554                 String message = StringUtils.EMPTY;
555                 String status = StringUtils.EMPTY;
556                 for (int i = 0; i < retryTimes; i++) {
557                     sleepFor(retryInterval);
558                     ChefResponse chefResponse = getApiMethod(chefAction);
559                     code = chefResponse.getStatusCode();
560                     message = chefResponse.getBody();
561                     JSONObject obj = new JSONObject(message);
562                     status = obj.getString("status");
563                     if (!"running".equals(status)) {
564                         logger.info(i + " time " + code + "   " + status);
565                         break;
566                     }
567                 }
568                 resolveSvcLogicAttributes(ctx, message, status);
569             } else {
570                 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
571             }
572         } catch (Exception e) {
573             code = APPC_ERRORCODE;
574             logger.error("An error occurred when executing checkPushJob method", e);
575             doFailure(ctx, code, e.getMessage());
576         }
577     }
578
579     private void resolveSvcLogicAttributes(SvcLogicContext svcLogic, String message, String status)   {
580         if ("complete".equals(status)) {
581             if (hasFailedNode(message)) {
582                 String finalMessage = "PushJob Status Complete but check failed nodes in the message :" + message;
583                 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, APPC_ERRORCODE.toString());
584                 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, finalMessage);
585             } else {
586                 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, STATUS_OK.toString());
587                 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
588             }
589         } else if ("running".equals(status)) {
590             svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, PUSHJOBSTATUS.toString());
591             svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, "chef client runtime out");
592         } else {
593             svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, KEY_NOTFOUND.toString());
594             svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
595         }
596     }
597
598     private Boolean hasFailedNode(String message) throws JSONException {
599         try {   
600             JSONObject messageJson = new JSONObject(message);
601             JSONObject node = messageJson.getJSONObject("nodes");
602             if (node == null) {
603                 logger.debug("Status Complete but node details in the message is null : " + message);
604                 return Boolean.TRUE;
605             }
606             if (node.has("failed") && !(node.isNull("failed")) && (node.getJSONArray("failed").length() != 0)) {
607                 logger.debug("Status Complete but one or more Failed nodes ....FAILURE " + message);
608                 return Boolean.TRUE;
609             }
610             logger.debug("Status Complete and no failed nodes ....SUCCESS " + message);
611             return Boolean.FALSE;
612         } catch (JSONException e) {
613             logger.error("Exception occured in hasFailedNode", e);
614             throw new JSONException("Exception occured in hasFailedNode" + e.getMessage());
615         }
616
617     }
618
619     private void sleepFor(int retryInterval) {
620         try {
621             Thread.sleep(retryInterval); // 1000 milliseconds is one second.
622         } catch (InterruptedException ex) {
623             Thread.currentThread().interrupt();
624         }
625     }
626
627     @SuppressWarnings("nls")
628     @Override
629     public void pushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
630         int code;
631         try {
632             chefInfo(params, ctx);
633             String pushRequest = params.get("pushRequest");
634             String chefAction = "/pushy/jobs";
635             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
636                     clientPrivatekey);
637             ChefResponse chefResponse = chefApiClient.post(chefAction, pushRequest);
638             code = chefResponse.getStatusCode();
639             String message = chefResponse.getBody();
640             if (code == STATUS_PUSHJOBCHECK) {
641                 int startIndex = message.indexOf("jobs") + 6;
642                 int endIndex = message.length() - 2;
643                 String jobID = message.substring(startIndex, endIndex);
644                 ctx.setAttribute("jobID", jobID);
645                 logger.info(jobID);
646             }
647             chefServerResult(ctx, code, message);
648         } catch (Exception e) {
649             code = APPC_ERRORCODE;
650             logger.error("An error occurred when executing pushJob method", e);
651             doFailure(ctx, code, e.getMessage());
652         }
653     }
654
655     @SuppressWarnings("static-method")
656     private void chefServerResult(SvcLogicContext svcLogicContext, int code, String message) {
657         initSvcLogic(svcLogicContext, code, message, "server");
658     }
659
660     @SuppressWarnings("static-method")
661     private void chefClientResult(SvcLogicContext svcLogicContext, int code, String message) {
662         initSvcLogic(svcLogicContext, code, message, "client");
663     }
664
665     private void initSvcLogic(SvcLogicContext svcLogicContext, int code, String message, String target) {
666
667         String codeStr = "server".equals(target) ? CHEF_SERVER_RESULT_CODE_STR : CHEF_CLIENT_RESULT_CODE_STR;
668         String messageStr = "client".equals(target) ? CHEF_CLIENT_RESULT_MSG_STR : CHEF_SERVER_RESULT_MSG_STR;
669         svcLogicContext.setStatus(OUTCOME_SUCCESS);
670         svcLogicContext.setAttribute(codeStr, Integer.toString(code));
671         svcLogicContext.setAttribute(messageStr, message);
672         logger.info(codeStr + ": " + svcLogicContext.getAttribute(codeStr));
673         logger.info(messageStr + ": " + svcLogicContext.getAttribute(messageStr));
674     }
675
676     @SuppressWarnings("static-method")
677     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
678
679         String cutMessage = message.contains("\n") ? message.substring(message.indexOf('\n')) : message;
680         svcLogic.setStatus(OUTCOME_FAILURE);
681         svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, Integer.toString(code));
682         svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, cutMessage);
683         throw new SvcLogicException("Chef Adapter error:" + cutMessage);
684     }
685 }