Fixes for Chef Adapter bundle
[appc.git] / appc-adapters / appc-chef-adapter / appc-chef-adapter-bundle / src / main / java / org / onap / appc / adapter / chef / impl / ChefAdapterImpl.java
index 0f4b8c8..bd367b0 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP : APPC
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Copyright (C) 2017 Amdocs
  * =============================================================================
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  * ============LICENSE_END=========================================================
  */
 package org.onap.appc.adapter.chef.impl;
 
+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.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.chefclient.api.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
@@ -120,21 +113,18 @@ public class ChefAdapterImpl implements ChefAdapter {
     @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 (privateKeyChecker.doesExist(clientPrivatekey)) {
+        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 chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
                     ChefResponse chefResponse = chefApiClient.put("/environments/" + envName, env);
@@ -147,22 +137,21 @@ public class ChefAdapterImpl implements ChefAdapter {
                         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 + "vnfcEnvironment", e);
+                    doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcEnvironment"+ 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;
-            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());
         }
     }
 
@@ -181,8 +170,6 @@ 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 (privateKeyChecker.doesExist(clientPrivatekey)) {
@@ -206,18 +193,18 @@ public class ChefAdapterImpl implements ChefAdapter {
                     message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
                     doFailure(ctx, code, message);
                 }
-                chefServerResult(rc, code, message);
+                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());
+            logger.error(POSTING_REQUEST_JSON_ERROR_STR +"vnfcNodeobjects", e);
+            doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR +"vnfcNodeobjects" + e.getMessage());
         } catch (Exception e) {
             code = 401;
-            logger.error(POSTING_REQUEST_ERROR_STR, e);
-            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
+            logger.error(POSTING_REQUEST_ERROR_STR +"vnfcNodeobjects", e);
+            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR +"vnfcNodeobjects"+ e.getMessage());
         }
     }
 
@@ -242,10 +229,6 @@ public class ChefAdapterImpl implements ChefAdapter {
                     pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
                         + nodeList + "," + "\"env\": {}," + "\"capture_output\": true" + "}";
                 }
-                RequestContext rc = new RequestContext(ctx);
-
-                rc.isAlive();
-                SvcLogicContext svcLogic = rc.getSvcLogicContext();
                 ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
                 ChefResponse chefResponse = cac.post(chefAction, pushRequest);
                 code = chefResponse.getStatusCode();
@@ -256,21 +239,17 @@ public class ChefAdapterImpl implements ChefAdapter {
                     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);
+                chefServerResult(ctx, code, message);
             } 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 e) {
             code = 401;
-            logger.error(POSTING_REQUEST_ERROR_STR, e);
-            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
+            logger.error(POSTING_REQUEST_ERROR_STR + "vnfcPushJob", e);
+            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcPushJob"+ e.getMessage());
         }
     }
 
@@ -308,12 +287,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;
@@ -333,20 +313,18 @@ 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());
+            logger.error(POSTING_REQUEST_JSON_ERROR_STR + "fetchResults", e);
+            doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + "fetchResults" + e.getMessage());
         } catch (Exception e) {
             code = 401;
-            logger.error(POSTING_REQUEST_ERROR_STR , e);
-            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + e.getMessage());
+            logger.error(POSTING_REQUEST_ERROR_STR + "fetchResults" , e);
+            doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "fetchResults"+ e.getMessage());
         }
     }
 
@@ -402,7 +380,6 @@ public class ChefAdapterImpl implements ChefAdapter {
         String dgContext = params.get("dgContext");
         JSONObject jsonConfig = new JSONObject(allConfigData);
         String contextData = fetchContextData(key, jsonConfig);
-
         ctx.setAttribute(dgContext, contextData);
     }
 
@@ -440,8 +417,6 @@ 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;
 
@@ -453,7 +428,7 @@ public class ChefAdapterImpl implements ChefAdapter {
             code = 500;
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
@@ -466,8 +441,6 @@ 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 (privateKeyChecker.doesExist(clientPrivatekey)) {
@@ -481,7 +454,7 @@ public class ChefAdapterImpl implements ChefAdapter {
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
         logger.info(code + "   " + message);
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
@@ -495,8 +468,6 @@ 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
@@ -513,7 +484,7 @@ public class ChefAdapterImpl implements ChefAdapter {
             message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
         }
         logger.info(code + "   " + message);
-        chefServerResult(rc, code, message);
+        chefServerResult(ctx, code, message);
     }
 
     /**
@@ -524,8 +495,6 @@ public class ChefAdapterImpl implements ChefAdapter {
         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 (privateKeyChecker.doesExist(clientPrivatekey)) {
@@ -538,30 +507,25 @@ public class ChefAdapterImpl implements ChefAdapter {
             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, organizations).get("");
+            chefClientResult(svcLogicContext, chefResponse.getStatusCode(), chefResponse.getBody());
+            svcLogicContext.setAttribute("chefAgent.code", "200");
         } catch (Exception e) {
             logger.error("An error occurred when executing trigger method", e);
-            doFailure(rc, 500, e.toString());
+            svcLogicContext.setAttribute("chefAgent.code", "500");
+            svcLogicContext.setAttribute("chefAgent.message", e.toString());
         }
     }
 
@@ -574,16 +538,13 @@ 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++) {
@@ -598,7 +559,7 @@ public class ChefAdapterImpl implements ChefAdapter {
                         break;
                     }
                 }
-                resolveSvcLogicAttributes(svcLogic, message, status);
+                resolveSvcLogicAttributes(ctx, message, status);
             } else {
                 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
             }
@@ -613,14 +574,12 @@ public class ChefAdapterImpl implements ChefAdapter {
         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 {
-            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);
-            }
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, "500");
+            svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
         }
     }
 
@@ -640,9 +599,6 @@ 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 chefApiClient = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
             ChefResponse chefResponse = chefApiClient.post(chefAction, pushRequest);
 
@@ -652,10 +608,10 @@ public class ChefAdapterImpl implements ChefAdapter {
                 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);
@@ -664,54 +620,25 @@ public class ChefAdapterImpl implements ChefAdapter {
     }
 
     @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";
-            logger.error("Parsing status code failed. Setting it to \"500\"", e);
-        }
-        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_CLIENT_RESULT_MSG_STR : CHEF_SERVER_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));
+        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")