ChefAdapterImpl junits
[appc.git] / appc-adapters / appc-chef-adapter / appc-chef-adapter-bundle / src / main / java / org / onap / appc / adapter / chef / impl / ChefAdapterImpl.java
index 90691d1..64aedcc 100644 (file)
  */
 package org.onap.appc.adapter.chef.impl;
 
-import java.io.File;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
-import java.util.Properties;
+import java.util.Optional;
 import org.apache.commons.lang.StringUtils;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.util.EntityUtils;
 import org.json.JSONException;
 import org.json.JSONObject;
 import org.onap.appc.adapter.chef.ChefAdapter;
-import org.onap.appc.adapter.chef.chefapi.ApiMethod;
-import org.onap.appc.adapter.chef.chefclient.ChefApiClient;
+import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
+import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
+import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
 
 /**
- * This class implements the {@link ChefAdapter} interface. This interface
- * defines the behaviors that our service provides.
+ * This class implements the {@link ChefAdapter} interface. This interface defines the behaviors that our service
+ * provides.
  */
 public class ChefAdapterImpl implements ChefAdapter {
 
@@ -98,7 +92,7 @@ public class ChefAdapterImpl implements ChefAdapter {
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
 
     private static final String CANNOT_FIND_PRIVATE_KEY_STR =
-            "Cannot find the private key in the APPC file system, please load the private key to ";
+        "Cannot find the private key in the APPC file system, please load the private key to ";
 
     private static final String POSTING_REQUEST_JSON_ERROR_STR = "Error posting request due to invalid JSON block: ";
     private static final String POSTING_REQUEST_ERROR_STR = "Error posting request: ";
@@ -108,87 +102,59 @@ public class ChefAdapterImpl implements ChefAdapter {
     private static final String CHEF_SERVER_RESULT_MSG_STR = "chefServerResult.message";
     private static final String CHEF_ACTION_STR = "chefAction";
     private static final String NODE_LIST_STR = "NodeList";
+    private final ChefApiClientFactory chefApiClientFactory;
+    private final PrivateKeyChecker privateKeyChecker;
 
-    /**
-     * This default constructor is used as a work around because the activator wasnt
-     * getting called
-     */
-    public ChefAdapterImpl() {
-        initialize();
-    }
-
-    public ChefAdapterImpl(Properties props) {
-        initialize();
-    }
-
-    /**
-     * This constructor is used primarily in the test cases to bypass initialization
-     * of the adapter for isolated, disconnected testing
-     *
-     * @param initialize
-     *        True if the adapter is to be initialized, can false if not
-     */
-
-    public ChefAdapterImpl(boolean initialize) {
-        if (initialize) {
-            initialize();
-        }
-    }
-
-    public ChefAdapterImpl(String key) {
-        initialize();
+    ChefAdapterImpl(ChefApiClientFactory chefApiClientFactory, PrivateKeyChecker privateKeyChecker) {
+        this.chefApiClientFactory = chefApiClientFactory;
+        this.privateKeyChecker = privateKeyChecker;
+        logger.info("Initialize Chef Adapter");
     }
 
     @SuppressWarnings("nls")
     @Override
     public void vnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
         int code;
-        try {
-            logger.info("environment of VNF-C");
-            chefInfo(params, ctx);
-            RequestContext rc = new RequestContext(ctx);
-            logger.info("Context" + ctx);
-            rc.isAlive();
-            String env = params.get("Environment");
-            logger.info("Environmnet" + env);
-            if (env.equals(StringUtils.EMPTY)) {
-                chefServerResult(rc, 200, "Skip Environment block ");
-            } else {
-                JSONObject envJ = new JSONObject(env);
-                String envName = envJ.getString("name");
-                String message;
-                if (privateKeyCheck()) {
+        logger.info("environment of VNF-C");
+        chefInfo(params, ctx);
+        String env = params.get("Environment");
+        logger.info("Environmnet" + env);
+        if (env.equals(StringUtils.EMPTY)) {
+            chefServerResult(ctx, 200, "Skip Environment block ");
+        } else {
+            String message;
+            if (privateKeyChecker.doesExist(clientPrivatekey)) {
+                try {
+                    JSONObject envJ = new JSONObject(env);
+                    String envName = envJ.getString("name");
                     // update the details of an environment on the Chef server.
-                    ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
-                    ApiMethod am = cac.put("/environments/" + envName).body(env);
-                    am.execute();
-                    code = am.getReturnCode();
-                    message = am.getResponseBodyAsString();
+                    ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
+                    ChefResponse chefResponse = chefApiClient.put("/environments/" + envName, env);
+                    code = chefResponse.getStatusCode();
+                    message = chefResponse.getBody();
                     if (code == 404) {
                         // need create a new environment
-                        am = cac.post("/environments").body(env);
-                        am.execute();
-                        code = am.getReturnCode();
-                        message = am.getResponseBodyAsString();
-                        logger.info("requestbody" + am.getReqBody());
+                        chefResponse = chefApiClient.post("/environments", env);
+                        code = chefResponse.getStatusCode();
+                        message = chefResponse.getBody();
+                        logger.info("requestbody {}", chefResponse.getBody());
                     }
-
-                } else {
-                    code = 500;
-                    message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
-                    doFailure(ctx, code, message);
+                    chefServerResult(ctx, code, message);
+                } catch (JSONException e) {
+                    code = 401;
+                    logger.error(POSTING_REQUEST_JSON_ERROR_STR, e);
+                    doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
+                } catch (Exception e) {
+                    code = 401;
+                    logger.error(POSTING_REQUEST_ERROR_STR, e);
+                    doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
                 }
-                chefServerResult(rc, code, message);
+            } else {
+                code = 500;
+                message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
+                doFailure(ctx, code, message);
             }
         }
-
-        catch (JSONException e) {
-            code = 401;
-            doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
-        } catch (Exception e) {
-            code = 401;
-            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
-        }
     }
 
     @SuppressWarnings("nls")
@@ -206,24 +172,20 @@ public class ChefAdapterImpl implements ChefAdapter {
                 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
                 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
                 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
-                RequestContext rc = new RequestContext(ctx);
-                rc.isAlive();
                 code = 200;
                 String message = null;
-                if (privateKeyCheck()) {
-                    ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                if (privateKeyChecker.doesExist(clientPrivatekey)) {
+                    ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
 
-                    for (int i = 0; i < nodes.size(); i++) {
-                        String nodeName = nodes.get(i);
+                    for (String nodeName: nodes) {
                         JSONObject nodeJ = new JSONObject(nodeS);
                         nodeJ.remove("name");
                         nodeJ.put("name", nodeName);
                         String nodeObject = nodeJ.toString();
                         logger.info(nodeObject);
-                        ApiMethod am = cac.put("/nodes/" + nodeName).body(nodeObject);
-                        am.execute();
-                        code = am.getReturnCode();
-                        message = am.getResponseBodyAsString();
+                        ChefResponse chefResponse = cac.put("/nodes/" + nodeName, nodeObject);
+                        code = chefResponse.getStatusCode();
+                        message = chefResponse.getBody();
                         if (code != 200) {
                             break;
                         }
@@ -233,17 +195,18 @@ public class ChefAdapterImpl implements ChefAdapter {
                     message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
                     doFailure(ctx, code, message);
                 }
-                chefServerResult(rc, code, message);
-            }
-            else {
+                chefServerResult(ctx, code, message);
+            } else {
                 throw new SvcLogicException("Missing Mandatory param(s) Node , NodeList ");
             }
         } catch (JSONException e) {
             code = 401;
+            logger.error(POSTING_REQUEST_JSON_ERROR_STR, e);
             doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
-        } catch (Exception ex) {
+        } catch (Exception e) {
             code = 401;
-            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + ex.getMessage());
+            logger.error(POSTING_REQUEST_ERROR_STR, e);
+            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
         }
     }
 
@@ -262,40 +225,32 @@ public class ChefAdapterImpl implements ChefAdapter {
                     String requestId = params.get("RequestId");
                     String callbackUrl = params.get("CallbackUrl");
                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
-                            + nodeList + "," + "\"env\": {\"RequestId\": \"" + requestId + "\", \"CallbackUrl\": \""
-                            + callbackUrl + "\"}," + "\"capture_output\": true" + "}";
+                        + nodeList + "," + "\"env\": {\"RequestId\": \"" + requestId + "\", \"CallbackUrl\": \""
+                        + callbackUrl + "\"}," + "\"capture_output\": true" + "}";
                 } else {
                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
-                            + nodeList + "," + "\"env\": {}," + "\"capture_output\": true" + "}";
+                        + nodeList + "," + "\"env\": {}," + "\"capture_output\": true" + "}";
                 }
-                RequestContext rc = new RequestContext(ctx);
-
-                rc.isAlive();
-                SvcLogicContext svcLogic = rc.getSvcLogicContext();
-                ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
-                ApiMethod am = cac.post(chefAction).body(pushRequest);
-                am.execute();
-                code = am.getReturnCode();
+                ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
+                ChefResponse chefResponse = cac.post(chefAction, pushRequest);
+                code = chefResponse.getStatusCode();
                 logger.info("pushRequest:" + pushRequest);
-                logger.info("requestbody:" + am.getReqBody());
-                String message = am.getResponseBodyAsString();
+                logger.info("requestbody: {}", chefResponse.getBody());
+                String message = chefResponse.getBody();
                 if (code == 201) {
                     int startIndex = message.indexOf("jobs") + 5;
                     int endIndex = message.length() - 2;
                     String jobID = message.substring(startIndex, endIndex);
-                    svcLogic.setAttribute("jobID", jobID);
+                    ctx.setAttribute("jobID", jobID);
                     logger.info(jobID);
                 }
-                chefServerResult(rc, code, message);
-            }
-            else {
+                chefServerResult(ctx, code, message);
+            } else {
                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
             }
-        } catch (JSONException e) {
-            code = 401;
-            doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
         } catch (Exception e) {
             code = 401;
+            logger.error(POSTING_REQUEST_ERROR_STR, e);
             doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
         }
     }
@@ -319,10 +274,10 @@ public class ChefAdapterImpl implements ChefAdapter {
                 for (String node : nodes) {
                     String chefAction = "/nodes/" + node;
                     String message;
-                    if (privateKeyCheck()) {
-                        ApiMethod am = getApiMethod(chefAction);
-                        code = am.getReturnCode();
-                        message = am.getResponseBodyAsString();
+                    if (privateKeyChecker.doesExist(clientPrivatekey)) {
+                        ChefResponse chefResponse = getApiMethod(chefAction);
+                        code = chefResponse.getStatusCode();
+                        message = chefResponse.getBody();
                     } else {
                         code = 500;
                         message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
@@ -334,12 +289,13 @@ public class ChefAdapterImpl implements ChefAdapter {
                         allNodeData = allNodeData.getJSONObject("normal");
                         String attribute = "PushJobOutput";
 
-                        String resultData = allNodeData.optString(attribute);
+                        String resultData = allNodeData.optString(attribute, null);
                         if (resultData == null) {
-                            resultData = allNodeData.optJSONObject(attribute).toString();
-
+                            resultData = Optional.ofNullable(allNodeData.optJSONObject(attribute))
+                                .map(p -> p.toString()).orElse(null);
                             if (resultData == null) {
-                                resultData = allNodeData.optJSONArray(attribute).toString();
+                                resultData = Optional.ofNullable(allNodeData.optJSONArray(attribute))
+                                    .map(p -> p.toString()).orElse(null);
 
                                 if (resultData == null) {
                                     code = 500;
@@ -359,25 +315,24 @@ public class ChefAdapterImpl implements ChefAdapter {
                     }
                 }
 
-                RequestContext rc = new RequestContext(ctx);
-                rc.isAlive();
-                chefServerResult(rc, code, returnMessage);
+                chefServerResult(ctx, code, returnMessage);
             } else {
                 throw new SvcLogicException("Missing Mandatory param(s)  NodeList ");
             }
         } catch (JSONException e) {
             code = 401;
+            logger.error(POSTING_REQUEST_JSON_ERROR_STR, e);
             doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
-        } catch (Exception ex) {
+        } catch (Exception e) {
             code = 401;
-            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + ex.getMessage());
+            logger.error(POSTING_REQUEST_ERROR_STR , e);
+            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
         }
     }
 
-    private ApiMethod getApiMethod(String chefAction) {
-        ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
-
-        return cac.get(chefAction).execute();
+    private ChefResponse getApiMethod(String chefAction) {
+        ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
+        return cac.get(chefAction);
     }
 
     /**
@@ -394,20 +349,15 @@ public class ChefAdapterImpl implements ChefAdapter {
         String runList = params.get("nodeobject.run_list");
         String chefEnvironment = params.get("nodeobject.chef_environment");
         String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
-                + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
-                + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
-                + chefEnvironment + "\"}";
+            + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
+            + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
+            + chefEnvironment + "\",}";
         logger.info(nodeObject);
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        svcLogic.setAttribute("chef.nodeObject", nodeObject);
+        ctx.setAttribute("chef.nodeObject", nodeObject);
     }
 
     /**
      * send get request to chef server
-     * 
-     * @throws SvcLogicException
      */
     private void chefInfo(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
 
@@ -415,7 +365,7 @@ public class ChefAdapterImpl implements ChefAdapter {
         serverAddress = params.get("serverAddress");
         organizations = params.get("organizations");
         if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(serverAddress)
-                && StringUtils.isNotBlank(organizations)) {
+            && StringUtils.isNotBlank(organizations)) {
             chefserver = "https://" + serverAddress + "/organizations/" + organizations;
             clientPrivatekey = "/opt/onap/appc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
             logger.info(" clientPrivatekey  " + clientPrivatekey);
@@ -424,40 +374,30 @@ public class ChefAdapterImpl implements ChefAdapter {
         }
     }
 
-    private Boolean privateKeyCheck() {
-        File f = new File(clientPrivatekey);
-        if (f.exists()) {
-            logger.info("Key exists");
-            return true;
-        } else {
-            logger.info("Key doesn't exists");
-            return false;
-        }
-    }
-
     @SuppressWarnings("nls")
     @Override
     public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
-        String contextData;
         String allConfigData = params.get("allConfig");
         String key = params.get("key");
         String dgContext = params.get("dgContext");
-        JSONObject josnConfig = new JSONObject(allConfigData);
+        JSONObject jsonConfig = new JSONObject(allConfigData);
+        String contextData = fetchContextData(key, jsonConfig);
+
+        ctx.setAttribute(dgContext, contextData);
+    }
 
+    private String fetchContextData(String key, JSONObject jsonConfig) {
         try {
-            contextData = josnConfig.getString(key);
+            return jsonConfig.getString(key);
         } catch (Exception e) {
+            logger.error("Failed getting string value corresponding to " + key + ". Trying to fetch nested json object", e);
             try {
-                contextData = josnConfig.getJSONObject(key).toString();
+                return jsonConfig.getJSONObject(key).toString();
             } catch (Exception ex) {
-                contextData = josnConfig.getJSONArray(key).toString();
+                logger.error("Failed getting json object corresponding to " + key + ". Trying to fetch array", ex);
+                return jsonConfig.getJSONArray(key).toString();
             }
         }
-
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        svcLogic.setAttribute(dgContext, contextData);
     }
 
     @SuppressWarnings("nls")
@@ -467,16 +407,11 @@ public class ChefAdapterImpl implements ChefAdapter {
         String string2 = params.get("String2");
         String dgContext = params.get("dgContext");
         String contextData = string1 + string2;
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        svcLogic.setAttribute(dgContext, contextData);
+        ctx.setAttribute(dgContext, contextData);
     }
 
     /**
      * Send GET request to chef server
-     * 
-     * @throws SvcLogicException
      */
     @SuppressWarnings("nls")
 
@@ -485,26 +420,22 @@ public class ChefAdapterImpl implements ChefAdapter {
         logger.info("chef get method");
         chefInfo(params, ctx);
         String chefAction = params.get(CHEF_ACTION_STR);
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
         int code;
         String message;
 
-        if (privateKeyCheck()) {
-            ApiMethod am = getApiMethod(chefAction);
-            code = am.getReturnCode();
-            message = am.getResponseBodyAsString();
+        if (privateKeyChecker.doesExist(clientPrivatekey)) {
+            ChefResponse chefResponse = getApiMethod(chefAction);
+            code = chefResponse.getStatusCode();
+            message = chefResponse.getBody();
         } else {
             code = 500;
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
      * Send PUT request to chef server
-     * 
-     * @throws SvcLogicException
      */
     @SuppressWarnings("nls")
 
@@ -513,29 +444,24 @@ public class ChefAdapterImpl implements ChefAdapter {
         chefInfo(params, ctx);
         String chefAction = params.get(CHEF_ACTION_STR);
         String chefNodeStr = params.get("chefRequestBody");
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
         int code;
         String message;
-        if (privateKeyCheck()) {
-            ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+        if (privateKeyChecker.doesExist(clientPrivatekey)) {
+            ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
 
-            ApiMethod am = cac.put(chefAction).body(chefNodeStr);
-            am.execute();
-            code = am.getReturnCode();
-            message = am.getResponseBodyAsString();
+            ChefResponse chefResponse = chefApiClient.put(chefAction, chefNodeStr);
+            code = chefResponse.getStatusCode();
+            message = chefResponse.getBody();
         } else {
             code = 500;
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
         logger.info(code + "   " + message);
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
      * send Post request to chef server
-     * 
-     * @throws SvcLogicException
      */
     @Override
     public void chefPost(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
@@ -545,76 +471,64 @@ public class ChefAdapterImpl implements ChefAdapter {
         String chefNodeStr = params.get("chefRequestBody");
         String chefAction = params.get(CHEF_ACTION_STR);
 
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
         int code;
         String message;
         // should load pem from somewhere else
-        if (privateKeyCheck()) {
-            ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+        if (privateKeyChecker.doesExist(clientPrivatekey)) {
+            ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
 
             // need pass path into it
             // "/nodes/testnode"
-            ApiMethod am = cac.post(chefAction).body(chefNodeStr);
-            am.execute();
-            code = am.getReturnCode();
-            message = am.getResponseBodyAsString();
+            ChefResponse chefResponse = chefApiClient.post(chefAction, chefNodeStr);
+            code = chefResponse.getStatusCode();
+            message = chefResponse.getBody();
         } else {
             code = 500;
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
         logger.info(code + "   " + message);
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
      * send delete request to chef server
-     * 
-     * @throws SvcLogicException
      */
     @Override
     public void chefDelete(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
         logger.info("chef delete method");
         chefInfo(params, ctx);
         String chefAction = params.get(CHEF_ACTION_STR);
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
         int code;
         String message;
-        if (privateKeyCheck()) {
-            ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
-            ApiMethod am = cac.delete(chefAction);
-            am.execute();
-            code = am.getReturnCode();
-            message = am.getResponseBodyAsString();
+        if (privateKeyChecker.doesExist(clientPrivatekey)) {
+            ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
+            ChefResponse chefResponse = chefApiClient.delete(chefAction);
+            code = chefResponse.getStatusCode();
+            message = chefResponse.getBody();
         } else {
             code = 500;
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
         logger.info(code + "   " + message);
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
      * Trigger target vm run chef
      */
     @Override
-    public void trigger(Map<String, String> params, SvcLogicContext ctx) {
+    public void trigger(Map<String, String> params, SvcLogicContext svcLogicContext) {
         logger.info("Run trigger method");
         String tVmIp = params.get("ip");
-        RequestContext rc = new RequestContext(ctx);
-        rc.isAlive();
-
-        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
-            HttpGet httpGet = new HttpGet(tVmIp);
-            HttpResponse response = httpClient.execute(httpGet);
-            int responseCode = response.getStatusLine().getStatusCode();
-            HttpEntity entity = response.getEntity();
-            String responseOutput = EntityUtils.toString(entity);
-            chefClientResult(rc, responseCode, responseOutput);
-            doSuccess(rc);
+
+        try {
+            ChefResponse chefResponse = chefApiClientFactory.create(tVmIp).get("");
+            chefClientResult(svcLogicContext, chefResponse.getStatusCode(), chefResponse.getBody());
+            svcLogicContext.setAttribute("chefAgent.code", "200");
         } catch (Exception e) {
-            doFailure(rc, 500, e.toString());
+            logger.error("An error occurred when executing trigger method", e);
+            svcLogicContext.setAttribute("chefAgent.code", "500");
+            svcLogicContext.setAttribute("chefAgent.message", e.toString());
         }
     }
 
@@ -627,23 +541,20 @@ public class ChefAdapterImpl implements ChefAdapter {
             String jobID = params.get("jobid");
             String retry = params.get("retryTimes");
             String intrva = params.get("retryInterval");
-            if (StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
+            if (StringUtils.isNotBlank(jobID) && StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
 
                 int retryTimes = Integer.parseInt(params.get("retryTimes"));
                 int retryInterval = Integer.parseInt(params.get("retryInterval"));
 
                 String chefAction = "/pushy/jobs/" + jobID;
 
-                RequestContext rc = new RequestContext(ctx);
-                rc.isAlive();
-                SvcLogicContext svcLogic = rc.getSvcLogicContext();
                 String message = StringUtils.EMPTY;
                 String status = StringUtils.EMPTY;
                 for (int i = 0; i < retryTimes; i++) {
                     sleepFor(retryInterval);
-                    ApiMethod am = getApiMethod(chefAction);
-                    code = am.getReturnCode();
-                    message = am.getResponseBodyAsString();
+                    ChefResponse chefResponse = getApiMethod(chefAction);
+                    code = chefResponse.getStatusCode();
+                    message = chefResponse.getBody();
                     JSONObject obj = new JSONObject(message);
                     status = obj.getString("status");
                     if (!"running".equals(status)) {
@@ -651,28 +562,30 @@ public class ChefAdapterImpl implements ChefAdapter {
                         break;
                     }
                 }
-                if ("complete".equals(status)) {
-                    svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "200");
-                    svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
-                } else {
-                    if ("running".equals(status)) {
-                        svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "202");
-                        svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, "chef client runtime out");
-                    } else {
-                        svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "500");
-                        svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
-                    }
-                }
-            }
-            else {
+                resolveSvcLogicAttributes(ctx, message, status);
+            } else {
                 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
             }
         } catch (Exception e) {
             code = 401;
+            logger.error("An error occurred when executing checkPushJob method", e);
             doFailure(ctx, code, e.getMessage());
         }
     }
 
+    private void resolveSvcLogicAttributes(SvcLogicContext svcLogic, String message, String status) {
+        if ("complete".equals(status)) {
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "200");
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
+        } else if ("running".equals(status)) {
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "202");
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, "chef client runtime out");
+        } else {
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "500");
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
+        }
+    }
+
     private void sleepFor(int retryInterval) {
         try {
             Thread.sleep(retryInterval); // 1000 milliseconds is one second.
@@ -689,89 +602,46 @@ public class ChefAdapterImpl implements ChefAdapter {
             chefInfo(params, ctx);
             String pushRequest = params.get("pushRequest");
             String chefAction = "/pushy/jobs";
-            RequestContext rc = new RequestContext(ctx);
-            rc.isAlive();
-            SvcLogicContext svcLogic = rc.getSvcLogicContext();
-            ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
-            ApiMethod am = cac.post(chefAction).body(pushRequest);
-
-            am.execute();
-            code = am.getReturnCode();
-            String message = am.getResponseBodyAsString();
+            ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
+            ChefResponse chefResponse = chefApiClient.post(chefAction, pushRequest);
+
+            code = chefResponse.getStatusCode();
+            String message = chefResponse.getBody();
             if (code == 201) {
                 int startIndex = message.indexOf("jobs") + 6;
                 int endIndex = message.length() - 2;
                 String jobID = message.substring(startIndex, endIndex);
-                svcLogic.setAttribute("jobID", jobID);
+                ctx.setAttribute("jobID", jobID);
                 logger.info(jobID);
             }
-            chefServerResult(rc, code, message);
+            chefServerResult(ctx, code, message);
         } catch (Exception e) {
             code = 401;
+            logger.error("An error occurred when executing pushJob method", e);
             doFailure(ctx, code, e.getMessage());
         }
     }
 
     @SuppressWarnings("static-method")
-    private void doFailure(RequestContext rc, int code, String message) {
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        String msg = (message == null) ? Integer.toString(code) : message;
-        if (msg.contains("\n")) {
-            msg = msg.substring(msg.indexOf("\n"));
-        }
-
-        String status;
-        try {
-            status = Integer.toString(code);
-        } catch (Exception e) {
-
-            status = "500";
-        }
-        svcLogic.setAttribute("chefAgent.code", status);
-        svcLogic.setAttribute("chefAgent.message", msg);
-    }
-
-    /**
-     * @param rc
-     *        The request context that manages the state and recovery of the
-     *        request for the life of its processing.
-     */
-    @SuppressWarnings("static-method")
-    private void doSuccess(RequestContext rc) {
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        svcLogic.setAttribute("chefAgent.code", "200");
-    }
-
-    @SuppressWarnings("static-method")
-    private void chefServerResult(RequestContext rc, int  code, String message) {
-      initSvcLogic(rc, code, message, "server");
+    private void chefServerResult(SvcLogicContext svcLogicContext, int code, String message) {
+        initSvcLogic(svcLogicContext, code, message, "server");
     }
 
     @SuppressWarnings("static-method")
-    private void chefClientResult(RequestContext rc, int code, String message) {
-        initSvcLogic(rc, code, message, "client");
+    private void chefClientResult(SvcLogicContext svcLogicContext, int code, String message) {
+        initSvcLogic(svcLogicContext, code, message, "client");
     }
 
-    private void initSvcLogic(RequestContext rc, int code, String message, String target) {
+    private void initSvcLogic(SvcLogicContext svcLogicContext, int code, String message, String target) {
 
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
         String codeStr = "server".equals(target) ? CHEF_SERVER_RESULT_CODE_STR : CHEF_CLIENT_RESULT_CODE_STR;
-        String messageStr = "client".equals(target) ? CHEF_SERVER_RESULT_MSG_STR : CHEF_CLIENT_RESULT_MSG_STR;
-
-        svcLogic.setStatus(OUTCOME_SUCCESS);
-        svcLogic.setAttribute(codeStr, Integer.toString(code));
-        svcLogic.setAttribute(messageStr, message);
-        logger.info(codeStr + ": " + svcLogic.getAttribute(codeStr));
-        logger.info(messageStr + ": " + svcLogic.getAttribute(messageStr));
-    }
+        String messageStr = "client".equals(target) ? CHEF_CLIENT_RESULT_MSG_STR : CHEF_SERVER_RESULT_MSG_STR;
 
-
-    /**
-     * initialize the provider adapter by building the context cache
-     */
-    private void initialize() {
-
-        logger.info("Initialize Chef Adapter");
+        svcLogicContext.setStatus(OUTCOME_SUCCESS);
+        svcLogicContext.setAttribute(codeStr, Integer.toString(code));
+        svcLogicContext.setAttribute(messageStr, message);
+        logger.info(codeStr + ": " + svcLogicContext.getAttribute(codeStr));
+        logger.info(messageStr + ": " + svcLogicContext.getAttribute(messageStr));
     }
 
     @SuppressWarnings("static-method")
@@ -785,4 +655,4 @@ public class ChefAdapterImpl implements ChefAdapter {
 
         throw new SvcLogicException("Chef Adapter error:" + cutMessage);
     }
-}
+}
\ No newline at end of file