use of org.cerberus.crud.service.ILogEventService in project cerberus-source by cerberustesting.
the class AddToExecutionQueueV003 method processRequest.
/**
* Process request for both GET and POST method.
*
* <p>
* Request processing is divided in two parts:
* <ol>
* <li>Getting all test cases which have been sent to this servlet;</li>
* <li>Try to insert all these test cases to the execution queue.</li>
* </ol>
* </p>
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
final String charset = request.getCharacterEncoding();
Date requestDate = new Date();
// Loading Services.
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
inQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
inQueueFactoryService = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
executionThreadService = appContext.getBean(IExecutionThreadPoolService.class);
testCaseService = appContext.getBean(ITestCaseService.class);
invariantService = appContext.getBean(IInvariantService.class);
applicationService = appContext.getBean(IApplicationService.class);
testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
campaignParameterService = appContext.getBean(ICampaignParameterService.class);
countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
// 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%", ""));
AnswerItem<List<TestCase>> testcases = null;
/**
* Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(ILogEventService.class);
logEventService.createForPublicCalls("/AddToExecutionQueueV003", "CALL", "AddToExecutionQueueV003 called : " + request.getRequestURL(), request);
// Parsing all parameters.
// Execution scope parameters : Campaign, TestCases, Countries, Environment, Browser.
String campaign = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_CAMPAIGN), null, charset);
List<String> selectTest;
selectTest = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_TEST), null, charset);
List<String> selectTestCase;
selectTestCase = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_TESTCASE), null, charset);
List<String> countries;
countries = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_COUNTRY), null, charset);
List<String> environments;
environments = ParameterParserUtil.parseListParamAndDecodeAndDeleteEmptyValue(request.getParameterValues(PARAMETER_ENVIRONMENT), null, charset);
List<String> robots = new ArrayList<>();
robots = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_ROBOT), robots, charset);
// Execution parameters.
String tag = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_TAG), "");
String robotIP = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT_IP), null, charset);
String robotPort = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT_PORT), null, charset);
String browser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_BROWSER), null, charset);
String browserVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_BROWSER_VERSION), null, charset);
String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_PLATFORM), null, charset);
String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_SCREENSIZE), null, charset);
int manualURL = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_MANUAL_URL), DEFAULT_VALUE_MANUAL_URL, charset);
String manualHost = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_HOST), null, charset);
String manualContextRoot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_CONTEXT_ROOT), null, charset);
String manualLoginRelativeURL = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_LOGIN_RELATIVE_URL), null, charset);
String manualEnvData = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_ENV_DATA), null, charset);
int screenshot = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_SCREENSHOT), DEFAULT_VALUE_SCREENSHOT, charset);
int verbose = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_VERBOSE), DEFAULT_VALUE_VERBOSE, charset);
String timeout = request.getParameter(PARAMETER_TIMEOUT);
int pageSource = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_PAGE_SOURCE), DEFAULT_VALUE_PAGE_SOURCE, charset);
int seleniumLog = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_SELENIUM_LOG), DEFAULT_VALUE_SELENIUM_LOG, charset);
int retries = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_RETRIES), DEFAULT_VALUE_RETRIES, charset);
String manualExecution = ParameterParserUtil.parseStringParamAndDecode(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION, charset);
int priority = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_EXEPRIORITY), DEFAULT_VALUE_PRIORITY, charset);
if (manualExecution.equals("")) {
manualExecution = DEFAULT_VALUE_MANUAL_EXECUTION;
}
String outputFormat = ParameterParserUtil.parseStringParamAndDecode(request.getParameter(PARAMETER_OUTPUTFORMAT), DEFAULT_VALUE_OUTPUTFORMAT, charset);
// Defining help message.
String helpMessage = "This servlet is used to add to Cerberus execution queue a list of execution. Execution list will be calculated from cartesian product of " + "testcase, country, environment and browser list. Those list can be defined from the associated servlet parameter but can also be defined from campaign directy inside Cerberus.\n" + "List defined from servlet overwrite the list defined from the campaign. All other execution parameters will be taken to each execution.\n" + "Available parameters:\n" + "- " + PARAMETER_CAMPAIGN + " : Campaign name from which testcase, countries, environment and browser can be defined from Cerberus. [" + campaign + "]\n" + "- " + PARAMETER_TEST + " : List of test to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + selectTest + "]\n" + "- " + PARAMETER_TESTCASE + " : List of testCase to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + selectTestCase + "]\n" + "- " + PARAMETER_COUNTRY + " : List of countries to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + countries + "]\n" + "- " + PARAMETER_ENVIRONMENT + " : List of environment to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + environments + "]\n" + "- " + PARAMETER_ROBOT + " : List of robot to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + robots + "]\n" + "- " + PARAMETER_ROBOT_IP + " : Robot IP that will be used for every execution triggered. [" + robotIP + "]\n" + "- " + PARAMETER_ROBOT_PORT + " : Robot Port that will be used for every execution triggered. [" + robotPort + "]\n" + "- " + PARAMETER_BROWSER + " : Browser that will be used for every execution triggered. [" + browser + "]\n" + "- " + PARAMETER_BROWSER_VERSION + " : Browser Version that will be used for every execution triggered. [" + browserVersion + "]\n" + "- " + PARAMETER_PLATFORM + " : Platform that will be used for every execution triggered. [" + platform + "]\n" + "- " + PARAMETER_SCREENSIZE + " : Size of the screen that will be used for every execution triggered. [" + screenSize + "]\n" + "- " + PARAMETER_MANUAL_URL + " : Activate (1) or not (0) the Manual URL of the application to execute. If activated the 4 parameters after are necessary. [" + manualURL + "]\n" + "- " + PARAMETER_MANUAL_HOST + " : Host of the application to test (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualHost + "]\n" + "- " + PARAMETER_MANUAL_CONTEXT_ROOT + " : Context root of the application to test (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualContextRoot + "]\n" + "- " + PARAMETER_MANUAL_LOGIN_RELATIVE_URL + " : Relative login URL of the application (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualLoginRelativeURL + "]\n" + "- " + PARAMETER_MANUAL_ENV_DATA + " : Environment where to get the test data when a " + PARAMETER_MANUAL_URL + " is defined. (only used when manualURL is active). [" + manualEnvData + "]\n" + "- " + PARAMETER_TAG + " : Tag that will be used for every execution triggered. [" + tag + "]\n" + "- " + PARAMETER_SCREENSHOT + " : Activate or not the screenshots for every execution triggered. [" + screenshot + "]\n" + "- " + PARAMETER_VERBOSE + " : Verbose level for every execution triggered. [" + verbose + "]\n" + "- " + PARAMETER_TIMEOUT + " : Timeout used for the action that will be used for every execution triggered. [" + timeout + "]\n" + "- " + PARAMETER_PAGE_SOURCE + " : Record Page Source during for every execution triggered. [" + pageSource + "]\n" + "- " + PARAMETER_SELENIUM_LOG + " : Get the SeleniumLog at the end of the execution for every execution triggered. [" + seleniumLog + "]\n" + "- " + PARAMETER_MANUAL_EXECUTION + " : Execute testcase in manual mode for every execution triggered. [" + manualExecution + "]\n" + "- " + PARAMETER_RETRIES + " : Number of tries if the result is not OK for every execution triggered. [" + retries + "]\n" + "- " + PARAMETER_EXEPRIORITY + " : Priority that will be used in the queue for every execution triggered. [" + priority + "]\n" + "- " + PARAMETER_OUTPUTFORMAT + " : Format of the servlet output. can be compact, json [" + outputFormat + "]\n";
// try {
// Checking the parameter validity.
StringBuilder errorMessage = new StringBuilder();
boolean error = false;
if (tag == null || tag.isEmpty()) {
if (request.getRemoteUser() != null) {
tag = request.getRemoteUser();
}
if (tag.length() > 0) {
tag += ".";
}
if (campaign != null) {
tag += campaign;
}
if (tag.length() > 0) {
tag += ".";
}
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String mytimestamp = sdf.format(timestamp);
tag += mytimestamp;
} else if (tag.length() > 255) {
errorMessage.append("Error - Parameter ").append(PARAMETER_TAG).append(" is too big. Maximum size if 255. Current size is : ").append(tag.length()).append("\n");
error = true;
}
if (campaign != null && !campaign.isEmpty()) {
final AnswerItem<Map<String, List<String>>> parsedCampaignParameters = campaignParameterService.parseParametersByCampaign(campaign);
if (parsedCampaignParameters.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
// If parameters are already defined from request, we ignore the campaign values.
if (countries == null || countries.isEmpty()) {
countries = parsedCampaignParameters.getItem().get(CampaignParameter.COUNTRY_PARAMETER);
}
if (environments == null || environments.isEmpty()) {
environments = parsedCampaignParameters.getItem().get(CampaignParameter.ENVIRONMENT_PARAMETER);
}
if (robots == null || robots.isEmpty()) {
robots = parsedCampaignParameters.getItem().get(CampaignParameter.ROBOT_PARAMETER);
}
}
if ((countries != null) && (selectTest == null || selectTest.isEmpty())) {
// If no countries are found, there is no need to get the testcase list. None will be returned.
selectTest = new ArrayList<>();
selectTestCase = new ArrayList<>();
testcases = testCaseService.findTestCaseByCampaignNameAndCountries(campaign, countries.toArray(new String[countries.size()]));
for (TestCase campaignTestCase : testcases.getItem()) {
selectTest.add(campaignTestCase.getTest());
selectTestCase.add(campaignTestCase.getTestCase());
}
}
}
if (countries == null || countries.isEmpty()) {
errorMessage.append("Error - No Country defined. You can either feed it with parameter '" + PARAMETER_COUNTRY + "' or add it into the campaign definition.\n");
error = true;
}
// }
if (selectTest == null || selectTest.isEmpty() || selectTestCase == null || selectTestCase.isEmpty()) {
errorMessage.append("Error - No TestCases defined. You can either feed it with parameters '" + PARAMETER_TEST + "' and '" + PARAMETER_TESTCASE + "' or add it into the campaign definition.\n");
error = true;
}
if ((selectTest != null) && (selectTestCase != null) && (selectTest.size() != selectTestCase.size())) {
errorMessage.append("Error - Test list size (").append(selectTest.size()).append(") is not the same as testcase list size (").append(selectTestCase.size()).append("). Please check that both list are consistent.\n");
error = true;
}
if (manualURL >= 1) {
if (manualHost == null || manualEnvData == null) {
errorMessage.append("Error - ManualURL has been activated but no ManualHost or Manual Environment defined.\n");
error = true;
}
} else if (environments == null || environments.isEmpty()) {
errorMessage.append("Error - No Environment defined (and " + PARAMETER_MANUAL_URL + " not activated). You can either feed it with parameter '" + PARAMETER_ENVIRONMENT + "' or add it into the campaign definition.\n");
error = true;
}
int nbExe = 0;
JSONArray jsonArray = new JSONArray();
String user = request.getRemoteUser() == null ? "" : request.getRemoteUser();
int nbtestcasenotactive = 0;
int nbtestcaseenvgroupnotallowed = 0;
int nbenvnotexist = 0;
boolean tagAlreadyAdded = false;
int nbrobot = 0;
if (robots == null || robots.isEmpty()) {
nbrobot = 1;
} else {
nbrobot = robots.size();
}
// Starting the request only if previous parameters exist.
if (!error) {
int nbtescase = selectTest.size();
int nbenv = environments.size();
int nbcountries = countries.size();
// Part 1: Getting all possible Execution from test cases + countries + environments + browsers which have been sent to this servlet.
Map<String, String> invariantEnv = invariantService.readToHashMapGp1StringByIdname("ENVIRONMENT", "");
List<TestCaseExecutionQueue> toInserts = new ArrayList<TestCaseExecutionQueue>();
try {
HashMap<String, CountryEnvParam> envMap = new HashMap<>();
LOG.debug("Loading all environments.");
for (CountryEnvParam envParam : countryEnvParamService.convert(countryEnvParamService.readActiveBySystem(null))) {
envMap.put(envParam.getSystem() + LOCAL_SEPARATOR + envParam.getCountry() + LOCAL_SEPARATOR + envParam.getEnvironment(), envParam);
}
LOG.debug("Nb of TestCase : " + selectTest.size());
for (int i = 0; i < selectTest.size(); i++) {
// for (String localTest : selectTest) {
String test = selectTest.get(i);
String testCase = selectTestCase.get(i);
TestCase tc = testCaseService.convert(testCaseService.readByKey(test, testCase));
// TestCases that are not active are not inserted into queue.
if (tc.getTcActive().equals("Y")) {
// We only insert testcase that exist for the given country.
for (TestCaseCountry country : testCaseCountryService.convert(testCaseCountryService.readByTestTestCase(null, test, testCase))) {
if (countries.contains(country.getCountry())) {
// for each environment we test that correspondng gp1 is compatible with testcase environment flag activation.
for (String environment : environments) {
String envGp1 = invariantEnv.get(environment);
if (((envGp1.equals("PROD")) && (tc.getActivePROD().equalsIgnoreCase("Y"))) || ((envGp1.equals("UAT")) && (tc.getActiveUAT().equalsIgnoreCase("Y"))) || ((envGp1.equals("QA")) && (tc.getActiveQA().equalsIgnoreCase("Y"))) || (envGp1.equals("DEV"))) {
// Getting Application in order to check application type against browser.
Application app = applicationService.convert(applicationService.readByKey(tc.getApplication()));
if (envMap.containsKey(app.getSystem() + LOCAL_SEPARATOR + country.getCountry() + LOCAL_SEPARATOR + environment)) {
// Create Tag only if not already done and defined.
if (!StringUtil.isNullOrEmpty(tag) && !tagAlreadyAdded) {
// We create or update it.
ITagService tagService = appContext.getBean(ITagService.class);
tagService.createAuto(tag, campaign, user);
tagAlreadyAdded = true;
}
if ((app != null) && (app.getType() != null) && (app.getType().equalsIgnoreCase(Application.TYPE_GUI) || app.getType().equalsIgnoreCase(Application.TYPE_APK) || app.getType().equalsIgnoreCase(Application.TYPE_IPA) || app.getType().equalsIgnoreCase(Application.TYPE_FAT))) {
if (robots == null || robots.isEmpty()) {
robots = new ArrayList<>();
robots.add("");
}
for (String robot : robots) {
try {
LOG.debug("Insert Queue Entry.");
toInserts.add(inQueueFactoryService.create(test, testCase, country.getCountry(), environment, robot, robotIP, robotPort, browser, browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, user, null, null, null));
} catch (FactoryCreationException e) {
LOG.error("Unable to insert record due to: " + e, e);
LOG.error("test: " + test + "-" + testCase + "-" + country.getCountry() + "-" + environment + "-" + robots);
}
}
} else {
// Application does not support robot so we force an empty value.
LOG.debug("Forcing Robot to empty value. Application type=" + app.getType());
try {
LOG.debug("Insert Queue Entry.");
toInserts.add(inQueueFactoryService.create(test, testCase, country.getCountry(), environment, "", "", "", "", "", "", "", manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, user, null, null, null));
} catch (FactoryCreationException e) {
LOG.error("Unable to insert record due to: " + e, e);
LOG.error("test: " + test + "-" + testCase + "-" + country.getCountry() + "-" + environment + "-" + robots);
}
}
} else {
LOG.debug("Env does not exist or is not active.");
nbenvnotexist = nbenvnotexist + nbrobot;
}
} else {
LOG.debug("Env group not active for testcase : " + environment);
nbtestcaseenvgroupnotallowed = nbtestcaseenvgroupnotallowed + nbrobot;
}
}
} else {
LOG.debug("Country does not match. " + countries + " " + country.getCountry());
}
}
} else {
LOG.debug("TestCase not Active.");
nbtestcasenotactive = nbtestcasenotactive + (nbcountries * nbenv * nbrobot);
}
}
} catch (CerberusException ex) {
LOG.warn(ex);
}
// Part 2: Try to insert all these test cases to the execution queue.
List<String> errorMessages = new ArrayList<String>();
for (TestCaseExecutionQueue toInsert : toInserts) {
try {
inQueueService.convert(inQueueService.create(toInsert));
nbExe++;
JSONObject value = new JSONObject();
value.put("queueId", toInsert.getId());
value.put("test", toInsert.getTest());
value.put("testcase", toInsert.getTestCase());
value.put("country", toInsert.getCountry());
value.put("environment", toInsert.getEnvironment());
jsonArray.put(value);
} catch (CerberusException e) {
String errorMessageTmp = "Unable to insert " + toInsert.toString() + " due to " + e.getMessage();
LOG.warn(errorMessageTmp);
errorMessages.add(errorMessageTmp);
continue;
} catch (JSONException ex) {
LOG.error(ex);
}
}
// Part 3 : Trigger JobQueue
try {
executionThreadService.executeNextInQueueAsynchroneously(false);
} catch (CerberusException ex) {
String errorMessageTmp = "Unable to feed the execution queue due to " + ex.getMessage();
LOG.warn(errorMessageTmp);
errorMessages.add(errorMessageTmp);
}
if (!errorMessages.isEmpty()) {
StringBuilder errorMessageTmp = new StringBuilder();
for (String item : errorMessages) {
errorMessageTmp.append(item);
errorMessageTmp.append(LINE_SEPARATOR);
}
errorMessage.append(errorMessageTmp.toString());
}
errorMessage.append(nbExe);
errorMessage.append(" execution(s) succesfully inserted to queue. ");
if (testcases != null && testcases.getResultMessage().getSource() == MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT) {
errorMessage.append(testcases.getResultMessage().getDescription());
}
// Message that everything went fine.
msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
} else {
// In case of errors, we display the help message.
// errorMessage.append(helpMessage);
}
// Init Answer with potencial error from Parsing parameter.
AnswerItem answer = new AnswerItem(msg);
switch(outputFormat) {
case "json":
try {
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", errorMessage.toString());
jsonResponse.put("helpMessage", helpMessage);
jsonResponse.put("tag", tag);
jsonResponse.put("nbExe", nbExe);
jsonResponse.put("nbErrorTCNotActive", nbtestcasenotactive);
jsonResponse.put("nbErrorTCNotAllowedOnEnv", nbtestcaseenvgroupnotallowed);
jsonResponse.put("nbErrorEnvNotExistOrNotActive", nbenvnotexist);
jsonResponse.put("queueList", jsonArray);
response.setContentType("application/json");
response.setCharacterEncoding("utf8");
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.setContentType("application/json");
response.setCharacterEncoding("utf8");
response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
}
break;
default:
response.setContentType("text");
response.setCharacterEncoding("utf8");
if (error) {
errorMessage.append("\n");
errorMessage.append(helpMessage);
}
response.getWriter().print(errorMessage.toString());
}
// } catch (Exception e) {
// LOG.error(e);
// out.println(helpMessage);
// out.println(e.toString());
// }
}
use of org.cerberus.crud.service.ILogEventService in project cerberus-source by cerberustesting.
the class DisableEnvironmentV000 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 {
PrintWriter out = response.getWriter();
String charset = request.getCharacterEncoding();
// Loading Services.
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
ICountryEnvParamService countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
IInvariantService invariantService = appContext.getBean(IInvariantService.class);
IBuildRevisionInvariantService buildRevisionInvariantService = appContext.getBean(IBuildRevisionInvariantService.class);
IEmailService emailService = appContext.getBean(IEmailService.class);
ICountryEnvParam_logService countryEnvParam_logService = appContext.getBean(ICountryEnvParam_logService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
/**
* Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(ILogEventService.class);
logEventService.createForPublicCalls("/DisableEnvironmentV000", "CALL", "DisableEnvironmentV000 called : " + request.getRequestURL(), request);
// Parsing all parameters.
String system = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("system"), "", charset);
String country = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("country"), "", charset);
String environment = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("environment"), "", charset);
// Defining help message.
String helpMessage = "\nThis servlet is used to inform Cerberus that a system is disabled. For example when a Revision is beeing deployed.\n\nParameter list :\n" + "- system [mandatory] : the system where the Build Revision has been deployed. [" + system + "]\n" + "- country [mandatory] : the country where the Build Revision has been deployed. You can use ALL if you want to perform the action for all countries that exist for the given system and environement. [" + country + "]\n" + "- environment [mandatory] : the environment where the Build Revision has been deployed. [" + environment + "]\n";
// Checking the parameter validity.
boolean error = false;
if (system.equalsIgnoreCase("")) {
out.println("Error - Parameter system is mandatory.");
error = true;
}
if (!system.equalsIgnoreCase("") && !invariantService.isInvariantExist("SYSTEM", system)) {
out.println("Error - System does not exist : " + system);
error = true;
}
if (environment.equalsIgnoreCase("")) {
out.println("Error - Parameter environment is mandatory.");
error = true;
}
if (!environment.equalsIgnoreCase("") && !invariantService.isInvariantExist("ENVIRONMENT", environment)) {
out.println("Error - Environment does not exist : " + environment);
error = true;
}
if (country.equalsIgnoreCase("")) {
out.println("Error - Parameter country is mandatory.");
error = true;
} else if (!country.equalsIgnoreCase(PARAMETERALL)) {
if (!invariantService.isInvariantExist("COUNTRY", country)) {
out.println("Error - Country does not exist : " + country);
error = true;
}
if (!error) {
if (!countryEnvParamService.exist(system, country, environment)) {
out.println("Error - System/Country/Environment does not exist : " + system + "/" + country + "/" + environment);
error = true;
}
}
}
// Starting the database update only when no blocking error has been detected.
if (error == false) {
/**
* Getting the list of objects to treat.
*/
MessageEvent msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg);
AnswerList answerList = new AnswerList();
if (country.equalsIgnoreCase(PARAMETERALL)) {
country = null;
}
answerList = countryEnvParamService.readByVarious(system, country, environment, null, null, null);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) answerList);
for (CountryEnvParam cepData : (List<CountryEnvParam>) answerList.getDataList()) {
/**
* For each object, we can update it.
*/
cepData.setActive(false);
Answer answerUpdate = countryEnvParamService.update(cepData);
if (!(answerUpdate.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()))) {
/**
* Object could not be updated. We stop here and report the
* error.
*/
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, answerUpdate);
} else {
/**
* Update was successful.
*/
// Adding Log entry.
logEventService.createForPrivateCalls("/DisableEnvironmentV000", "UPDATE", "Updated CountryEnvParam : ['" + cepData.getSystem() + "','" + cepData.getCountry() + "','" + cepData.getEnvironment() + "']", request);
// Adding CountryEnvParam Log entry.
countryEnvParam_logService.createLogEntry(cepData.getSystem(), cepData.getCountry(), cepData.getEnvironment(), "", "", "Disabled.", "PublicCall");
/**
* Email notification.
*/
// Email Calculation.
String eMailContent;
String OutputMessage = "";
MessageEvent me = emailService.generateAndSendDisableEnvEmail(cepData.getSystem(), cepData.getCountry(), cepData.getEnvironment());
if (!"OK".equals(me.getMessage().getCodeString())) {
LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched." + me.getMessage().getDescription());
logEventService.createForPrivateCalls("/DisableEnvironmentV000", "DISABLE", "Warning on Disable environment : ['" + cepData.getSystem() + "','" + cepData.getCountry() + "','" + cepData.getEnvironment() + "'] " + me.getMessage().getDescription(), request);
OutputMessage = me.getMessage().getDescription();
}
if (OutputMessage.equals("")) {
msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer answerSMTP = new AnswerList(msg);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, answerSMTP);
} else {
msg = new MessageEvent(MessageEventEnum.GENERIC_WARNING);
msg.setDescription(msg.getDescription().replace("%REASON%", OutputMessage + " when sending email for " + cepData.getSystem() + "/" + cepData.getCountry() + "/" + cepData.getEnvironment()));
Answer answerSMTP = new AnswerList(msg);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, answerSMTP);
}
}
}
/**
* Formating and returning the result.
*/
out.println(finalAnswer.getResultMessage().getMessage().getCodeString() + " - " + finalAnswer.getResultMessage().getDescription());
} else {
// In case of errors, we display the help message.
out.println(helpMessage);
}
}
use of org.cerberus.crud.service.ILogEventService in project cerberus-source by cerberustesting.
the class NewChain 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, JSONException {
JSONObject jsonResponse = new JSONObject();
AnswerItem answerItem = new AnswerItem();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
answerItem.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
response.setContentType("application/json");
/**
* Parsing and securing all required parameters.
*/
String system = policy.sanitize(request.getParameter("system"));
String country = policy.sanitize(request.getParameter("country"));
String env = policy.sanitize(request.getParameter("environment"));
String chain = policy.sanitize(request.getParameter("chain"));
// Init Answer with potencial error from Parsing parameter.
// AnswerItem answer = new AnswerItem(msg);
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IEmailService emailService = appContext.getBean(IEmailService.class);
ICountryEnvParamService countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
IBuildRevisionBatchService buildRevisionBatchService = appContext.getBean(IBuildRevisionBatchService.class);
ILogEventService logEventService = appContext.getBean(ILogEventService.class);
if (request.getParameter("system") == null) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "System name is missing!"));
answerItem.setResultMessage(msg);
} else if (request.getParameter("country") == null) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Country is missing!"));
answerItem.setResultMessage(msg);
} else if (request.getParameter("environment") == null) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Environment is missing!"));
answerItem.setResultMessage(msg);
} else if (request.getParameter("chain") == null) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Chain is missing!"));
answerItem.setResultMessage(msg);
} else {
// All parameters are OK we can start performing the operation.
// Getting the contryEnvParam based on the parameters.
answerItem = countryEnvParamService.readByKey(system, country, env);
if (!(answerItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && answerItem.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%", OBJECT_NAME).replace("%OPERATION%", OPERATION).replace("%REASON%", OBJECT_NAME + " ['" + system + "','" + country + "','" + env + "'] does not exist. Cannot register a new event!"));
answerItem.setResultMessage(msg);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
// Adding BuildRevisionBatch entry.
// Adding CountryEnvParam Log entry.
CountryEnvParam cepData = (CountryEnvParam) answerItem.getItem();
buildRevisionBatchService.create(system, country, env, cepData.getBuild(), cepData.getRevision(), chain);
/**
* Email notification.
*/
String OutputMessage = "";
MessageEvent me = emailService.generateAndSendNewChainEmail(system, country, env, chain);
if (!"OK".equals(me.getMessage().getCodeString())) {
LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched." + me.getMessage().getDescription());
logEventService.createForPrivateCalls("/NewChain", "NEWCHAIN", "Warning on registering new event on environment : ['" + system + "','" + country + "','" + env + "'] " + me.getMessage().getDescription(), request);
OutputMessage = me.getMessage().getDescription();
}
if (OutputMessage.equals("")) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION));
answerItem.setResultMessage(msg);
} else {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).concat(" Just one warning : ").concat(OutputMessage));
answerItem.setResultMessage(msg);
}
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", answerItem.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", answerItem.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.cerberus.crud.service.ILogEventService in project cerberus-source by cerberustesting.
the class CreateUpdateTestCaseExecutionFile 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 org.cerberus.exception.CerberusException
* @throws org.json.JSONException
*/
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();
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(), fileItem.getString("UTF-8"));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters
*/
// Parameter that needs to be secured --> We SECURE+DECODE them
String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(fileData.get("desc"), null, charset);
String extension = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(fileData.get("type"), "", charset);
String fileName = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(fileData.get("fileName"), null, charset);
Integer fileID = ParameterParserUtil.parseIntegerParam(fileData.get("fileID"), 0);
Integer idex = ParameterParserUtil.parseIntegerParam(fileData.get("idex"), 0);
boolean action = fileData.get("action") != null ? true : false;
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IRecorderService recorderService = appContext.getBean(IRecorderService.class);
TestCaseStepActionExecution testCaseStepActionExecution = null;
TestCaseStepActionControlExecution testCaseStepActionControlExecution = null;
JSONArray obj = null;
if (action) {
obj = new JSONArray(fileData.get("action"));
testCaseStepActionExecution = updateTestCaseStepActionExecutionFromJsonArray(obj, appContext);
} else {
obj = new JSONArray(fileData.get("control"));
testCaseStepActionControlExecution = updateTestCaseStepActionControlExecutionFromJsonArray(obj, appContext);
}
if (description.isEmpty()) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "manual testcase execution file").replace("%OPERATION%", "Create/Update").replace("%REASON%", "desc is missing!"));
ans.setResultMessage(msg);
} else {
ans = recorderService.recordManuallyFile(testCaseStepActionExecution, testCaseStepActionControlExecution, extension, description, file, idex, fileName, fileID);
}
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Object created. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/CreateUpdateTestCaseExecutionFile", "CREATE", "Create execution file", 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.crud.service.ILogEventService in project cerberus-source by cerberustesting.
the class DeleteTestCaseExecutionFile 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, JSONException, CerberusException {
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");
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
/**
* Parsing and securing all required parameters.
*/
Long fileId = ParameterParserUtil.parseLongParam(request.getParameter("fileID"), 0);
/**
* Checking all constrains before calling the services.
*/
if (fileId == null) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseExecutionFile").replace("%OPERATION%", "Delete").replace("%REASON%", "field fileID is missing!"));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
ITestCaseExecutionFileService testCaseExecutionFileService = appContext.getBean(ITestCaseExecutionFileService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
IRecorderService recorderService = appContext.getBean(IRecorderService.class);
AnswerItem resp = testCaseExecutionFileService.readByKey(fileId);
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%", "TestCaseExecutionFile").replace("%OPERATION%", "Delete").replace("%REASON%", "TestCaseExecutionFile with this ID 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.
*/
TestCaseExecutionFile testCaseExecutionFile = (TestCaseExecutionFile) resp.getItem();
String rootFolder = parameterService.getParameterStringByKey("cerberus_exemanualmedia_path", "", "");
testCaseExecutionFileService.deleteFile(rootFolder, testCaseExecutionFile.getFileName());
ans = testCaseExecutionFileService.delete(testCaseExecutionFile);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Delete was successful. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/DeleteTestCaseExecutionFile", "DELETE", "Delete TestCase Execution File : ['" + testCaseExecutionFile + "']", 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