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