From 75621ce65e4eb50bc522f4337f29dca86463f386 Mon Sep 17 00:00:00 2001 From: Skip Wonnell Date: Sat, 13 Jan 2018 13:21:36 -0600 Subject: Code hardening for Ansible Bundle Fix sonar issues - Note: two public method names in AnsibleServerEmulater (Post and Get) require correction, but cannot be changed yet without a merge conflict. Format code to ONAP style Simplify code Issue-ID: APPC-401 Change-Id: Id33f47f61bd10088a2c0312bebdcd86801fabf80 Signed-off-by: Skip Wonnell --- .../ansible/model/AnsibleMessageParser.java | 201 +++++++++++---------- .../appc/adapter/ansible/model/AnsibleResult.java | 55 +++--- .../adapter/ansible/model/AnsibleResultCodes.java | 99 ++++------ .../ansible/model/AnsibleServerEmulator.java | 180 +++++++++--------- 4 files changed, 249 insertions(+), 286 deletions(-) (limited to 'appc-adapters/appc-ansible-adapter') diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java index 5457eda49..6ed57320c 100644 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleMessageParser.java @@ -9,15 +9,15 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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========================================================= */ @@ -25,18 +25,20 @@ package org.onap.appc.adapter.ansible.model; /** - * This module imples the APP-C/Ansible Server interface + * This module implements the APP-C/Ansible Server interface * based on the REST API specifications */ - -import java.util.*; - -import com.google.common.base.Strings; - -import org.json.JSONObject; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; +import org.json.JSONObject; import org.onap.appc.exceptions.APPCException; +import com.google.common.base.Strings; /** * Class that validates and constructs requests sent/received from @@ -66,16 +68,16 @@ public class AnsibleMessageParser { * a) validates if all parameters are appropriate (else, throws an exception) and * b) if correct returns a JSON object with appropriate key-value pairs to send to the server. * - * Mandatory parameters, that must be in the supplied information to the Ansible Adapter + * Mandatory parameters, that must be in the supplied information to the Ansible Adapter * 1. URL to connect to * 2. credentials for URL (assume username password for now) * 3. Playbook name * */ public JSONObject reqMessage(Map params) throws APPCException { - final String[] mandatoryTestParams = { AGENT_URL_KEY, PLAYBOOK_NAME_KEY, USER_KEY, PASS_KEY }; - final String[] optionalTestParams = { ENV_PARAMETERS_OPT_KEY, NODE_LIST_OPT_KEY, LOCAL_PARAMETERS_OPT_KEY, - TIMEOUT_OPT_KEY, VERSION_OPT_KEY, FILE_PARAMETERS_OPT_KEY, ACTION_OPT_KEY }; + final String[] mandatoryTestParams = {AGENT_URL_KEY, PLAYBOOK_NAME_KEY, USER_KEY, PASS_KEY}; + final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, NODE_LIST_OPT_KEY, LOCAL_PARAMETERS_OPT_KEY, + TIMEOUT_OPT_KEY, VERSION_OPT_KEY, FILE_PARAMETERS_OPT_KEY, ACTION_OPT_KEY}; JSONObject jsonPayload = new JSONObject(); @@ -100,7 +102,7 @@ public class AnsibleMessageParser { */ public String reqUriResult(Map params) throws APPCException { - final String[] mandatoryTestParams = { AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY }; + final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY}; for (String key : mandatoryTestParams) { throwIfMissingMandatoryParam(params, key); @@ -115,7 +117,7 @@ public class AnsibleMessageParser { */ public String reqUriOutput(Map params) throws APPCException { - final String[] mandatoryTestParams = { AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY }; + final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY}; for (String mandatoryParam : mandatoryTestParams) { throwIfMissingMandatoryParam(params, mandatoryParam); @@ -130,7 +132,7 @@ public class AnsibleMessageParser { */ public String reqUriLog(Map params) throws APPCException { - final String[] mandatoryTestParams = { AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY }; + final String[] mandatoryTestParams = {AGENT_URL_KEY, ID_KEY, USER_KEY, PASS_KEY}; for (String mandatoryParam : mandatoryTestParams) { throwIfMissingMandatoryParam(params, mandatoryParam); @@ -153,7 +155,8 @@ public class AnsibleMessageParser { int initResponseValue = AnsibleResultCodes.INITRESPONSE.getValue(); boolean validCode = AnsibleResultCodes.CODE.checkValidCode(initResponseValue, code); if (!validCode) { - throw new APPCException("Invalid InitResponse code = " + code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(initResponseValue)); + throw new APPCException("Invalid InitResponse code = " + code + " received. MUST be one of " + + AnsibleResultCodes.CODE.getValidCodes(initResponseValue)); } ansibleResult = new AnsibleResult(code, msg); @@ -168,79 +171,81 @@ public class AnsibleMessageParser { * This method parses response from an Ansible server when we do a GET for a result * and returns an AnsibleResult object. **/ - public AnsibleResult parseGetResponse(String input) throws APPCException { - - AnsibleResult ansibleResult = new AnsibleResult(); - int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue(); - - try{ - JSONObject postResponse = new JSONObject(input); - - int codeStatus = postResponse.getInt(STATUS_CODE_KEY); - String messageStatus = postResponse.getString(STATUS_MESSAGE_KEY); - - boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus); - - if(!valCode){ - throw new APPCException("Invalid FinalResponse code = " + codeStatus + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue())); - } - - ansibleResult.setStatusCode(codeStatus); - ansibleResult.setStatusMessage(messageStatus); - System.out.println("Received response with code = " + Integer.toString(codeStatus) + " Message = " + messageStatus); - - if(! postResponse.isNull("Results")){ - - // Results are available. process them - // Results is a dictionary of the form - // {host :{status:s, group:g, message:m, hostname:h}, ...} - System.out.println("Processing results in response"); - JSONObject results = postResponse.getJSONObject("Results"); - System.out.println("Get JSON dictionary from Results .."); - Iterator hosts = results.keys(); - System.out.println("Iterating through hosts"); - - while(hosts.hasNext()){ - String host = hosts.next(); - System.out.println("Processing host = " + host); - - try{ - JSONObject hostResponse = results.getJSONObject(host); - int subCode = hostResponse.getInt(STATUS_CODE_KEY); - String message = hostResponse.getString(STATUS_MESSAGE_KEY); - - System.out.println("Code = " + Integer.toString(subCode) + " Message = " + message); - - if(subCode != 200 || ! message.equals("SUCCESS")){ - finalCode = AnsibleResultCodes.REQ_FAILURE.getValue(); - } - } - catch(JSONException e){ - ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); - ansibleResult.setStatusMessage(String.format("Error processing response message = %s from host %s", results.getString(host), host)); - break; - } - } - - ansibleResult.setStatusCode(finalCode); - - // We return entire Results object as message - ansibleResult.setResults(results.toString()); - - } - else{ - ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); - ansibleResult.setStatusMessage("Results not found in GET for response"); - } - - - } - catch(JSONException e){ - ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error parsing response = " + input + ". Error = " + e.getMessage(), ""); - } - - - return ansibleResult; + public AnsibleResult parseGetResponse(String input) throws APPCException { + + AnsibleResult ansibleResult = new AnsibleResult(); + int finalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue(); + + try { + JSONObject postResponse = new JSONObject(input); + + int codeStatus = postResponse.getInt(STATUS_CODE_KEY); + String messageStatus = postResponse.getString(STATUS_MESSAGE_KEY); + + boolean valCode = + AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), codeStatus); + + if (!valCode) { + throw new APPCException("Invalid FinalResponse code = " + codeStatus + " received. MUST be one of " + + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue())); + } + + ansibleResult.setStatusCode(codeStatus); + ansibleResult.setStatusMessage(messageStatus); + System.out.println( + "Received response with code = " + Integer.toString(codeStatus) + " Message = " + messageStatus); + + if (!postResponse.isNull("Results")) { + + // Results are available. process them + // Results is a dictionary of the form + // {host :{status:s, group:g, message:m, hostname:h}, ...} + System.out.println("Processing results in response"); + JSONObject results = postResponse.getJSONObject("Results"); + System.out.println("Get JSON dictionary from Results .."); + Iterator hosts = results.keys(); + System.out.println("Iterating through hosts"); + + while (hosts.hasNext()) { + String host = hosts.next(); + System.out.println("Processing host = " + host); + + try { + JSONObject hostResponse = results.getJSONObject(host); + int subCode = hostResponse.getInt(STATUS_CODE_KEY); + String message = hostResponse.getString(STATUS_MESSAGE_KEY); + + System.out.println("Code = " + Integer.toString(subCode) + " Message = " + message); + + if (subCode != 200 || !message.equals("SUCCESS")) { + finalCode = AnsibleResultCodes.REQ_FAILURE.getValue(); + } + } catch (JSONException e) { + ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); + ansibleResult.setStatusMessage(String.format( + "Error processing response message = %s from host %s", results.getString(host), host)); + break; + } + } + + ansibleResult.setStatusCode(finalCode); + + // We return entire Results object as message + ansibleResult.setResults(results.toString()); + + } else { + ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue()); + ansibleResult.setStatusMessage("Results not found in GET for response"); + } + + + } catch (JSONException e) { + ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(), + "Error parsing response = " + input + ". Error = " + e.getMessage(), ""); + } + + + return ansibleResult; } private void parseOptionalParams(Map params, String[] optionalTestParams, JSONObject jsonPayload) { @@ -248,11 +253,13 @@ public class AnsibleMessageParser { Set optionalParamsSet = new HashSet<>(); Collections.addAll(optionalParamsSet, optionalTestParams); + //@formatter:off params.entrySet() .stream() .filter(entry -> optionalParamsSet.contains(entry.getKey())) .filter(entry -> !Strings.isNullOrEmpty(entry.getValue())) - .forEach(entry -> parseOptionalParam(entry, jsonPayload)); + .forEach(entry -> parseOptionalParam(entry, jsonPayload)); + //@formatter:on } private void parseOptionalParam(Map.Entry params, JSONObject jsonPayload) { @@ -297,10 +304,14 @@ public class AnsibleMessageParser { private void throwIfMissingMandatoryParam(Map params, String key) throws APPCException { if (!params.containsKey(key)) { - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + throw new APPCException(String.format( + "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", + key)); } if (Strings.isNullOrEmpty(params.get(key))) { - throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key)); + throw new APPCException(String.format( + "Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", + key)); } } -} \ No newline at end of file +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java index 873d88f43..066a3da27 100644 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResult.java @@ -9,30 +9,28 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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.ansible.model; - /* Simple class to store code and message returned by POST/GET to an Ansible Server */ -public class AnsibleResult{ +public class AnsibleResult { private int statusCode; private String statusMessage; private String results; - - public AnsibleResult(){ + public AnsibleResult() { this(-1, "UNKNOWN", "UNKNOWN"); } @@ -40,48 +38,39 @@ public class AnsibleResult{ this(code, message, "UNKNOWN"); } - public AnsibleResult(int code, String message, String result){ + public AnsibleResult(int code, String message, String result) { statusCode = code; statusMessage = message; results = result; } - //************************************************* - // Various set methods - public void setStatusCode(int code){ - this.statusCode = code; + public void setStatusCode(int code) { + this.statusCode = code; } - public void setStatusMessage(String message){ - this.statusMessage = message; + public void setStatusMessage(String message) { + this.statusMessage = message; } - public void setResults(String results){ - this.results = results; + public void setResults(String results) { + this.results = results; } - - - void set(int code, String message, String results){ - this.statusCode = code; - this.statusMessage = message; - this.results = results; + void set(int code, String message, String results) { + this.statusCode = code; + this.statusMessage = message; + this.results = results; } - //********************************************* - // Various get methods - public int getStatusCode(){ - return this.statusCode; + public int getStatusCode() { + return this.statusCode; } - public String getStatusMessage(){ - return this.statusMessage; + public String getStatusMessage() { + return this.statusMessage; } - public String getResults(){ - return this.results; + public String getResults() { + return this.results; } - - } - diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java index 5d44f6dae..bcc77655e 100644 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleResultCodes.java @@ -9,35 +9,38 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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.ansible.model; - -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; /** * enum of the various codes that APP-C uses to resolve different - * status of response from Ansible Server + * status of response from Ansible Server **/ -public enum AnsibleResultCodes{ +public enum AnsibleResultCodes { + // @formatter:off SUCCESS(400), KEYSTORE_EXCEPTION(622), CERTIFICATE_ERROR(610), - IO_EXCEPTION (611), + IO_EXCEPTION(611), HOST_UNKNOWN(625), USER_UNAUTHORIZED(613), UNKNOWN_EXCEPTION(699), @@ -51,72 +54,40 @@ public enum AnsibleResultCodes{ MESSAGE(1), CODE(0), INITRESPONSE(0), - FINALRESPONSE(1); - - private final Set initCodes = new HashSet(Arrays.asList(100, 101)); - private final Set finalCodes = new HashSet(Arrays.asList(200, 500)); - private final ArrayList>codeSets = new ArrayList>(Arrays.asList(initCodes, finalCodes)); - - private final Set MessageSet = new HashSet(Arrays.asList("PENDING", "FINISHED", "TERMINATED")); + FINALRESPONSE(1); + // @formatter:on + private final Set initCodes = new HashSet<>(Arrays.asList(100, 101)); + private final Set finalCodes = new HashSet<>(Arrays.asList(200, 500)); + private final ArrayList> codeSets = new ArrayList<>(Arrays.asList(initCodes, finalCodes)); + private final Set messageSet = new HashSet<>(Arrays.asList("PENDING", "FINISHED", "TERMINATED")); private final int value; - - AnsibleResultCodes(int value){ - this.value = value; - }; + AnsibleResultCodes(int value) { + this.value = value; + }; - public int getValue(){ - return this.value; + public int getValue() { + return value; } - - public boolean checkValidCode(int Type, int Code){ - SetCodeSet = codeSets.get(Type); - if (CodeSet.contains(Code)){ - return true; - } - else{ - return false; - } + public boolean checkValidCode(int type, int code) { + return codeSets.get(type).contains(code); } - - public String getValidCodes(int Type){ - SetCodeSet = codeSets.get(Type); - - Iterator iter = CodeSet.iterator(); - String ValidCodes = "[ "; - while(iter.hasNext()){ - ValidCodes = ValidCodes + iter.next().toString() + ","; - } - - ValidCodes = ValidCodes + "]"; - return ValidCodes; + public String getValidCodes(int type) { + StringBuilder sb = new StringBuilder("[ "); + codeSets.get(type).stream().forEach(s -> sb.append(s).append(",")); + return sb.append("]").toString(); } - - public boolean checkValidMessage(String Message){ - if (MessageSet.contains(Message)){ - return true; - } - else{ - return false; - } + public boolean checkValidMessage(String message) { + return messageSet.contains(message); } - - - public String getValidMessages(){ - Iterator iter = MessageSet.iterator(); - String ValidMessage = "[ "; - while(iter.hasNext()){ - ValidMessage = ValidMessage + iter.next() + ","; - } - - ValidMessage = ValidMessage + "]"; - return ValidMessage; + public String getValidMessages() { + StringBuilder sb = new StringBuilder("[ "); + messageSet.stream().forEach(s -> sb.append(s).append(",")); + return sb.append("]").toString(); } - - -}; +} diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java index 7b7d95580..ebaae20f5 100644 --- a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java +++ b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/model/AnsibleServerEmulator.java @@ -9,137 +9,129 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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========================================================= */ - -/* Class to emulate responses from the Ansible Server that is compliant with the APP-C Ansible Server - Interface. Used for jUnit tests to verify code is working. In tests it can be used - as a replacement for methods from ConnectionBuilder class -*/ +/* + * Class to emulate responses from the Ansible Server that is compliant with the APP-C Ansible Server + * Interface. Used for jUnit tests to verify code is working. In tests it can be used + * as a replacement for methods from ConnectionBuilder class + */ package org.onap.appc.adapter.ansible.model; -import java.util.*; -import java.util.regex.Pattern; import java.util.regex.Matcher; - -import org.json.JSONObject; +import java.util.regex.Pattern; +import org.apache.commons.lang.StringUtils; import org.json.JSONException; -import org.onap.appc.adapter.ansible.model.AnsibleResult; +import org.json.JSONObject; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; public class AnsibleServerEmulator { - + private final EELFLogger logger = EELFManager.getInstance().getLogger(AnsibleServerEmulator.class); + + private static final String PLAYBOOK_NAME = "PlaybookName"; + private static final String STATUS_CODE = "StatusCode"; + private static final String STATUS_MESSAGE = "StatusMessage"; + private String playbookName = "test_playbook.yaml"; - private String TestId; /** * Method that emulates the response from an Ansible Server - when presented with a request to execute a playbook - Returns an ansible object result. The response code is always the http code 200 (i.e connection successful) - payload is json string as would be sent back by Ansible Server - **/ - - public AnsibleResult Post(String AgentUrl, String payload){ - AnsibleResult result = new AnsibleResult() ; - - try{ - // Request must be a JSON object - - JSONObject message = new JSONObject(payload); - if (message.isNull("Id")){ - RejectRequest(result, "Must provide a valid Id"); - } - else if(message.isNull("PlaybookName")){ - RejectRequest(result, "Must provide a playbook Name"); - } - else if(!message.getString("PlaybookName").equals(playbookName)){ - RejectRequest(result, "Playbook " + message.getString("PlaybookName") + " not found in catalog"); - } - else{ - AcceptRequest(result); - } - } - catch (JSONException e){ - RejectRequest(result, e.getMessage()); - } - - return result; + * when presented with a request to execute a playbook + * Returns an ansible object result. The response code is always the http code 200 (i.e connection successful) + * payload is json string as would be sent back by Ansible Server + **/ + public AnsibleResult Post(String agentUrl, String payload) { + AnsibleResult result = new AnsibleResult(); + + try { + // Request must be a JSON object + + JSONObject message = new JSONObject(payload); + if (message.isNull("Id")) { + rejectRequest(result, "Must provide a valid Id"); + } else if (message.isNull(PLAYBOOK_NAME)) { + rejectRequest(result, "Must provide a playbook Name"); + } else if (!message.getString(PLAYBOOK_NAME).equals(playbookName)) { + rejectRequest(result, "Playbook " + message.getString(PLAYBOOK_NAME) + " not found in catalog"); + } else { + acceptRequest(result); + } + } catch (JSONException e) { + logger.error("JSONException caught", e); + rejectRequest(result, e.getMessage()); + } + return result; } + /** + * Method to emulate response from an Ansible + * Server when presented with a GET request + * Returns an ansibl object result. The response code is always the http code 200 (i.e connection successful) + * payload is json string as would be sent back by Ansible Server + * + **/ + public AnsibleResult Get(String agentUrl) { - /** Method to emulate response from an Ansible - Server when presented with a GET request - Returns an ansibl object result. The response code is always the http code 200 (i.e connection successful) - payload is json string as would be sent back by Ansible Server - - **/ - public AnsibleResult Get(String AgentUrl){ + Pattern pattern = Pattern.compile(".*?\\?Id=(.*?)&Type.*"); + Matcher matcher = pattern.matcher(agentUrl); + String id = StringUtils.EMPTY; + String vmAddress = "192.168.1.10"; - // Extract id - Pattern pattern = Pattern.compile(".*?\\?Id=(.*?)&Type.*"); - Matcher matcher = pattern.matcher(AgentUrl); - String Id = ""; - - if (matcher.find()){ - Id = matcher.group(1); - } + if (matcher.find()) { + id = matcher.group(1); + } - AnsibleResult get_result = new AnsibleResult(); + AnsibleResult getResult = new AnsibleResult(); - JSONObject response = new JSONObject(); - response.put("StatusCode", 200); - response.put("StatusMessage", "FINISHED"); + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, 200); + response.put(STATUS_MESSAGE, "FINISHED"); - JSONObject results = new JSONObject(); + JSONObject results = new JSONObject(); - JSONObject vm_results = new JSONObject(); - vm_results.put("StatusCode", 200); - vm_results.put("StatusMessage", "SUCCESS"); - vm_results.put("Id", Id); - results.put("192.168.1.10", vm_results); - + JSONObject vmResults = new JSONObject(); + vmResults.put(STATUS_CODE, 200); + vmResults.put(STATUS_MESSAGE, "SUCCESS"); + vmResults.put("Id", id); + results.put(vmAddress, vmResults); - response.put("Results", results); + response.put("Results", results); - get_result.setStatusCode(200); - get_result.setStatusMessage(response.toString()); + getResult.setStatusCode(200); + getResult.setStatusMessage(response.toString()); - return get_result; - + return getResult; } - - private void RejectRequest(AnsibleResult result, String Message){ - result.setStatusCode(200); - JSONObject response = new JSONObject(); - response.put("StatusCode", AnsibleResultCodes.REJECTED.getValue()); - response.put("StatusMessage", Message); - result.setStatusMessage(response.toString()); - + private void rejectRequest(AnsibleResult result, String Message) { + result.setStatusCode(200); + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, AnsibleResultCodes.REJECTED.getValue()); + response.put(STATUS_MESSAGE, Message); + result.setStatusMessage(response.toString()); } - private void AcceptRequest(AnsibleResult result){ - result.setStatusCode(200); - JSONObject response = new JSONObject(); - response.put("StatusCode", AnsibleResultCodes.PENDING.getValue()); - response.put("StatusMessage", "PENDING"); - result.setStatusMessage(response.toString()); - + private void acceptRequest(AnsibleResult result) { + result.setStatusCode(200); + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, AnsibleResultCodes.PENDING.getValue()); + response.put(STATUS_MESSAGE, "PENDING"); + result.setStatusMessage(response.toString()); } - -}; - +} \ No newline at end of file -- cgit 1.2.3-korg