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