Search in sources :

Example 1 with IExecutionThreadPoolService

use of org.cerberus.engine.threadpool.IExecutionThreadPoolService 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();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) FactoryCreationException(org.cerberus.exception.FactoryCreationException) ApplicationContext(org.springframework.context.ApplicationContext) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService) JSONArray(org.json.JSONArray) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) FactoryCreationException(org.cerberus.exception.FactoryCreationException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) Answer(org.cerberus.util.answer.Answer) JSONObject(org.json.JSONObject) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) ITagService(org.cerberus.crud.service.ITagService)

Example 2 with IExecutionThreadPoolService

use of org.cerberus.engine.threadpool.IExecutionThreadPoolService 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();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) ITagService(org.cerberus.crud.service.ITagService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService)

Example 3 with IExecutionThreadPoolService

use of org.cerberus.engine.threadpool.IExecutionThreadPoolService in project cerberus-source by cerberustesting.

the class GetExecutionQueue 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.json.JSONException
 * @throws org.cerberus.exception.CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException, CerberusException {
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    boolean check = ParameterParserUtil.parseBooleanParam(request.getParameter("check"), false);
    boolean push = ParameterParserUtil.parseBooleanParam(request.getParameter("push"), false);
    if (check) {
        IApplicationService applicationService = appContext.getBean(IApplicationService.class);
        IInvariantService invariantService = appContext.getBean(IInvariantService.class);
        ITestService testService = appContext.getBean(ITestService.class);
        ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
        ICountryEnvParamService cepService = appContext.getBean(ICountryEnvParamService.class);
        IParameterService parameterService = appContext.getBean(IParameterService.class);
        testCaseExecutionService = appContext.getBean(ITestCaseExecutionService.class);
        List<ExecutionValidator> inQueue = new ArrayList<>();
        JSONArray testCaseList = new JSONArray(request.getParameter("testcase"));
        JSONArray environmentList = new JSONArray(request.getParameter("environment"));
        JSONArray countryList = new JSONArray(request.getParameter("countries"));
        /**
         * Creating all the list from the JSON to call the services
         */
        List<TestCase> TCList = new ArrayList<>();
        List<String> envList = new ArrayList<>();
        List<String> countries = new ArrayList<>();
        for (int index = 0; index < testCaseList.length(); index++) {
            JSONObject testCaseJson = testCaseList.getJSONObject(index);
            TestCase tc = new TestCase();
            tc.setTest(testCaseJson.getString("test"));
            tc.setTestCase(testCaseJson.getString("testcase"));
            TCList.add(tc);
        }
        for (int index = 0; index < environmentList.length(); index++) {
            String environment = environmentList.getString(index);
            envList.add(environment);
        }
        for (int index = 0; index < countryList.length(); index++) {
            String country = countryList.getString(index);
            countries.add(country);
        }
        List<TestCaseExecution> tceList = testCaseExecutionService.createAllTestCaseExecution(TCList, envList, countries);
        IExecutionCheckService execCheckService = appContext.getBean(IExecutionCheckService.class);
        for (TestCaseExecution execution : tceList) {
            boolean exception = false;
            ExecutionValidator validator = new ExecutionValidator();
            try {
                execution.setTestObj(testService.convert(testService.readByKey(execution.getTest())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_TEST_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%TEST%", execution.getTest()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            try {
                execution.setTestCaseObj(testCaseService.findTestCaseByKey(execution.getTest(), execution.getTestCase()));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_TESTCASE_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%TEST%", execution.getTest()));
                mes.setDescription(mes.getDescription().replace("%TESTCASE%", execution.getTestCase()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            try {
                execution.setApplicationObj(applicationService.convert(applicationService.readByKey(execution.getTestCaseObj().getApplication())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_APPLICATION_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%APPLI%", execution.getTestCaseObj().getApplication()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            execution.setEnvironmentData(execution.getEnvironment());
            try {
                execution.setCountryEnvParam(cepService.convert(cepService.readByKey(execution.getApplicationObj().getSystem(), execution.getCountry(), execution.getEnvironment())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_COUNTRYENV_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%SYSTEM%", execution.getApplicationObj().getSystem()));
                mes.setDescription(mes.getDescription().replace("%COUNTRY%", execution.getCountry()));
                mes.setDescription(mes.getDescription().replace("%ENV%", execution.getEnvironmentData()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            try {
                execution.setEnvironmentDataObj(invariantService.convert(invariantService.readByKey("ENVIRONMENT", execution.getEnvironmentData())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_ENVIRONMENT_DOESNOTEXIST);
                mes.setDescription(mes.getDescription().replace("%ENV%", execution.getEnvironmentData()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            String browser = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_BROWSER), DEFAULT_VALUE_BROWSER);
            if (!(StringUtil.isNullOrEmpty(browser))) {
                // if application is not GUI, we force browser to empty value.
                if (execution.getApplicationObj() != null && execution.getApplicationObj().getType() != null && !(execution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI))) {
                    execution.setBrowser("");
                }
            } else {
                execution.setBrowser(browser);
            }
            String manualExecution = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION);
            execution.setManualExecution(manualExecution);
            if (exception == false) {
                /**
                 * Checking the execution as it would be checked in the
                 * engine
                 */
                MessageGeneral message = execCheckService.checkTestCaseExecution(execution);
                if (!(message.equals(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_CHECKINGPARAMETERS)))) {
                    validator.setValid(false);
                    validator.setMessage(message.getDescription());
                } else {
                    validator.setValid(true);
                    validator.setMessage("Valid Execution.");
                }
            }
            validator.setExecution(execution);
            inQueue.add(validator);
        }
        JSONArray dataArray = new JSONArray();
        for (ExecutionValidator tce : inQueue) {
            JSONObject exec = new JSONObject();
            exec.put("test", tce.getExecution().getTest());
            exec.put("testcase", tce.getExecution().getTestCase());
            exec.put("env", tce.getExecution().getEnvironment());
            exec.put("country", tce.getExecution().getCountry());
            exec.put("appType", tce.getExecution().getApplicationObj().getType());
            exec.put("isValid", tce.isValid());
            exec.put("message", tce.getMessage());
            dataArray.put(exec);
        }
        jsonResponse.put("contentTable", dataArray);
    }
    if (push) {
        IExecutionThreadPoolService executionThreadService = appContext.getBean(IExecutionThreadPoolService.class);
        IParameterService parameterService = appContext.getBean(IParameterService.class);
        IFactoryTestCaseExecutionQueue inQueueFactoryService = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
        ITestCaseExecutionQueueService inQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
        int addedToQueue = 0;
        JSONArray toAddList = new JSONArray(request.getParameter("toAddList"));
        JSONArray browsers = new JSONArray(request.getParameter("browsers"));
        Date requestDate = new Date();
        /**
         * RETRIEVING ROBOT SETTINGS *
         */
        String robot = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_ROBOT), null);
        String robotIP = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_ROBOT_IP), null);
        String robotPort = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_ROBOT_PORT), null);
        String browserVersion = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_BROWSER_VERSION), null);
        String platform = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_PLATFORM), null);
        String screenSize = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_SCREENSIZE), null);
        /**
         * RETRIEVING EXECUTION SETTINGS *
         */
        String tag = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_TAG), "");
        int screenshot = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_SCREENSHOT), DEFAULT_VALUE_SCREENSHOT);
        int verbose = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_VERBOSE), DEFAULT_VALUE_VERBOSE);
        String timeout = request.getParameter(PARAMETER_TIMEOUT);
        int pageSource = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_PAGE_SOURCE), DEFAULT_VALUE_PAGE_SOURCE);
        int seleniumLog = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_SELENIUM_LOG), DEFAULT_VALUE_SELENIUM_LOG);
        int retries = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_RETRIES), DEFAULT_VALUE_RETRIES);
        String manualExecution = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION);
        /**
         * RETRIEVING MANUAL ENVIRONMENT SETTINGS *
         */
        String manualHost = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_HOST), null);
        String manualContextRoot = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_CONTEXT_ROOT), null);
        String manualLoginRelativeURL = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_LOGIN_RELATIVE_URL), null);
        String manualEnvData = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_ENV_DATA), null);
        // Create Tag when exist.
        if (!StringUtil.isNullOrEmpty(tag)) {
            // We create or update it.
            ITagService tagService = appContext.getBean(ITagService.class);
            tagService.createAuto(tag, "", request.getRemoteUser());
        }
        for (int index = 0; index < toAddList.length(); index++) {
            JSONObject toAdd = toAddList.getJSONObject(index);
            int manualURL = 0;
            if (toAdd.getString("env").equals("MANUAL")) {
                manualURL = 1;
            }
            try {
                // Create the template
                TestCaseExecutionQueue tceiq = inQueueFactoryService.create(toAdd.getString("test"), toAdd.getString("testcase"), toAdd.getString("country"), toAdd.getString("env"), robot, robotIP, robotPort, "", browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, 1000, request.getRemoteUser(), null, null, null);
                // Then fill it with either no browser
                if ((browsers.length() == 0) || ((toAdd.getString("appType") != null) && (!toAdd.getString("appType").equalsIgnoreCase(Application.TYPE_GUI)))) {
                    inQueueService.convert(inQueueService.create(tceiq));
                    addedToQueue++;
                } else // Or with required browsers
                {
                    for (int iterBrowser = 0; iterBrowser < browsers.length(); iterBrowser++) {
                        tceiq.setBrowser(browsers.getString(iterBrowser));
                        try {
                            inQueueService.convert(inQueueService.create(tceiq));
                            addedToQueue++;
                        } catch (CerberusException e) {
                            LOG.warn("Unable to insert execution in queue " + tceiq, e);
                        }
                    }
                }
            } catch (FactoryCreationException e) {
                LOG.warn("Unable to create the execution queue template", e);
            }
        }
        // Trigger execution if necessary
        if (addedToQueue > 0) {
            try {
                executionThreadService.executeNextInQueueAsynchroneously(false);
            } catch (CerberusException ex) {
                String errorMessage = "Unable to feed the execution queue due to " + ex.getMessage();
                LOG.warn(errorMessage);
                answer.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED));
                answer.getResultMessage().setDescription(errorMessage);
            }
            jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
            jsonResponse.put("message", answer.getResultMessage().getDescription());
            jsonResponse.put("addedToQueue", addedToQueue);
            jsonResponse.put("redirect", "ReportingExecutionByTag.jsp?Tag=" + StringUtil.encodeAsJavaScriptURIComponent(tag));
        }
    }
    response.setContentType("application/json");
    response.getWriter().print(jsonResponse.toString());
}
Also used : IExecutionCheckService(org.cerberus.engine.execution.IExecutionCheckService) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) IParameterService(org.cerberus.crud.service.IParameterService) ITestCaseExecutionService(org.cerberus.crud.service.ITestCaseExecutionService) ExecutionValidator(org.cerberus.dto.ExecutionValidator) FactoryCreationException(org.cerberus.exception.FactoryCreationException) ApplicationContext(org.springframework.context.ApplicationContext) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) ITestService(org.cerberus.crud.service.ITestService) ITestCaseService(org.cerberus.crud.service.ITestCaseService) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) IApplicationService(org.cerberus.crud.service.IApplicationService) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService) TestCaseExecution(org.cerberus.crud.entity.TestCaseExecution) CerberusException(org.cerberus.exception.CerberusException) IInvariantService(org.cerberus.crud.service.IInvariantService) JSONArray(org.json.JSONArray) AnswerItem(org.cerberus.util.answer.AnswerItem) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) Date(java.util.Date) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) ITagService(org.cerberus.crud.service.ITagService) ICountryEnvParamService(org.cerberus.crud.service.ICountryEnvParamService)

Aggregations

TestCaseExecutionQueue (org.cerberus.crud.entity.TestCaseExecutionQueue)3 ITagService (org.cerberus.crud.service.ITagService)3 ITestCaseExecutionQueueService (org.cerberus.crud.service.ITestCaseExecutionQueueService)3 MessageEvent (org.cerberus.engine.entity.MessageEvent)3 IExecutionThreadPoolService (org.cerberus.engine.threadpool.IExecutionThreadPoolService)3 CerberusException (org.cerberus.exception.CerberusException)3 AnswerItem (org.cerberus.util.answer.AnswerItem)3 JSONObject (org.json.JSONObject)3 ApplicationContext (org.springframework.context.ApplicationContext)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 ServletException (javax.servlet.ServletException)2 IFactoryTestCaseExecutionQueue (org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue)2 ILogEventService (org.cerberus.crud.service.ILogEventService)2 LogEventService (org.cerberus.crud.service.impl.LogEventService)2 FactoryCreationException (org.cerberus.exception.FactoryCreationException)2 Answer (org.cerberus.util.answer.Answer)2 JSONArray (org.json.JSONArray)2 JSONException (org.json.JSONException)2 PolicyFactory (org.owasp.html.PolicyFactory)2