Reformat and clean up ChefAdapterImpl.java
[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 java.io.File;
27 import java.util.Arrays;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Properties;
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.http.HttpEntity;
33 import org.apache.http.HttpResponse;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.impl.client.CloseableHttpClient;
36 import org.apache.http.impl.client.HttpClients;
37 import org.apache.http.util.EntityUtils;
38 import org.json.JSONException;
39 import org.json.JSONObject;
40 import org.onap.appc.adapter.chef.ChefAdapter;
41 import org.onap.appc.adapter.chef.chefapi.ApiMethod;
42 import org.onap.appc.adapter.chef.chefclient.ChefApiClient;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
45 import com.att.eelf.configuration.EELFLogger;
46 import com.att.eelf.configuration.EELFManager;
47
48 /**
49  * This class implements the {@link ChefAdapter} interface. This interface
50  * defines the behaviors that our service provides.
51  */
52 public class ChefAdapterImpl implements ChefAdapter {
53     // chef server Initialize variable
54     private String username = StringUtils.EMPTY;
55     private String clientPrivatekey = StringUtils.EMPTY;
56     private String chefserver = StringUtils.EMPTY;
57     private String serverAddress = StringUtils.EMPTY;
58     private String organizations = StringUtils.EMPTY;
59
60     @SuppressWarnings("nls")
61     public static final String MDC_ADAPTER = "adapter";
62
63     @SuppressWarnings("nls")
64     public static final String MDC_SERVICE = "service";
65
66     @SuppressWarnings("nls")
67     public static final String OUTCOME_FAILURE = "failure";
68
69     @SuppressWarnings("nls")
70     public static final String OUTCOME_SUCCESS = "success";
71
72     @SuppressWarnings("nls")
73     public static final String PROPERTY_PROVIDER = "provider";
74
75     @SuppressWarnings("nls")
76     public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
77
78     @SuppressWarnings("nls")
79     public static final String PROPERTY_PROVIDER_NAME = "name";
80
81     @SuppressWarnings("nls")
82     public static final String PROPERTY_PROVIDER_TENANT = "tenant";
83
84     @SuppressWarnings("nls")
85     public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
86
87     @SuppressWarnings("nls")
88     public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
89
90     @SuppressWarnings("nls")
91     public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
92
93     @SuppressWarnings("nls")
94     public static final String PROPERTY_PROVIDER_TYPE = "type";
95
96
97     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
98
99     private static final String CANNOT_FIND_PRIVATE_KEY_STR =
100             "Cannot find the private key in the APPC file system, please load the private key to ";
101
102     /**
103      * This default constructor is used as a work around because the activator wasnt
104      * getting called
105      */
106     public ChefAdapterImpl() {
107         initialize();
108     }
109
110     public ChefAdapterImpl(Properties props) {
111         initialize();
112     }
113
114     /**
115      * This constructor is used primarily in the test cases to bypass initialization
116      * of the adapter for isolated, disconnected testing
117      *
118      * @param initialize
119      *        True if the adapter is to be initialized, can false if not
120      */
121
122     public ChefAdapterImpl(boolean initialize) {
123         if (initialize) {
124             initialize();
125         }
126     }
127
128     public ChefAdapterImpl(String key) {
129         initialize();
130     }
131
132     /**
133      * Returns the symbolic name of the adapter
134      *
135      * @return The adapter name
136      * @see org.onap.appc.adapter.chef.ChefAdapter#getAdapterName()
137      */
138     @Override
139     public String getAdapterName() {
140         return "chef adapter";
141     }
142
143     @SuppressWarnings("nls")
144     @Override
145     public void VnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
146         int code;
147         try {
148             logger.info("environment of VNF-C");
149             chefInfo(params, ctx);
150             RequestContext rc = new RequestContext(ctx);
151             logger.info("Context" + ctx);
152             rc.isAlive();
153             String env = params.get("Environment");
154             logger.info("Environmnet" + env);
155             if (env.equals(StringUtils.EMPTY)) {
156                 chefServerResult(rc, "200", "Skip Environment block ");
157             } else {
158                 JSONObject env_J = new JSONObject(env);
159                 String envName = env_J.getString("name");
160                 String message = null;
161                 if (privateKeyCheck()) {
162                     // update the details of an environment on the Chef server.
163                     ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
164                     ApiMethod am = cac.put("/environments/" + envName).body(env);
165                     am.execute();
166                     code = am.getReturnCode();
167                     message = am.getResponseBodyAsString();
168                     if (code == 404) {
169                         // need create a new environment
170                         am = cac.post("/environments").body(env);
171                         am.execute();
172                         code = am.getReturnCode();
173                         message = am.getResponseBodyAsString();
174                         logger.info("requestbody" + am.getReqBody());
175                     }
176
177                 } else {
178                     code = 500;
179                     message = "Cannot find the private key in the APPC file system, please load the private key to "
180                             + clientPrivatekey;
181                     doFailure(ctx, code, message);
182                 }
183                 chefServerResult(rc, Integer.toString(code), message);
184             }
185         }
186
187         catch (JSONException e) {
188             code = 401;
189             doFailure(ctx, code, "Error posting request  due to invalid JSON block. Reason = " + e.getMessage());
190         } catch (Exception e) {
191             code = 401;
192             doFailure(ctx, code, "Error posting request :Reason = " + e.getMessage());
193         }
194     }
195
196     @SuppressWarnings("nls")
197     @Override
198     public void VnfcNodeobjects(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
199         logger.info("update the nodeObjects of VNF-C");
200         int code;
201         try {
202             chefInfo(params, ctx);
203             String nodeList_S = params.get("NodeList");
204             String node_S = params.get("Node");
205             if (StringUtils.isNotBlank(nodeList_S) && StringUtils.isNotBlank(node_S)) {
206                 nodeList_S = nodeList_S.replace("[", StringUtils.EMPTY);
207                 nodeList_S = nodeList_S.replace("]", StringUtils.EMPTY);
208                 nodeList_S = nodeList_S.replace("\"", StringUtils.EMPTY);
209                 nodeList_S = nodeList_S.replace(" ", StringUtils.EMPTY);
210                 List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*"));
211                 RequestContext rc = new RequestContext(ctx);
212                 rc.isAlive();
213                 code = 200;
214                 String message = null;
215                 if (privateKeyCheck()) {
216                     ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
217
218                     for (int i = 0; i < nodes.size(); i++) {
219                         String nodeName = nodes.get(i);
220                         JSONObject node_J = new JSONObject(node_S);
221                         node_J.remove("name");
222                         node_J.put("name", nodeName);
223                         String nodeObject = node_J.toString();
224                         logger.info(nodeObject);
225                         ApiMethod am = cac.put("/nodes/" + nodeName).body(nodeObject);
226                         am.execute();
227                         code = am.getReturnCode();
228                         message = am.getResponseBodyAsString();
229                         if (code != 200) {
230                             break;
231                         }
232                     }
233                 } else {
234                     code = 500;
235                     message = "Cannot find the private key in the APPC file system, please load the private key to "
236                             + clientPrivatekey;
237                     doFailure(ctx, code, message);
238                 }
239                 chefServerResult(rc, Integer.toString(code), message);
240             }
241             else {
242                 throw new SvcLogicException("Missing Mandatory param(s) Node , NodeList ");
243             }
244         } catch (JSONException e) {
245             code = 401;
246             doFailure(ctx, code, "Error posting request  due to invalid JSON block. Reason = " + e.getMessage());
247         } catch (Exception ex) {
248             code = 401;
249             doFailure(ctx, code, "Error posting request :Reason = " + ex.getMessage());
250         }
251     }
252
253     @Override
254     public void VnfcPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
255         int code;
256         try {
257             chefInfo(params, ctx);
258             String nodeList = params.get("NodeList");
259             if (StringUtils.isNotBlank(nodeList)) {
260                 String isCallback = params.get("CallbackCapable");
261                 String chefAction = "/pushy/jobs";
262                 // need work on this
263                 String pushRequest = StringUtils.EMPTY;
264                 if (isCallback.equals("true")) {
265                     String requestId = params.get("RequestId");
266                     String callbackUrl = params.get("CallbackUrl");
267                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
268                             + nodeList + "," + "\"env\": {\"RequestId\": \"" + requestId + "\", \"CallbackUrl\": \""
269                             + callbackUrl + "\"}," + "\"capture_output\": true" + "}";
270                 } else {
271                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
272                             + nodeList + "," + "\"env\": {}," + "\"capture_output\": true" + "}";
273                 }
274                 RequestContext rc = new RequestContext(ctx);
275
276                 rc.isAlive();
277                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
278                 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
279                 ApiMethod am = cac.post(chefAction).body(pushRequest);
280                 am.execute();
281                 code = am.getReturnCode();
282                 logger.info("pushRequest:" + pushRequest);
283                 logger.info("requestbody:" + am.getReqBody());
284                 String message = am.getResponseBodyAsString();
285                 if (code == 201) {
286                     int startIndex = message.indexOf("jobs") + 5;
287                     int endIndex = message.length() - 2;
288                     String jobID = message.substring(startIndex, endIndex);
289                     svcLogic.setAttribute("jobID", jobID);
290                     logger.info(jobID);
291                 }
292                 chefServerResult(rc, Integer.toString(code), message);
293             }
294             else {
295                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
296             }
297         } catch (JSONException e) {
298             code = 401;
299             doFailure(ctx, code, "Error posting request  due to invalid JSON block. Reason = " + e.getMessage());
300         } catch (Exception e) {
301             code = 401;
302             doFailure(ctx, code, e.getMessage());
303         }
304     }
305
306     @SuppressWarnings("nls")
307     @Override
308     public void fetchResults(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
309         int code;
310         try {
311             chefInfo(params, ctx);
312             String nodeList_S = params.get("NodeList");
313             if (StringUtils.isNotBlank(nodeList_S)) {
314                 nodeList_S = nodeList_S.replace("[", StringUtils.EMPTY);
315                 nodeList_S = nodeList_S.replace("]", StringUtils.EMPTY);
316                 nodeList_S = nodeList_S.replace("\"", StringUtils.EMPTY);
317                 nodeList_S = nodeList_S.replace(" ", StringUtils.EMPTY);
318                 List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*"));
319                 JSONObject Result = new JSONObject();
320                 String returnCode = "200";
321                 String returnMessage = StringUtils.EMPTY;
322
323                 for (int i = 0; i < nodes.size(); i++) {
324                     String node = nodes.get(i);
325                     String chefAction = "/nodes/" + node;
326                     String message = null;
327                     if (privateKeyCheck()) {
328                         ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
329                         ApiMethod am = cac.get(chefAction);
330                         am.execute();
331                         code = am.getReturnCode();
332                         message = am.getResponseBodyAsString();
333                     } else {
334                         code = 500;
335                         message = "Cannot find the private key in the APPC file system, please load the private key to "
336                                 + clientPrivatekey;
337                         doFailure(ctx, code, message);
338                     }
339                     if (code == 200) {
340                         JSONObject nodeResult = new JSONObject();
341                         JSONObject allNodeData = new JSONObject(message);
342                         allNodeData = allNodeData.getJSONObject("normal");
343                         String attribute = "PushJobOutput";
344                         String resultData;
345                         try {
346                             resultData = allNodeData.getString(attribute);
347                         } catch (Exception exc1) {
348                             try {
349                                 resultData = allNodeData.getJSONObject(attribute).toString();
350                             } catch (Exception exc2) {
351                                 try {
352                                     resultData = allNodeData.getJSONArray(attribute).toString();
353                                 } catch (Exception exc3) {
354                                     returnCode = "500";
355                                     returnMessage = "cannot find " + attribute;
356                                     break;
357                                 }
358                             }
359                         }
360                         nodeResult.put(attribute, resultData);
361                         Result.put(node, nodeResult);
362                     } else {
363                         returnCode = "500";
364                         returnMessage = message + " Cannot access: " + node;
365                         doFailure(ctx, code, message);
366                         break;
367                     }
368                 }
369                 RequestContext rc = new RequestContext(ctx);
370                 rc.isAlive();
371                 if (!returnCode.equals("500")) {
372                     returnMessage = Result.toString();
373                     returnCode = "200";
374                 }
375                 chefServerResult(rc, returnCode, returnMessage);
376             }
377             else {
378                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
379             }
380         } catch (JSONException e) {
381             code = 401;
382             doFailure(ctx, code, "Error posting request  due to invalid JSON block. Reason = " + e.getMessage());
383         } catch (Exception ex) {
384             code = 401;
385             doFailure(ctx, code, "Error posting request :Reason = " + ex.getMessage());
386         }
387     }
388
389     /**
390      * build node object
391      */
392     @SuppressWarnings("nls")
393     @Override
394     public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
395         logger.info("nodeObejctBuilder");
396         String name = params.get("nodeobject.name");
397         String normal = params.get("nodeobject.normal");
398         String overrides = params.get("nodeobject.overrides");
399         String defaults = params.get("nodeobject.defaults");
400         String runList = params.get("nodeobject.run_list");
401         String chefEnvironment = params.get("nodeobject.chef_environment");
402         String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
403                 + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
404                 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
405                 + chefEnvironment + "\"}";
406         logger.info(nodeObject);
407         RequestContext rc = new RequestContext(ctx);
408         rc.isAlive();
409         SvcLogicContext svcLogic = rc.getSvcLogicContext();
410         svcLogic.setAttribute("chef.nodeObject", nodeObject);
411     }
412
413     /**
414      * send get request to chef server
415      * 
416      * @throws SvcLogicException
417      */
418     public void chefInfo(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
419
420         username = params.get("username");
421         serverAddress = params.get("serverAddress");
422         organizations = params.get("organizations");
423         if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(serverAddress)
424                 && StringUtils.isNotBlank(organizations)) {
425             chefserver = "https://" + serverAddress + "/organizations/" + organizations;
426             clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
427             logger.info(" clientPrivatekey  " + clientPrivatekey);
428         } else {
429             String message = "Missing mandatory param(s) such as username,serverAddres,organizations";
430             doFailure(ctx, 401, message);
431         }
432     }
433
434     public Boolean privateKeyCheck() {
435         File f = new File(clientPrivatekey);
436         if (f.exists()) {
437             logger.info("Key exists");
438             return true;
439         } else {
440             logger.info("Key doesnot exists");
441             return false;
442         }
443     }
444
445     @SuppressWarnings("nls")
446     @Override
447     public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
448         String contextData = "someValue";
449         String allConfigData = params.get("allConfig");
450         String key = params.get("key");
451         String dgContext = params.get("dgContext");
452         JSONObject josnConfig = new JSONObject(allConfigData);
453
454         try {
455             contextData = josnConfig.getString(key);
456         } catch (Exception ex) {
457             try {
458                 contextData = josnConfig.getJSONObject(key).toString();
459             } catch (Exception exc) {
460                 contextData = josnConfig.getJSONArray(key).toString();
461             }
462         }
463
464         RequestContext rc = new RequestContext(ctx);
465         rc.isAlive();
466         SvcLogicContext svcLogic = rc.getSvcLogicContext();
467         svcLogic.setAttribute(dgContext, contextData);
468     }
469
470     @SuppressWarnings("nls")
471     @Override
472     public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
473         String string1 = params.get("String1");
474         String string2 = params.get("String2");
475         String dgContext = params.get("dgContext");
476         String contextData = string1 + string2;
477         RequestContext rc = new RequestContext(ctx);
478         rc.isAlive();
479         SvcLogicContext svcLogic = rc.getSvcLogicContext();
480         svcLogic.setAttribute(dgContext, contextData);
481     }
482
483     /**
484      * Send GET request to chef server
485      * 
486      * @throws SvcLogicException
487      */
488     @SuppressWarnings("nls")
489
490     @Override
491     public void chefGet(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
492         logger.info("chef get method");
493         chefInfo(params, ctx);
494         String chefAction = params.get("chefAction");
495         RequestContext rc = new RequestContext(ctx);
496         rc.isAlive();
497         int code;
498         String message = null;
499
500         if (privateKeyCheck()) {
501             ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
502             ApiMethod am = cac.get(chefAction);
503             am.execute();
504             code = am.getReturnCode();
505             message = am.getResponseBodyAsString();
506         } else {
507             code = 500;
508             message = "Cannot find the private key in the APPC file system, please load the private key to "
509                     + clientPrivatekey;
510         }
511         chefServerResult(rc, Integer.toString(code), message);
512     }
513
514     /**
515      * Send PUT request to chef server
516      * 
517      * @throws SvcLogicException
518      */
519     @SuppressWarnings("nls")
520
521     @Override
522     public void chefPut(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
523         chefInfo(params, ctx);
524         String chefAction = params.get("chefAction");
525         String chefNodeStr = params.get("chefRequestBody");
526         RequestContext rc = new RequestContext(ctx);
527         rc.isAlive();
528         int code;
529         String message;
530         if (privateKeyCheck()) {
531             ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
532
533             ApiMethod am = cac.put(chefAction).body(chefNodeStr);
534             am.execute();
535             code = am.getReturnCode();
536             message = am.getResponseBodyAsString();
537         } else {
538             code = 500;
539             message = "Cannot find the private key in the APPC file system, please load the private key to "
540                     + clientPrivatekey;
541         }
542         logger.info(code + "   " + message);
543         chefServerResult(rc, Integer.toString(code), message);
544     }
545
546     /**
547      * send Post request to chef server
548      * 
549      * @throws SvcLogicException
550      */
551     @Override
552     public void chefPost(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
553         chefInfo(params, ctx);
554         logger.info("chef Post method");
555         logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
556         String chefNodeStr = params.get("chefRequestBody");
557         String chefAction = params.get("chefAction");
558
559         RequestContext rc = new RequestContext(ctx);
560         rc.isAlive();
561         int code;
562         String message;
563         // should load pem from somewhere else
564         if (privateKeyCheck()) {
565             ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
566
567             // need pass path into it
568             // "/nodes/testnode"
569             ApiMethod am = cac.post(chefAction).body(chefNodeStr);
570             am.execute();
571             code = am.getReturnCode();
572             message = am.getResponseBodyAsString();
573         } else {
574             code = 500;
575             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
576         }
577         logger.info(code + "   " + message);
578         chefServerResult(rc, Integer.toString(code), message);
579     }
580
581     /**
582      * send delete request to chef server
583      * 
584      * @throws SvcLogicException
585      */
586     @Override
587     public void chefDelete(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
588         logger.info("chef delete method");
589         chefInfo(params, ctx);
590         String chefAction = params.get("chefAction");
591         RequestContext rc = new RequestContext(ctx);
592         rc.isAlive();
593         int code;
594         String message = null;
595         if (privateKeyCheck()) {
596             ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
597             ApiMethod am = cac.delete(chefAction);
598             am.execute();
599             code = am.getReturnCode();
600             message = am.getResponseBodyAsString();
601         } else {
602             code = 500;
603             message = "Cannot find the private key in the APPC file system, please load the private key to "
604                     + clientPrivatekey;
605         }
606         logger.info(code + "   " + message);
607         chefServerResult(rc, Integer.toString(code), message);
608     }
609
610     /**
611      * Trigger target vm run chef
612      */
613     @Override
614     public void trigger(Map<String, String> params, SvcLogicContext ctx) {
615         logger.info("Run trigger method");
616         String tVmIp = params.get("ip");
617         RequestContext rc = new RequestContext(ctx);
618         rc.isAlive();
619
620         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
621             HttpGet httpGet = new HttpGet(tVmIp);
622             HttpResponse response = null;
623             response = httpClient.execute(httpGet);
624             int responseCode = response.getStatusLine().getStatusCode();
625             HttpEntity entity = response.getEntity();
626             String responseOutput = EntityUtils.toString(entity);
627             chefClientResult(rc, Integer.toString(responseCode), responseOutput);
628             doSuccess(rc);
629         } catch (Exception ex) {
630             doFailure(rc, 500, ex.toString());
631         }
632     }
633
634     @SuppressWarnings("nls")
635     @Override
636     public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
637         int code;
638         try {
639             chefInfo(params, ctx);
640             String jobID = params.get("jobid");
641             String retry = params.get("retryTimes");
642             String intrva = params.get("retryInterval");
643             if (StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
644
645                 int retryTimes = Integer.parseInt(params.get("retryTimes"));
646                 int retryInterval = Integer.parseInt(params.get("retryInterval"));
647
648                 String chefAction = "/pushy/jobs/" + jobID;
649
650                 RequestContext rc = new RequestContext(ctx);
651                 rc.isAlive();
652                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
653                 String message = StringUtils.EMPTY;
654                 String status = StringUtils.EMPTY;
655                 for (int i = 0; i < retryTimes; i++) {
656                     try {
657                         Thread.sleep(retryInterval); // 1000 milliseconds is one second.
658                     } catch (InterruptedException ex) {
659                         Thread.currentThread().interrupt();
660                     }
661                     ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
662                     ApiMethod am = cac.get(chefAction);
663                     am.execute();
664                     code = am.getReturnCode();
665                     message = am.getResponseBodyAsString();
666                     JSONObject obj = new JSONObject(message);
667                     status = obj.getString("status");
668                     if (!status.equals("running")) {
669                         logger.info(i + " time " + code + "   " + status);
670                         break;
671                     }
672                 }
673                 if (status.equals("complete")) {
674                     svcLogic.setAttribute("chefServerResult.code", "200");
675                     svcLogic.setAttribute("chefServerResult.message", message);
676                 } else {
677                     if (status.equals("running")) {
678                         svcLogic.setAttribute("chefServerResult.code", "202");
679                         svcLogic.setAttribute("chefServerResult.message", "chef client runtime out");
680                     } else {
681                         svcLogic.setAttribute("chefServerResult.code", "500");
682                         svcLogic.setAttribute("chefServerResult.message", message);
683                     }
684                 }
685             }
686             else {
687                 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
688             }
689         } catch (Exception e) {
690             code = 401;
691             doFailure(ctx, code, e.getMessage());
692         }
693     }
694
695     @SuppressWarnings("nls")
696     @Override
697     public void pushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
698         int code;
699         try {
700             chefInfo(params, ctx);
701             String pushRequest = params.get("pushRequest");
702             String chefAction = "/pushy/jobs";
703             RequestContext rc = new RequestContext(ctx);
704             rc.isAlive();
705             SvcLogicContext svcLogic = rc.getSvcLogicContext();
706             ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
707             ApiMethod am = cac.post(chefAction).body(pushRequest);
708
709             am.execute();
710             code = am.getReturnCode();
711             String message = am.getResponseBodyAsString();
712             if (code == 201) {
713                 int startIndex = message.indexOf("jobs") + 6;
714                 int endIndex = message.length() - 2;
715                 String jobID = message.substring(startIndex, endIndex);
716                 svcLogic.setAttribute("jobID", jobID);
717                 logger.info(jobID);
718             }
719             chefServerResult(rc, Integer.toString(code), message);
720         } catch (Exception e) {
721             code = 401;
722             doFailure(ctx, code, e.getMessage());
723         }
724     }
725
726     @SuppressWarnings("static-method")
727     private void doFailure(RequestContext rc, int code, String message) {
728         SvcLogicContext svcLogic = rc.getSvcLogicContext();
729         String msg = (message == null) ? Integer.toString(code) : message;
730         if (msg.contains("\n")) {
731             msg = msg.substring(msg.indexOf("\n"));
732         }
733
734         String status;
735         try {
736             status = Integer.toString(code);
737         } catch (Exception e) {
738
739             status = "500";
740         }
741         svcLogic.setAttribute("chefAgent.code", status);
742         svcLogic.setAttribute("chefAgent.message", msg);
743     }
744
745     /**
746      * @param rc
747      *        The request context that manages the state and recovery of the
748      *        request for the life of its processing.
749      */
750     @SuppressWarnings("static-method")
751     private void doSuccess(RequestContext rc) {
752         SvcLogicContext svcLogic = rc.getSvcLogicContext();
753         svcLogic.setAttribute("chefAgent.code", "200");
754     }
755
756     @SuppressWarnings("static-method")
757     private void chefServerResult(RequestContext rc, String code, String message) {
758         SvcLogicContext svcLogic = rc.getSvcLogicContext();
759         svcLogic.setStatus(OUTCOME_SUCCESS);
760         svcLogic.setAttribute("chefServerResult.code", code);
761         svcLogic.setAttribute("chefServerResult.message", message);
762         logger.info("chefServerResult.code" + svcLogic.getAttribute("chefServerResult.code"));
763         logger.info("chefServerResult.message" + svcLogic.getAttribute("chefServerResult.message"));
764     }
765
766     @SuppressWarnings("static-method")
767     private void chefClientResult(RequestContext rc, String code, String message) {
768         SvcLogicContext svcLogic = rc.getSvcLogicContext();
769         svcLogic.setStatus(OUTCOME_SUCCESS);
770         svcLogic.setAttribute("chefClientResult.code", code);
771         svcLogic.setAttribute("chefClientResult.message", message);
772         logger.info("chefClientResult.code" + svcLogic.getAttribute("chefClientResult.code"));
773         logger.info("chefClientResult.message" + svcLogic.getAttribute("chefClientResult.message"));
774     }
775
776     /**
777      * initialize the provider adapter by building the context cache
778      */
779     private void initialize() {
780
781         logger.info("Initialize Chef Adapter");
782     }
783
784     @SuppressWarnings("static-method")
785     private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
786
787         if (message.contains("\n")) {
788             message = message.substring(message.indexOf("\n"));
789         }
790         svcLogic.setStatus(OUTCOME_FAILURE);
791         svcLogic.setAttribute("chefServerResult.code", Integer.toString(code));
792         svcLogic.setAttribute("chefServerResult.message", message);
793
794         throw new SvcLogicException("Chef Adapater Error = " + message);
795     }
796 }