use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.
the class ReadTestCaseExecution method findValuesForColumnFilter.
/**
* Find Values to display for Column Filter
*
* @param system
* @param test
* @param appContext
* @param request
* @param columnName
* @return
* @throws JSONException
*/
private AnswerItem findValuesForColumnFilter(String system, String test, ApplicationContext appContext, HttpServletRequest request, String columnName) throws JSONException {
AnswerItem answer = new AnswerItem();
JSONObject object = new JSONObject();
AnswerList values = new AnswerList();
Map<String, List<String>> individualSearch = new HashMap<>();
testCaseService = appContext.getBean(TestCaseService.class);
invariantService = appContext.getBean(InvariantService.class);
buildRevisionInvariantService = appContext.getBean(BuildRevisionInvariantService.class);
applicationService = appContext.getBean(ApplicationService.class);
LOG.debug(columnName);
switch(columnName) {
/**
* Columns from Status
*/
case "exe.controlStatus":
List<String> dataList = new ArrayList<>();
dataList.add(TestCaseExecution.CONTROLSTATUS_CA);
dataList.add(TestCaseExecution.CONTROLSTATUS_FA);
dataList.add(TestCaseExecution.CONTROLSTATUS_KO);
dataList.add(TestCaseExecution.CONTROLSTATUS_NA);
dataList.add(TestCaseExecution.CONTROLSTATUS_NE);
dataList.add(TestCaseExecution.CONTROLSTATUS_OK);
dataList.add(TestCaseExecution.CONTROLSTATUS_PE);
values.setDataList(dataList);
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
msg.setDescription(msg.getDescription().replace("%ITEM%", "execution").replace("%OPERATION%", "SELECT"));
values.setResultMessage(msg);
break;
/**
* For columns test and testcase, get distinct values from test
* table
*/
case "exe.test":
case "exe.testcase":
case "exe.status":
values = testCaseService.readDistinctValuesByCriteria(system, test, "", null, columnName.replace("exe.", "tec."));
break;
/**
* For columns country, environment get values from invariant
*/
case "exe.country":
case "exe.environment":
try {
/**
*/
AnswerList<Invariant> invariants = invariantService.readByIdname(columnName.replace("exe.", ""));
List<Invariant> invariantList = invariantService.convert(invariants);
List<String> stringResult = new ArrayList();
for (Invariant inv : invariantList) {
stringResult.add(inv.getValue());
}
values.setDataList(stringResult);
values.setTotalRows(invariantList.size());
values.setResultMessage(invariants.getResultMessage());
} catch (CerberusException ex) {
LOG.warn(ex);
}
break;
/**
* For columns build, revision get values from
* buildrevisioninvariant
*/
case "exe.build":
case "exe.revision":
individualSearch = new HashMap<>();
individualSearch.put("level", new ArrayList(Arrays.asList(columnName.equals("exe.build") ? "1" : "2")));
values = buildRevisionInvariantService.readDistinctValuesByCriteria(system, "", individualSearch, "versionName");
break;
/**
* For columns application get values from application
*/
case "exe.application":
values = applicationService.readDistinctValuesByCriteria(system, "", null, columnName.replace("exe.", ""));
break;
/**
* For all other columns, get distinct values from testcaseexecution
*/
default:
String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "tec.test,tec.testcase,application,project,ticket,description,behaviororvalueexpected,readonly,bugtrackernewurl,deploytype,mavengroupid");
String[] columnToSort = sColumns.split(",");
List<String> individualLike = new ArrayList(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(",")));
individualSearch = new HashMap<>();
for (int a = 0; a < columnToSort.length; a++) {
if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
List<String> search = new ArrayList(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
if (individualLike.contains(columnToSort[a])) {
individualSearch.put(columnToSort[a] + ":like", search);
} else {
individualSearch.put(columnToSort[a], search);
}
}
}
values = testCaseExecutionService.readDistinctValuesByCriteria(system, test, searchParameter, individualSearch, columnName);
}
object.put("distinctValues", values.getDataList());
answer.setItem(object);
answer.setResultMessage(values.getResultMessage());
return answer;
}
use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.
the class ReadTestCaseExecutionQueue 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
* @throws CerberusException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException {
String echo = request.getParameter("sEcho");
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
response.setContentType("application/json");
response.setCharacterEncoding("utf8");
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
// Default message to unexpected error.
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
// Init Answer with potencial error from Parsing parameter.
String queueId = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("queueid"), "");
Long queueid = Long.valueOf(0);
boolean queueid_error = false;
if (request.getParameter("queueid") != null) {
try {
if (request.getParameter("queueid") != null && !request.getParameter("queueid").equals("")) {
queueid = Long.valueOf(policy.sanitize(request.getParameter("queueid")));
queueid_error = false;
}
} catch (Exception ex) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Case Execution Queue"));
msg.setDescription(msg.getDescription().replace("%OPERATION%", "Read"));
msg.setDescription(msg.getDescription().replace("%REASON%", "queueid must be an integer value."));
queueid_error = true;
}
}
AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
// Global boolean on the servlet that define if the user has permition to edit and delete object.
boolean userHasPermissions = request.isUserInRole("RunTest");
try {
JSONObject jsonResponse;
if (!Strings.isNullOrEmpty(request.getParameter("columnName"))) {
answer = findDistinctValuesOfColumn(appContext, request, request.getParameter("columnName"));
jsonResponse = (JSONObject) answer.getItem();
} else if (queueid != 0) {
answer = findExecutionQueueByKeyTech(queueid, appContext, userHasPermissions);
jsonResponse = (JSONObject) answer.getItem();
} else if (request.getParameter("flag") != null && request.getParameter("flag").equals("queueStatus")) {
answer = findExecutionInQueueStatus(appContext, request);
jsonResponse = (JSONObject) answer.getItem();
} else {
answer = findExecutionInQueueList(appContext, true, request);
jsonResponse = (JSONObject) answer.getItem();
}
jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", answer.getResultMessage().getDescription());
jsonResponse.put("sEcho", echo);
response.getWriter().print(jsonResponse.toString());
} catch (JSONException e) {
LOG.warn(e);
// 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.exception.CerberusException in project cerberus-source by cerberustesting.
the class ReadTestCaseExecutionQueue method findExecutionInQueueStatus.
private AnswerItem findExecutionInQueueStatus(ApplicationContext appContext, HttpServletRequest request) throws JSONException {
AnswerItem item = new AnswerItem();
JSONObject object = new JSONObject();
executionThreadPoolService = appContext.getBean(IExecutionThreadPoolService.class);
parameterService = appContext.getBean(IParameterService.class);
invariantService = appContext.getBean(IInvariantService.class);
JSONArray jsonArray = new JSONArray();
try {
HashMap<String, Integer> mapRunning = executionThreadPoolService.getCurrentlyRunning();
HashMap<String, Integer> mapInQueue = executionThreadPoolService.getCurrentlyToTreat();
HashMap<String, Integer> mapPoolSize = executionThreadPoolService.getCurrentlyPoolSizes();
for (Map.Entry<String, Integer> entry : mapRunning.entrySet()) {
String column = entry.getKey();
Integer name = entry.getValue();
if (!("".equals(column))) {
String[] data = column.split("\\/\\/");
JSONObject jsonObject = new JSONObject();
switch(data[0]) {
case TestCaseExecutionQueueToTreat.CONSTRAIN1_GLOBAL:
jsonObject.put("contrainId", data[0]);
jsonObject.put("system", "");
jsonObject.put("environment", "");
jsonObject.put("country", "");
jsonObject.put("application", "");
jsonObject.put("robot", "");
jsonObject.put("nbInQueue", ParameterParserUtil.parseIntegerParam(mapInQueue.get(column), 0));
jsonObject.put("nbPoolSize", ParameterParserUtil.parseIntegerParam(mapPoolSize.get(column), 0));
jsonObject.put("nbRunning", ParameterParserUtil.parseIntegerParam(name, 0));
jsonObject.put("hasPermissionsUpdate", parameterService.hasPermissionsUpdate("cerberus_queueexecution_global_threadpoolsize", request));
break;
case TestCaseExecutionQueueToTreat.CONSTRAIN2_APPLICATION:
jsonObject.put("contrainId", data[0]);
jsonObject.put("system", data[1]);
jsonObject.put("environment", data[2]);
jsonObject.put("country", data[3]);
jsonObject.put("application", data[4]);
jsonObject.put("robot", "");
jsonObject.put("nbInQueue", ParameterParserUtil.parseIntegerParam(mapInQueue.get(column), 0));
jsonObject.put("nbPoolSize", ParameterParserUtil.parseIntegerParam(mapPoolSize.get(column), 0));
jsonObject.put("nbRunning", ParameterParserUtil.parseIntegerParam(name, 0));
jsonObject.put("hasPermissionsUpdate", parameterService.hasPermissionsUpdate("cerberus_queueexecution_global_threadpoolsize", request));
break;
case TestCaseExecutionQueueToTreat.CONSTRAIN3_ROBOT:
jsonObject.put("contrainId", data[0]);
jsonObject.put("system", "");
jsonObject.put("environment", "");
jsonObject.put("country", "");
jsonObject.put("application", "");
if (data.length > 1) {
jsonObject.put("robot", data[1]);
if ((data[1] == null) || (data[1].equalsIgnoreCase("null"))) {
jsonObject.put("invariantExist", false);
} else {
jsonObject.put("invariantExist", invariantService.isInvariantExist("ROBOTHOST", data[1]));
}
} else {
jsonObject.put("robot", "");
jsonObject.put("invariantExist", false);
}
jsonObject.put("nbInQueue", ParameterParserUtil.parseIntegerParam(mapInQueue.get(column), 0));
jsonObject.put("nbPoolSize", ParameterParserUtil.parseIntegerParam(mapPoolSize.get(column), 0));
jsonObject.put("nbRunning", ParameterParserUtil.parseIntegerParam(name, 0));
jsonObject.put("hasPermissionsUpdate", parameterService.hasPermissionsUpdate("cerberus_queueexecution_global_threadpoolsize", request));
break;
}
jsonArray.put(jsonObject);
}
}
object.put("contentTable", jsonArray);
} catch (CerberusException ex) {
LOG.warn(ex);
}
object.put("messageType", "");
object.put("message", "");
item.setResultMessage(new MessageEvent(MessageEventEnum.GENERIC_OK));
item.setItem(object);
return item;
}
use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.
the class UpdateTestCaseExecutionQueue 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();
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();
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"), null, charset);
String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testCase"), null, charset);
int manualURL = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("manualURL"), 0, charset);
String manualHost = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualHost"), null, charset);
String manualContextRoot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualContextRoot"), "", charset);
String manualLoginRelativeURL = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualLoginRelativeURL"), "", charset);
String tag = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("tag"), null, charset);
String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robot"), null, charset);
String robotIP = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotIP"), null, charset);
String robotPort = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotPort"), null, charset);
String browser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browser"), null, charset);
String browserVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browserVersion"), null, charset);
String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("platform"), null, charset);
String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("screenSize"), null, 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);
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;
}
// Parameter that we cannot secure as we need the html --> We DECODE them
String[] myIds = request.getParameterValues("id");
long id = 0;
// 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);
boolean id_error = false;
for (String myId : myIds) {
id_error = false;
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 {
/**
* All data seems cleans so we can call the services.
*/
ITestCaseExecutionQueueService executionQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
IExecutionThreadPoolService executionThreadPoolService = appContext.getBean(IExecutionThreadPoolService.class);
AnswerItem resp = executionQueueService.readByKey(id);
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 {
TestCaseExecutionQueue executionQueueData = (TestCaseExecutionQueue) resp.getItem();
if (actionSave.equals("save")) {
/**
* The service was able to perform the query and confirm
* the object exist, then we can update it.
*/
executionQueueData.setTest(ParameterParserUtil.parseStringParam(test, executionQueueData.getTest()));
executionQueueData.setTestCase(ParameterParserUtil.parseStringParam(testcase, executionQueueData.getTestCase()));
executionQueueData.setTag(ParameterParserUtil.parseStringParam(tag, executionQueueData.getTag()));
executionQueueData.setEnvironment(ParameterParserUtil.parseStringParam(environment, executionQueueData.getEnvironment()));
executionQueueData.setCountry(ParameterParserUtil.parseStringParam(country, executionQueueData.getCountry()));
executionQueueData.setManualURL(ParameterParserUtil.parseIntegerParam(manualURL, executionQueueData.getManualURL()));
executionQueueData.setManualHost(ParameterParserUtil.parseStringParam(manualHost, executionQueueData.getManualHost()));
executionQueueData.setManualContextRoot(ParameterParserUtil.parseStringParam(manualContextRoot, executionQueueData.getManualContextRoot()));
executionQueueData.setManualLoginRelativeURL(ParameterParserUtil.parseStringParam(manualLoginRelativeURL, executionQueueData.getManualLoginRelativeURL()));
executionQueueData.setManualEnvData(ParameterParserUtil.parseStringParam(manualEnvData, executionQueueData.getManualEnvData()));
executionQueueData.setRobot(ParameterParserUtil.parseStringParam(robot, executionQueueData.getRobot()));
executionQueueData.setRobotIP(ParameterParserUtil.parseStringParam(robotIP, executionQueueData.getRobotIP()));
executionQueueData.setRobotPort(ParameterParserUtil.parseStringParam(robotPort, executionQueueData.getRobotPort()));
executionQueueData.setBrowser(ParameterParserUtil.parseStringParam(browser, executionQueueData.getBrowser()));
executionQueueData.setBrowserVersion(ParameterParserUtil.parseStringParam(browserVersion, executionQueueData.getBrowserVersion()));
executionQueueData.setPlatform(ParameterParserUtil.parseStringParam(platform, executionQueueData.getPlatform()));
executionQueueData.setScreenSize(ParameterParserUtil.parseStringParam(screenSize, executionQueueData.getScreenSize()));
executionQueueData.setVerbose(ParameterParserUtil.parseIntegerParam(verbose, executionQueueData.getVerbose()));
executionQueueData.setScreenshot(screenshot);
executionQueueData.setPageSource(pageSource);
executionQueueData.setSeleniumLog(seleniumLog);
executionQueueData.setTimeout(timeout);
executionQueueData.setRetries(retries);
executionQueueData.setManualExecution(manualExecution);
executionQueueData.setDebugFlag(debugFlag);
executionQueueData.setPriority(priority);
executionQueueData.setUsrModif(request.getRemoteUser());
ans = executionQueueService.update(executionQueueData);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update was successfull. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateTestCaseExecutionQueue", "UPDATE", "Updated ExecutionQueue : ['" + id + "']", request);
}
}
// Update is done, we now check what action needs to be performed.
if (actionState.equals("toQUEUED")) {
LOG.debug("toQUEUED");
ans = executionQueueService.updateToQueued(id, "Trigered by user " + request.getRemoteUser() + ".");
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
executionThreadPoolService.executeNextInQueueAsynchroneously(false);
}
// Priority Update.
if (actionSave.equals("priority")) {
executionQueueData.setPriority(priority);
ans = executionQueueService.update(executionQueueData);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
// Update is done, we now check what action needs to be performed.
if (actionState.equals("toCANCELLED")) {
LOG.debug("toCANCELLED");
ans = executionQueueService.updateToCancelled(id, "Cancelled by user " + request.getRemoteUser() + ".");
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
// Update is done, we now check what action needs to be performed.
if (actionState.equals("toCANCELLEDForce")) {
LOG.debug("toCANCELLEDForce");
ans = executionQueueService.updateToCancelledForce(id, "Forced Cancelled by user " + request.getRemoteUser() + ".");
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
// Update is done, we now check what action needs to be performed.
if (actionState.equals("toERRORForce")) {
LOG.debug("toERRORForce");
ans = executionQueueService.updateToErrorForce(id, "Forced Eroor by user " + request.getRemoteUser() + ".");
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.exception.CerberusException in project cerberus-source by cerberustesting.
the class CreateInvariant 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);
String charset = request.getCharacterEncoding();
String id = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("idName"), "", charset);
String value = request.getParameter("value");
String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
String veryShortDescField = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("veryShortDesc"), "", charset);
String gp1 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp1"), "", charset);
String gp2 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp2"), "", charset);
String gp3 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp3"), "", charset);
String gp4 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp4"), "", charset);
String gp5 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp5"), "", charset);
String gp6 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp6"), "", charset);
String gp7 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp7"), "", charset);
String gp8 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp8"), "", charset);
String gp9 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp9"), "", charset);
Integer sort = 10;
boolean sort_error = false;
try {
if (request.getParameter("Sort") != null && !request.getParameter("Sort").equals("")) {
sort = Integer.valueOf(policy.sanitize(request.getParameter("Sort")));
}
} catch (Exception ex) {
sort_error = true;
}
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(id)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Create").replace("%REASON%", "Invariant name is missing!"));
ans.setResultMessage(msg);
} else if (sort_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Create").replace("%REASON%", "Could not manage to convert sort to an integer value!"));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IInvariantService invariantService = appContext.getBean(IInvariantService.class);
IFactoryInvariant factoryInvariant = appContext.getBean(IFactoryInvariant.class);
Invariant invariantData = factoryInvariant.create(id, value, sort, description, veryShortDescField, gp1, gp2, gp3, gp4, gp5, gp6, gp7, gp8, gp9);
if (invariantService.hasPermissionsCreate(invariantData, request)) {
ans = invariantService.create(invariantData);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Object updated. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/CreateInvariant2", "CREATE", "Create Invariant : ['" + id + "']", request);
}
} else {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Create").replace("%REASON%", "You are not allowed to do that or invariant is not public."));
ans.setResultMessage(msg);
}
}
/**
* 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();
}
Aggregations