Used constants in the place of dup literals
[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         final String LOG_STR = "fetchResults";
270         try {
271             chefInfo(params, ctx);
272             String nodeListS = params.get(NODE_LIST_STR);
273             if (StringUtils.isNotBlank(nodeListS)) {
274                 nodeListS = nodeListS.replace("[", StringUtils.EMPTY);
275                 nodeListS = nodeListS.replace("]", StringUtils.EMPTY);
276                 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
277                 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
278                 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
279                 JSONObject result = new JSONObject();
280                 String returnMessage = StringUtils.EMPTY;
281
282                 for (String node : nodes) {
283                     String chefAction = "/nodes/" + node;
284                     String message;
285                     if (privateKeyChecker.doesExist(clientPrivatekey)) {
286                         ChefResponse chefResponse = getApiMethod(chefAction);
287                         code = chefResponse.getStatusCode();
288                         message = chefResponse.getBody();
289                     } else {
290                         code = KEY_NOTFOUND;
291                         message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
292                         doFailure(ctx, code, message);
293                     }
294                     if (code == STATUS_OK) {
295                         JSONObject nodeResult = new JSONObject();
296                         JSONObject allNodeData = new JSONObject(message);
297                         allNodeData = allNodeData.getJSONObject("normal");
298                         String attribute = "PushJobOutput";
299
300                         String resultData = allNodeData.optString(attribute, null);
301                         if (resultData == null) {
302                             resultData = Optional.ofNullable(allNodeData.optJSONObject(attribute))
303                                     .map(p -> p.toString()).orElse(null);
304                             if (resultData == null) {
305                                 resultData = Optional.ofNullable(allNodeData.optJSONArray(attribute))
306                                         .map(p -> p.toString()).orElse(null);
307
308                                 if (resultData == null) {
309                                     code = KEY_NOTFOUND;
310                                     returnMessage = "Cannot find " + attribute;
311                                     break;
312                                 }
313                             }
314                         }
315                         nodeResult.put(attribute, resultData);
316                         result.put(node, nodeResult);
317                         returnMessage = result.toString();
318                     } else {
319                         code = KEY_NOTFOUND;
320                         returnMessage = message + " Cannot access: " + node;
321                         doFailure(ctx, code, message);
322                         break;
323                     }
324                 }
325
326                 chefServerResult(ctx, code, returnMessage);
327             } else {
328                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
329             }
330         } catch (JSONException e) {
331             code = APPC_ERRORCODE;
332             logger.error(POSTING_REQUEST_JSON_ERROR_STR + LOG_STR, e);
333             doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + LOG_STR + e.getMessage());
334         } catch (Exception e) {
335             code = APPC_ERRORCODE;
336             logger.error(POSTING_REQUEST_ERROR_STR + LOG_STR, e);
337             doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + LOG_STR + e.getMessage());
338         }
339     }
340
341     private ChefResponse getApiMethod(String chefAction) {
342         ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
343         return cac.get(chefAction);
344     }
345
346     /**
347      * build node object
348      */
349     @SuppressWarnings("nls")
350     @Override
351     public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
352         logger.info("nodeObejctBuilder");
353         String name = params.get("nodeobject.name");
354         String normal = params.get("nodeobject.normal");
355         String overrides = params.get("nodeobject.overrides");
356         String defaults = params.get("nodeobject.defaults");
357         String runList = params.get("nodeobject.run_list");
358         String chefEnvironment = params.get("nodeobject.chef_environment");
359         String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
360                 + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
361                 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
362                 + chefEnvironment + "\",}";
363         logger.info(nodeObject);
364         ctx.setAttribute("chef.nodeObject", nodeObject);
365     }
366
367     /**
368      * send get request to chef server
369      */
370     private void chefInfo(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
371
372         username = params.get("username");
373         serverAddress = params.get("serverAddress");
374         organizations = params.get("organizations");
375         if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(serverAddress)
376                 && StringUtils.isNotBlank(organizations)) {
377             chefserver = "https://" + serverAddress + "/organizations/" + organizations;
378             clientPrivatekey = "/opt/onap/appc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
379             logger.info(" clientPrivatekey  " + clientPrivatekey);
380         } else {
381             doFailure(ctx, APPC_ERRORCODE, "Missing mandatory param(s) such as username, serverAddress, organizations");
382         }
383     }
384
385     @SuppressWarnings("nls")
386     @Override
387     public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
388         String allConfigData = params.get("allConfig");
389         String key = params.get("key");
390         String dgContext = params.get("dgContext");
391         JSONObject jsonConfig = new JSONObject(allConfigData);
392         String contextData = fetchContextData(key, jsonConfig);
393         ctx.setAttribute(dgContext, contextData);
394     }
395
396     private String fetchContextData(String key, JSONObject jsonConfig) {
397         try {
398             return jsonConfig.getString(key);
399         } catch (Exception e) {
400             logger.error("Failed getting string value corresponding to " + key + ". Trying to fetch nested json object",
401                     e);
402             try {
403                 return jsonConfig.getJSONObject(key).toString();
404             } catch (Exception ex) {
405                 logger.error("Failed getting json object corresponding to " + key + ". Trying to fetch array", ex);
406                 return jsonConfig.getJSONArray(key).toString();
407             }
408         }
409     }
410
411     @SuppressWarnings("nls")
412     @Override
413     public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
414         String string1 = params.get("String1");
415         String string2 = params.get("String2");
416         String dgContext = params.get("dgContext");
417         String contextData = string1 + string2;
418         ctx.setAttribute(dgContext, contextData);
419     }
420
421     /**
422      * Send GET request to chef server
423      */
424     @SuppressWarnings("nls")
425
426     @Override
427     public void chefGet(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
428         logger.info("chef get method");
429         chefInfo(params, ctx);
430         String chefAction = params.get(CHEF_ACTION_STR);
431         int code;
432         String message;
433         if (privateKeyChecker.doesExist(clientPrivatekey)) {
434             ChefResponse chefResponse = getApiMethod(chefAction);
435             code = chefResponse.getStatusCode();
436             message = chefResponse.getBody();
437         } else {
438             code = KEY_NOTFOUND;
439             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
440         }
441         chefServerResult(ctx, code, message);
442     }
443
444     /**
445      * Send PUT request to chef server
446      */
447     @SuppressWarnings("nls")
448
449     @Override
450     public void chefPut(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
451         chefInfo(params, ctx);
452         String chefAction = params.get(CHEF_ACTION_STR);
453         String chefNodeStr = params.get("chefRequestBody");
454         int code;
455         String message;
456         if (privateKeyChecker.doesExist(clientPrivatekey)) {
457             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
458                     clientPrivatekey);
459             ChefResponse chefResponse = chefApiClient.put(chefAction, chefNodeStr);
460             code = chefResponse.getStatusCode();
461             message = chefResponse.getBody();
462         } else {
463             code = KEY_NOTFOUND;
464             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
465         }
466         logger.info(code + "   " + message);
467         chefServerResult(ctx, code, message);
468     }
469
470     /**
471      * send Post request to chef server
472      */
473     @Override
474     public void chefPost(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
475         chefInfo(params, ctx);
476         logger.info("chef Post method");
477         logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
478         String chefNodeStr = params.get("chefRequestBody");
479         String chefAction = params.get(CHEF_ACTION_STR);
480         int code;
481         String message;
482         // should load pem from somewhere else
483         if (privateKeyChecker.doesExist(clientPrivatekey)) {
484             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
485                     clientPrivatekey);
486             // need pass path into it
487             // "/nodes/testnode"
488             ChefResponse chefResponse = chefApiClient.post(chefAction, chefNodeStr);
489             code = chefResponse.getStatusCode();
490             message = chefResponse.getBody();
491         } else {
492             code = KEY_NOTFOUND;
493             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
494         }
495         logger.info(code + "   " + message);
496         chefServerResult(ctx, code, message);
497     }
498
499     /**
500      * send delete request to chef server
501      */
502     @Override
503     public void chefDelete(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
504         logger.info("chef delete method");
505         chefInfo(params, ctx);
506         String chefAction = params.get(CHEF_ACTION_STR);
507         int code;
508         String message;
509         if (privateKeyChecker.doesExist(clientPrivatekey)) {
510             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
511                     clientPrivatekey);
512             ChefResponse chefResponse = chefApiClient.delete(chefAction);
513             code = chefResponse.getStatusCode();
514             message = chefResponse.getBody();
515         } else {
516             code = KEY_NOTFOUND;
517             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
518         }
519         logger.info(code + "   " + message);
520         chefServerResult(ctx, code, message);
521     }
522
523     /**
524      * Trigger target vm run chef
525      */
526     @Override
527     public void trigger(Map<String, String> params, SvcLogicContext svcLogicContext) {
528         logger.info("Run trigger method");
529         String tVmIp = params.get("ip");
530         try {
531             ChefResponse chefResponse = chefApiClientFactory.create(tVmIp, organizations).get("");
532             chefClientResult(svcLogicContext, chefResponse.getStatusCode(), chefResponse.getBody());
533             svcLogicContext.setAttribute("chefAgent.code", STATUS_OK.toString());
534         } catch (Exception e) {
535             logger.error("An error occurred when executing trigger method", e);
536             svcLogicContext.setAttribute("chefAgent.code", KEY_NOTFOUND.toString());
537             svcLogicContext.setAttribute("chefAgent.message", e.toString());
538         }
539     }
540
541     @SuppressWarnings("nls")
542     @Override
543     public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
544         int code;
545         try {
546             chefInfo(params, ctx);
547             String jobID = params.get("jobid");
548             String retry = params.get("retryTimes");
549             String intrva = params.get("retryInterval");
550             if (StringUtils.isNotBlank(jobID) && StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
551
552                 int retryTimes = Integer.parseInt(params.get("retryTimes"));
553                 int retryInterval = Integer.parseInt(params.get("retryInterval"));
554                 String chefAction = "/pushy/jobs/" + jobID;
555                 String message = StringUtils.EMPTY;
556                 String status = StringUtils.EMPTY;
557                 for (int i = 0; i < retryTimes; i++) {
558                     sleepFor(retryInterval);
559                     ChefResponse chefResponse = getApiMethod(chefAction);
560                     code = chefResponse.getStatusCode();
561                     message = chefResponse.getBody();
562                     JSONObject obj = new JSONObject(message);
563                     status = obj.getString("status");
564                     if (!"running".equals(status)) {
565                         logger.info(i + " time " + code + "   " + status);
566                         break;
567                     }
568                 }
569                 resolveSvcLogicAttributes(ctx, message, status);
570             } else {
571                 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
572             }
573         } catch (Exception e) {
574             code = APPC_ERRORCODE;
575             logger.error("An error occurred when executing checkPushJob method", e);
576             doFailure(ctx, code, e.getMessage());
577         }
578     }
579
580     private void resolveSvcLogicAttributes(SvcLogicContext svcLogic, String message, String status)   {
581         if ("complete".equals(status)) {
582             if (hasFailedNode(message)) {
583                 String finalMessage = "PushJob Status Complete but check failed nodes in the message :" + message;
584                 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, APPC_ERRORCODE.toString());
585                 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, finalMessage);
586             } else {
587                 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, STATUS_OK.toString());
588                 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
589             }
590         } else if ("running".equals(status)) {
591             svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, PUSHJOBSTATUS.toString());
592             svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, "chef client runtime out");
593         } else {
594             svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, KEY_NOTFOUND.toString());
595             svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
596         }
597     }
598
599     private Boolean hasFailedNode(String message) throws JSONException {
600         try {   
601             JSONObject messageJson = new JSONObject(message);
602             JSONObject node = messageJson.getJSONObject("nodes");
603             if (node == null) {
604                 logger.debug("Status Complete but node details in the message is null : " + message);
605                 return Boolean.TRUE;
606             }
607             if (node.has("failed") && !(node.isNull("failed")) && (node.getJSONArray("failed").length() != 0)) {
608                 logger.debug("Status Complete but one or more Failed nodes ....FAILURE " + message);
609                 return Boolean.TRUE;
610             }
611             logger.debug("Status Complete and no failed nodes ....SUCCESS " + message);
612             return Boolean.FALSE;
613         } catch (JSONException e) {
614             logger.error("Exception occured in hasFailedNode", e);
615             throw new JSONException("Exception occured in hasFailedNode" + e.getMessage());
616         }
617
618     }
619
620     private void sleepFor(int retryInterval) {
621         try {
622             Thread.sleep(retryInterval); // 1000 milliseconds is one second.
623         } catch (InterruptedException ex) {
624             Thread.currentThread().interrupt();
625         }
626     }
627
628     @SuppressWarnings("nls")
629     @Override
630     public void pushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
631         int code;
632         try {
633             chefInfo(params, ctx);
634             String pushRequest = params.get("pushRequest");
635             String chefAction = "/pushy/jobs";
636             ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
637                     clientPrivatekey);
638             ChefResponse chefResponse = chefApiClient.post(chefAction, pushRequest);
639             code = chefResponse.getStatusCode();
640             String message = chefResponse.getBody();
641             if (code == STATUS_PUSHJOBCHECK) {
642                 int startIndex = message.indexOf("jobs") + 6;
643                 int endIndex = message.length() - 2;
644                 String jobID = message.substring(startIndex, endIndex);
645                 ctx.setAttribute("jobID", jobID);
646                 logger.info(jobID);
647             }
648             chefServerResult(ctx, code, message);
649         } catch (Exception e) {
650             code = APPC_ERRORCODE;
651             logger.error("An error occurred when executing pushJob method", e);
652             doFailure(ctx, code, e.getMessage());
653         }
654     }
655
656     @SuppressWarnings("static-method")
657     private void chefServerResult(SvcLogicContext svcLogicContext, int code, String message) {
658         initSvcLogic(svcLogicContext, code, message, "server");
659     }
660
661     @SuppressWarnings("static-method")
662     private void chefClientResult(SvcLogicContext svcLogicContext, int code, String message) {
663         initSvcLogic(svcLogicContext, code, message, "client");
664     }
665
666     private void initSvcLogic(SvcLogicContext svcLogicContext, int code, String message, String target) {
667
668         String codeStr = "server".equals(target) ? CHEF_SERVER_RESULT_CODE_STR : CHEF_CLIENT_RESULT_CODE_STR;
669         String messageStr = "client".equals(target) ? CHEF_CLIENT_RESULT_MSG_STR : CHEF_SERVER_RESULT_MSG_STR;
670         svcLogicContext.setStatus(OUTCOME_SUCCESS);
671         svcLogicContext.setAttribute(codeStr, Integer.toString(code));
672         svcLogicContext.setAttribute(messageStr, message);
673         logger.info(codeStr + ": " + svcLogicContext.getAttribute(codeStr));
674         logger.info(messageStr + ": " + svcLogicContext.getAttribute(messageStr));
675     }
676
677     @SuppressWarnings("static-method")
678     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
679
680         String cutMessage = message.contains("\n") ? message.substring(message.indexOf('\n')) : message;
681         svcLogic.setStatus(OUTCOME_FAILURE);
682         svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, Integer.toString(code));
683         svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, cutMessage);
684         throw new SvcLogicException("Chef Adapter error:" + cutMessage);
685     }
686 }