use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.
the class CreateAppService method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
final void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
response.setContentType("text/html;charset=UTF-8");
String charset = request.getCharacterEncoding();
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
// Parameter that needs to be secured --> We SECURE+DECODE them
String service = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("service"), null, charset);
String group = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("group"), "", charset);
String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
String attachementurl = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("attachementurl"), "", charset);
String operation = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("operation"), "", charset);
String application = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), null, charset);
String type = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("type"), "", charset);
String method = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("method"), "", charset);
// Parameter that we cannot secure as we need the html --> We DECODE them
String servicePath = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("servicePath"), "", charset);
String serviceRequest = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("serviceRequest"), null, charset);
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(service)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "SoapLibrary").replace("%OPERATION%", "Create").replace("%REASON%", "SoapLibrary name is missing!"));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
appServiceService = appContext.getBean(IAppServiceService.class);
appServiceFactory = appContext.getBean(IFactoryAppService.class);
appServiceHeaderService = appContext.getBean(IAppServiceHeaderService.class);
appServiceContentService = appContext.getBean(IAppServiceContentService.class);
appServiceContentFactory = appContext.getBean(IFactoryAppServiceContent.class);
appServiceHeaderFactory = appContext.getBean(IFactoryAppServiceHeader.class);
AppService appService = appServiceFactory.create(service, type, method, application, group, serviceRequest, description, servicePath, attachementurl, operation, request.getRemoteUser(), null, null, null);
ans = appServiceService.create(appService);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Adding Log entry.
*/
logEventService = appContext.getBean(ILogEventService.class);
logEventService.createForPrivateCalls("/CreateAppService", "CREATE", "Create AppService : " + service, request);
}
// Update content
if (request.getParameter("contentList") != null) {
JSONArray objContentArray = new JSONArray(request.getParameter("contentList"));
List<AppServiceContent> contentList = new ArrayList();
contentList = getContentListFromRequest(request, appContext, service, objContentArray);
// Update the Database with the new list.
ans = appServiceContentService.compareListAndUpdateInsertDeleteElements(service, contentList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
// Update header
if (request.getParameter("headerList") != null) {
JSONArray objHeaderArray = new JSONArray(request.getParameter("headerList"));
List<AppServiceHeader> headerList = new ArrayList();
headerList = getHeaderListFromRequest(request, appContext, service, objHeaderArray);
// Update the Database with the new list.
ans = appServiceHeaderService.compareListAndUpdateInsertDeleteElements(service, headerList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.
the class UpdateRobot method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
Answer ans = new Answer();
Gson gson = new Gson();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
response.setContentType("application/json");
String charset = request.getCharacterEncoding();
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
// Parameter that needs to be secured --> We SECURE+DECODE them
String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robot"), null, charset);
String port = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("port"), null, charset);
String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("platform"), null, charset);
String browser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browser"), null, charset);
String version = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("version"), "", charset);
String active = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("active"), "Y", charset);
String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
String userAgent = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("useragent"), "", charset);
String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("screensize"), "", charset);
String hostUser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("hostUsername"), null, charset);
String hostPassword = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("hostPassword"), null, charset);
// Parameter that we cannot secure as we need the html --> We DECODE them
String host = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("host"), null, charset);
String robotDecli = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("robotDecli"), null, charset);
List<RobotCapability> capabilities = (List<RobotCapability>) (request.getParameter("capabilities") == null ? Collections.emptyList() : gson.fromJson(request.getParameter("capabilities"), new TypeToken<List<RobotCapability>>() {
}.getType()));
// Securing capabilities by setting them the associated robot name
// Check also if there is no duplicated capability
Map<String, Object> capabilityMap = new HashMap<String, Object>();
for (RobotCapability capability : capabilities) {
capabilityMap.put(capability.getCapability(), null);
capability.setRobot(robot);
}
Integer robotid = 0;
boolean robotid_error = true;
try {
if (request.getParameter("robotid") != null && !request.getParameter("robotid").equals("")) {
robotid = Integer.valueOf(policy.sanitize(request.getParameter("robotid")));
robotid_error = false;
}
} catch (Exception ex) {
robotid_error = true;
}
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(robot)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Update").replace("%REASON%", "Robot name is missing."));
ans.setResultMessage(msg);
} else if (StringUtil.isNullOrEmpty(host)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Update").replace("%REASON%", "Robot host is missing."));
ans.setResultMessage(msg);
} else if (StringUtil.isNullOrEmpty(platform)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Update").replace("%REASON%", "Robot platform is missing."));
ans.setResultMessage(msg);
} else if (robotid_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert robotid to an integer value or robotid is missing."));
ans.setResultMessage(msg);
} else if (capabilityMap.size() != capabilities.size()) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Create").replace("%REASON%", "There is at least one duplicated capability. Please edit or remove it to continue."));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IRobotService robotService = appContext.getBean(IRobotService.class);
AnswerItem resp = robotService.readByKeyTech(robotid);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the error.
*/
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Update").replace("%REASON%", "Robot does not exist."));
ans.setResultMessage(msg);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
Robot robotData = (Robot) resp.getItem();
robotData.setRobot(robot);
robotData.setHost(host);
robotData.setPort(port);
robotData.setPlatform(platform);
robotData.setBrowser(browser);
robotData.setVersion(version);
robotData.setActive(active);
robotData.setDescription(description);
robotData.setUserAgent(userAgent);
robotData.setCapabilities(capabilities);
robotData.setScreenSize(screenSize);
robotData.setHostUser(hostUser);
robotData.setHostPassword(hostPassword);
robotData.setRobotDecli(robotDecli);
ans = robotService.update(robotData);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update was successful. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateRobot", "UPDATE", "Updated Robot : ['" + robotid + "'|'" + robot + "']", request);
}
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", ans.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.
the class UpdateTestDataLib method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String charset = request.getCharacterEncoding();
IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
response.setContentType("application/json");
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), ParameterParserUtil.parseStringParamAndDecode(fileItem.getString("UTF-8"), "", charset));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
String type = policy.sanitize(fileData.get("type"));
String system = policy.sanitize(fileData.get("system"));
String environment = policy.sanitize(fileData.get("environment"));
String country = policy.sanitize(fileData.get("country"));
String database = policy.sanitize(fileData.get("database"));
String databaseUrl = policy.sanitize(fileData.get("databaseUrl"));
String databaseCsv = policy.sanitize(fileData.get("databaseCsv"));
// Parameter that needs to be secured --> We SECURE+DECODE them
// this is mandatory
String name = fileData.get("name");
String group = fileData.get("group");
String description = fileData.get("libdescription");
String service = fileData.get("service");
// Parameter that we cannot secure as we need the html --> We DECODE them
String script = fileData.get("script");
String servicePath = fileData.get("servicepath");
String method = fileData.get("method");
String envelope = fileData.get("envelope");
String csvUrl = fileData.get("csvUrl");
String separator = fileData.get("separator");
String activateAutoSubdata = fileData.get("subdataCheck");
Integer testdatalibid = 0;
boolean testdatalibid_error = true;
try {
if (fileData.get("testdatalibid") != null && !fileData.get("testdatalibid").isEmpty()) {
testdatalibid = Integer.valueOf(fileData.get("testdatalibid"));
testdatalibid_error = false;
}
} catch (NumberFormatException ex) {
testdatalibid_error = true;
LOG.warn(ex);
}
try {
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(name)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Test data library name is missing."));
finalAnswer.setResultMessage(msg);
} else if (testdatalibid_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert testdatalibid to an integer value or testdatalibid is missing."));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
// specific attributes
ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
AnswerItem resp = libService.readByKey(testdatalibid);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the
* error.
*/
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
TestDataLib lib = (TestDataLib) resp.getItem();
String fileName = lib.getCsvUrl();
if (file != null) {
ans = libService.uploadFile(lib.getTestDataLibID(), file);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
fileName = file.getName();
}
}
lib.setName(name);
lib.setType(type);
lib.setGroup(group);
lib.setDescription(description);
lib.setSystem(system);
lib.setEnvironment(environment);
lib.setCountry(country);
lib.setDatabase(database);
lib.setScript(script);
lib.setDatabaseUrl(databaseUrl);
lib.setServicePath(servicePath);
lib.setService(service);
lib.setMethod(method);
lib.setEnvelope(envelope);
lib.setDatabaseCsv(databaseCsv);
if (file == null) {
lib.setCsvUrl(csvUrl);
} else {
lib.setCsvUrl(File.separator + lib.getTestDataLibID() + File.separator + fileName);
}
lib.setSeparator(separator);
lib.setLastModifier(request.getRemoteUser());
ans = libService.update(lib);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update operation finished with success, then the
* logging entry must be added.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateTestDataLib", "UPDATE", "Update TestDataLib - id: " + testdatalibid + " name: " + name + " system: " + system + " environment: " + environment + " country: " + country, request);
}
List<TestDataLibData> tdldList = new ArrayList();
// Getting list of SubData from JSON Call
if (fileData.get("subDataList") != null) {
JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
tdldList = getSubDataFromParameter(request, appContext, testdatalibid, objSubDataArray);
}
// When File has just been uploaded to servlet and flag to load the subdata value has been checked, we will parse it in order to automatically feed the subdata.
if (file != null && activateAutoSubdata.equals("1")) {
String str = "";
try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibcsv_path", "", null) + lib.getCsvUrl()))) {
// First line of the file is split by separator.
str = reader.readLine();
String[] subData = (!lib.getSeparator().isEmpty()) ? str.split(lib.getSeparator()) : str.split(",");
// We take the subdata from the servlet input.
TestDataLibData firstLine = tdldList.get(0);
tdldList = new ArrayList();
firstLine.setColumnPosition("1");
tdldList.add(firstLine);
int i = 1;
for (String item : subData) {
String subdataName = "SUBDATA" + i;
TestDataLibData tdld = tdldFactory.create(null, testdatalibid, subdataName, item, null, null, Integer.toString(i), null);
tdldList.add(tdld);
i++;
}
// Update the Database with the new list.
} finally {
try {
file.getInputStream().close();
} catch (Throwable ignore) {
}
}
}
ans = tdldService.compareListAndUpdateInsertDeleteElements(testdatalibid, tdldList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
}
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
} catch (JSONException ex) {
LOG.warn(ex);
// returns a default error message with the json format that is able to be parsed by the client-side
response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
}
}
use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.
the class CreateTestCaseExecutionQueue method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
JSONObject executionQueue = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
AnswerItem ansItem = new AnswerItem();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String charset = request.getCharacterEncoding();
response.setContentType("application/json");
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
String actionState = policy.sanitize(request.getParameter("actionState"));
String actionSave = policy.sanitize(request.getParameter("actionSave"));
String environment = policy.sanitize(request.getParameter("environment"));
String country = policy.sanitize(request.getParameter("country"));
String manualEnvData = policy.sanitize(request.getParameter("manualEnvData"));
// Parameter that needs to be secured --> We SECURE+DECODE them
String test = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), "", charset);
String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testCase"), "", charset);
int manualURL = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("manualURL"), 0, charset);
String manualHost = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualHost"), "", charset);
String manualContextRoot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualContextRoot"), "", charset);
String manualLoginRelativeURL = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualLoginRelativeURL"), "", charset);
String tag = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("tag"), "", charset);
String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robot"), "", charset);
String robotIP = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotIP"), "", charset);
String robotPort = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotPort"), "", charset);
String browser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browser"), "", charset);
String browserVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browserVersion"), "", charset);
String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("platform"), "", charset);
String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("screenSize"), "", charset);
int verbose = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("verbose"), 1, charset);
int screenshot = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("screenshot"), 0, charset);
int pageSource = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("pageSource"), 0, charset);
int seleniumLog = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("seleniumLog"), 0, charset);
String timeout = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("timeout"), "", charset);
int retries = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("retries"), 0, charset);
String manualExecution = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualExecution"), "", charset);
String debugFlag = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("debugFlag"), "N", charset);
// Parameter that we cannot secure as we need the html --> We DECODE them
String[] myIds = request.getParameterValues("id");
if (myIds == null) {
myIds = new String[1];
myIds[0] = "0";
}
long id = 0;
Integer priority = TestCaseExecutionQueue.PRIORITY_DEFAULT;
boolean prio_error = false;
try {
if (request.getParameter("priority") != null && !request.getParameter("priority").equals("")) {
priority = Integer.valueOf(policy.sanitize(request.getParameter("priority")));
}
} catch (Exception ex) {
prio_error = true;
}
boolean id_error = false;
IExecutionThreadPoolService executionThreadPoolService = appContext.getBean(IExecutionThreadPoolService.class);
// Create Tag when exist.
if (!StringUtil.isNullOrEmpty(tag)) {
// We create or update it.
ITagService tagService = appContext.getBean(ITagService.class);
tagService.createAuto(tag, "", request.getRemoteUser());
}
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
List<TestCaseExecutionQueue> insertedList = new ArrayList();
for (String myId : myIds) {
id_error = false;
id = 0;
try {
id = Long.valueOf(myId);
} catch (NumberFormatException ex) {
id_error = true;
}
/**
* Checking all constrains before calling the services.
*/
if (id_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution Queue").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert id to an integer value."));
ans.setResultMessage(msg);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
} else if (prio_error || priority > 2147483647 || priority < -2147483648) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution Queue").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert priority to an integer value."));
ans.setResultMessage(msg);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
} else {
try {
/**
* All data seems cleans so we can call the services.
*/
ITestCaseExecutionQueueService executionQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
IFactoryTestCaseExecutionQueue executionQueueFactory = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
if (actionSave.equals("save")) {
/**
* The service was able to perform the query and confirm
* the object exist, then we can update it.
*/
TestCaseExecutionQueue executionQueueData;
if (id == 0) {
// If id is not defined, we build the execution queue from all request datas.
executionQueueData = executionQueueFactory.create(test, testcase, country, environment, robot, robotIP, robotPort, browser, browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, request.getRemoteUser(), null, null, null);
executionQueueData.setDebugFlag(debugFlag);
} else {
// If id is defined, we get the execution queue from database.
executionQueueData = executionQueueService.convert(executionQueueService.readByKey(id));
executionQueueData.setState(TestCaseExecutionQueue.State.QUEUED);
executionQueueData.setComment("");
executionQueueData.setDebugFlag("N");
executionQueueData.setPriority(TestCaseExecutionQueue.PRIORITY_DEFAULT);
executionQueueData.setUsrCreated(request.getRemoteUser());
}
ansItem = executionQueueService.create(executionQueueData);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ansItem);
if (ansItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
TestCaseExecutionQueue addedExecution = (TestCaseExecutionQueue) ansItem.getItem();
insertedList.add(addedExecution);
}
if (myIds.length <= 1) {
if (ansItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update was successful. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/CreateTestCaseExecutionQueue", "CREATE", "Created ExecutionQueue : ['" + id + "']", request);
}
}
}
} catch (FactoryCreationException ex) {
LOG.warn(ex);
}
}
}
// Update is done, we now check what action needs to be performed.
if (actionState.equals("toQUEUED")) {
executionThreadPoolService.executeNextInQueueAsynchroneously(false);
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
if (insertedList.isEmpty()) {
jsonResponse.put("addedEntries", 0);
} else {
JSONArray executionList = new JSONArray();
for (TestCaseExecutionQueue testCaseExecutionQueue : insertedList) {
JSONObject myExecution = new JSONObject();
myExecution.append("id", testCaseExecutionQueue.getId());
executionList.put(myExecution);
}
jsonResponse.put("testCaseExecutionQueueList", executionList);
jsonResponse.put("addedEntries", insertedList.size());
}
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.
the class DeleteRobot method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
response.setContentType("application/json");
/**
* Parsing and securing all required parameters.
*/
Integer robotid = 0;
boolean robotid_error = true;
try {
if (request.getParameter("robotid") != null && !request.getParameter("robotid").equals("")) {
robotid = Integer.valueOf(policy.sanitize(request.getParameter("robotid")));
robotid_error = false;
}
} catch (Exception ex) {
robotid_error = true;
}
/**
* Checking all constrains before calling the services.
*/
if (robotid_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Delete").replace("%REASON%", "Robot ID (robotid) is missing."));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IRobotService robotService = appContext.getBean(IRobotService.class);
AnswerItem resp = robotService.readByKeyTech(robotid);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the error.
*/
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Delete").replace("%REASON%", "Robot does not exist."));
ans.setResultMessage(msg);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can delete it.
*/
Robot robotData = (Robot) resp.getItem();
ans = robotService.delete(robotData);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Delete was successful. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/DeleteRobot", "DELETE", "Delete Robot : ['" + robotid + "'|'" + robotData.getRobot() + "']", request);
}
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", ans.getResultMessage().getDescription());
response.getWriter().print(jsonResponse.toString());
response.getWriter().flush();
}
Aggregations