Search in sources :

Example 31 with TestCaseStep

use of org.cerberus.crud.entity.TestCaseStep in project cerberus-source by cerberustesting.

the class CreateTestCase method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("test"), "");
    String testcase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("testCase"), "");
    String originalTest = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTest"), "");
    String originalTestCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTestCase"), "");
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(test) && StringUtil.isNullOrEmpty(testcase)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Case").replace("%OPERATION%", "Create").replace("%REASON%", "mandatory fields (test or testcase) are missing."));
        finalAnswer.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        testCaseService = appContext.getBean(ITestCaseService.class);
        testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);
        testCaseLabelFactory = appContext.getBean(IFactoryTestCaseLabel.class);
        testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
        testCaseCountryFactory = appContext.getBean(IFactoryTestCaseCountry.class);
        testCaseCountryPropertiesService = appContext.getBean(ITestCaseCountryPropertiesService.class);
        testCaseStepService = appContext.getBean(ITestCaseStepService.class);
        testCaseStepActionService = appContext.getBean(ITestCaseStepActionService.class);
        testCaseStepActionControlService = appContext.getBean(ITestCaseStepActionControlService.class);
        TestCase testCaseData = getTestCaseFromRequest(request);
        ans = testCaseService.create(testCaseData);
        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateTestCase", "CREATE", "Create TestCase : ['" + testcase + "']", request);
            // Update labels
            if (request.getParameter("labelList") != null) {
                JSONArray objLabelArray = new JSONArray(request.getParameter("labelList"));
                List<TestCaseLabel> labelList = new ArrayList();
                labelList = getLabelListFromRequest(request, appContext, test, testcase, objLabelArray);
                // Update the Database with the new list.
                ans = testCaseLabelService.compareListAndUpdateInsertDeleteElements(test, testcase, labelList);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
            }
            // Update Countries
            if (request.getParameter("countryList") != null) {
                JSONArray objCountryArray = new JSONArray(request.getParameter("countryList"));
                List<TestCaseCountry> tccList = new ArrayList();
                tccList = getCountryListFromRequest(request, appContext, test, testcase, objCountryArray);
                // Update the Database with the new list.
                ans = testCaseCountryService.compareListAndUpdateInsertDeleteElements(test, testcase, tccList);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                // Duplicate other objects.
                List<TestCaseCountryProperties> tccpList = new ArrayList();
                List<TestCaseCountryProperties> newTccpList = new ArrayList();
                if (!tccList.isEmpty() && ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    tccpList = testCaseCountryPropertiesService.findListOfPropertyPerTestTestCase(originalTest, originalTestCase);
                    // Build a new list with the countries that exist for the testcase.
                    for (TestCaseCountryProperties curTccp : tccpList) {
                        if (testCaseCountryService.exist(test, testcase, curTccp.getCountry())) {
                            newTccpList.add(curTccp);
                        }
                    }
                    if (!newTccpList.isEmpty()) {
                        ans = testCaseCountryPropertiesService.duplicateList(newTccpList, test, testcase);
                        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    }
                }
            }
            List<TestCaseStep> tcsList = new ArrayList();
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                tcsList = testCaseStepService.getListOfSteps(originalTest, originalTestCase);
                if (!tcsList.isEmpty()) {
                    ans = testCaseStepService.duplicateList(tcsList, test, testcase);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
            }
            List<TestCaseStepAction> tcsaList = new ArrayList();
            if (!tcsList.isEmpty() && ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                tcsaList = testCaseStepActionService.findTestCaseStepActionbyTestTestCase(originalTest, originalTestCase);
                if (!tcsaList.isEmpty()) {
                    ans = testCaseStepActionService.duplicateList(tcsaList, test, testcase);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
            }
            if (!tcsList.isEmpty() && !tcsaList.isEmpty() && ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                List<TestCaseStepActionControl> tcsacList = testCaseStepActionControlService.findControlByTestTestCase(originalTest, originalTestCase);
                if (!tcsacList.isEmpty()) {
                    ans = testCaseStepActionControlService.duplicateList(tcsacList, test, testcase);
                    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 : ITestCaseStepActionService(org.cerberus.crud.service.ITestCaseStepActionService) TestCaseStepAction(org.cerberus.crud.entity.TestCaseStepAction) TestCaseCountryProperties(org.cerberus.crud.entity.TestCaseCountryProperties) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) ApplicationContext(org.springframework.context.ApplicationContext) ITestCaseCountryPropertiesService(org.cerberus.crud.service.ITestCaseCountryPropertiesService) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) TestCaseStepActionControl(org.cerberus.crud.entity.TestCaseStepActionControl) ITestCaseLabelService(org.cerberus.crud.service.ITestCaseLabelService) ITestCaseStepService(org.cerberus.crud.service.ITestCaseStepService) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) JSONArray(org.json.JSONArray) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) ITestCaseStepActionControlService(org.cerberus.crud.service.ITestCaseStepActionControlService) Answer(org.cerberus.util.answer.Answer) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel)

Example 32 with TestCaseStep

use of org.cerberus.crud.entity.TestCaseStep in project cerberus-source by cerberustesting.

the class DeleteTest 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();
    Answer ans = new Answer();
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    // Parsing and securing all required parameters.
    String key = policy.sanitize(request.getParameter("test"));
    // Checking all constrains before calling the services.
    if (StringUtil.isNull(key)) {
        ans.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED).resolveDescription("ITEM", "Test").resolveDescription("OPERATION", "Delete").resolveDescription("REASON", "Test name is missing."));
    } else {
        // All data seems cleans so we can call the services.
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestService testService = appContext.getBean(ITestService.class);
        AnswerItem resp = testService.readByKey(key);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
            // Object could not be found. We stop here and report the error.
            ans.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED).resolveDescription("ITEM", "Test").resolveDescription("OPERATION", "Delete").resolveDescription("REASON", "Test does not exist"));
        } else {
            // The service was able to perform the query and confirm the object exist
            Test testData = (Test) resp.getItem();
            // Check if there is no associated Test Cases defining Step which is used OUTSIDE of the deleting Test
            try {
                final Collection<TestCaseStep> externallyUsedTestCaseSteps = externallyUsedTestCaseSteps(testData);
                if (!externallyUsedTestCaseSteps.isEmpty()) {
                    final String cerberusUrl = appContext.getBean(IParameterService.class).findParameterByKey("cerberus_url", "").getValue();
                    ans.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED).resolveDescription("ITEM", "Test").resolveDescription("OPERATION", "Delete").resolveDescription("REASON", "You are trying to remove a Test which contains Test Case Steps which are currently used by other Test Case Steps outside of the removing Test. Please remove this link before to proceed: " + Collections2.transform(externallyUsedTestCaseSteps, new Function<TestCaseStep, String>() {

                        @Override
                        @Nullable
                        public String apply(@Nullable final TestCaseStep input) {
                            return String.format("<a href='%s/TestCaseScript.jsp?test=%s&testcase=%s&step=%s'>%s/%s#%s</a>", cerberusUrl, input.getTest(), input.getTestCase(), input.getStep(), input.getTest(), input.getTestCase(), input.getStep());
                        }
                    })));
                } else {
                    // Test seems clean, process to delete
                    ans = testService.delete(testData);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                        // Delete was successful. Adding Log entry.
                        ILogEventService logEventService = appContext.getBean(LogEventService.class);
                        logEventService.createForPrivateCalls("/DeleteTest", "DELETE", "Delete Test : ['" + key + "']", request);
                    }
                }
            } catch (final CerberusException e) {
                LOGGER.error(e.getMessage(), e);
                ans.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION", "Unexpected error: " + e.getMessage()));
            }
        }
    }
    // 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();
}
Also used : CerberusException(org.cerberus.exception.CerberusException) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) AnswerItem(org.cerberus.util.answer.AnswerItem) Answer(org.cerberus.util.answer.Answer) Function(com.google.common.base.Function) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) ITestService(org.cerberus.crud.service.ITestService) Test(org.cerberus.crud.entity.Test) ILogEventService(org.cerberus.crud.service.ILogEventService) Nullable(javax.annotation.Nullable)

Example 33 with TestCaseStep

use of org.cerberus.crud.entity.TestCaseStep in project cerberus-source by cerberustesting.

the class UpdateTestCaseWithDependencies method getTestCaseStepFromParameter.

private List<TestCaseStep> getTestCaseStepFromParameter(HttpServletRequest request, ApplicationContext appContext, String test, String testCase, boolean duplicate) {
    List<TestCaseStep> testCaseStep = new ArrayList();
    ITestCaseStepService tcsService = appContext.getBean(ITestCaseStepService.class);
    String[] testcase_step_increment = getParameterValuesIfExists(request, "step_increment");
    IFactoryTestCaseStep testCaseStepFactory = appContext.getBean(IFactoryTestCaseStep.class);
    if (testcase_step_increment != null) {
        for (String inc : testcase_step_increment) {
            String delete = getParameterIfExists(request, "step_delete_" + inc);
            String stepInUse = getParameterIfExists(request, "step_InUseInOtherTestCase_" + inc);
            int step = getParameterIfExists(request, "step_technical_number_" + inc) == null ? 0 : Integer.parseInt(getParameterIfExists(request, "step_technical_number_" + inc));
            int sort = getParameterIfExists(request, "step_number_" + inc) == null ? 0 : Integer.parseInt(getParameterIfExists(request, "step_number_" + inc));
            int initialStep = getParameterIfExists(request, "initial_step_number_" + inc) == null ? 0 : Integer.parseInt(getParameterIfExists(request, "initial_step_number_" + inc));
            String loop = getParameterIfExists(request, "step_loop_" + inc);
            String conditionOper = getParameterIfExists(request, "step_conditionoper_" + inc);
            String conditionVal1 = getParameterIfExists(request, "step_conditionval1_" + inc);
            String conditionVal2 = getParameterIfExists(request, "step_conditionval2_" + inc);
            String desc = getParameterIfExists(request, "step_description_" + inc);
            String useStep = getParameterIfExists(request, "step_useStep_" + inc);
            String useStepChanged = getParameterIfExists(request, "step_useStepChanged_" + inc);
            String useStepTest = getParameterIfExists(request, "step_useStepTest_" + inc) == null ? "" : getParameterIfExists(request, "step_useStepTest_" + inc);
            String useStepTestCase = getParameterIfExists(request, "step_useStepTestCase_" + inc) == null ? "" : getParameterIfExists(request, "step_useStepTestCase_" + inc);
            String stepValue = getParameterIfExists(request, "step_useStepStep_" + inc);
            int useStepStep = stepValue == null || stepValue.equals("") ? -1 : Integer.parseInt(getParameterIfExists(request, "step_useStepStep_" + inc));
            String inLibrary = getParameterIfExists(request, "step_inLibrary_" + inc);
            /* If delete, don't add it to the list of steps */
            if (delete == null) {
                TestCaseStep tcStep = testCaseStepFactory.create(test, testCase, step, sort, loop, conditionOper, conditionVal1, conditionVal2, desc, useStep == null ? "N" : useStep, useStepTest, useStepTestCase, useStepStep, inLibrary == null ? "N" : inLibrary);
                /* Take action and control only if not use step*/
                if (useStep == null || useStep.equals("N")) {
                    String isToCopySteps = getParameterIfExists(request, "isToCopySteps_" + inc);
                    if (isToCopySteps != null && isToCopySteps.equals("Y")) {
                        // TODO:FN the information about the useStep should be cleared?
                        // tcStep.setTestCaseStepAction(tcsService.findTestCaseStep(useStepTest, useStepTestCase, useStepStep));
                        ITestCaseStepActionService tcsaService = appContext.getBean(TestCaseStepActionService.class);
                        ITestCaseStepActionControlService tcsacService = appContext.getBean(TestCaseStepActionControlService.class);
                        int stepNumber = Integer.parseInt(stepValue);
                        List<TestCaseStepAction> actions = tcsaService.getListOfAction(useStepTest, useStepTestCase, stepNumber);
                        for (TestCaseStepAction act : actions) {
                            List<TestCaseStepActionControl> controlsPerAction = tcsacService.findControlByTestTestCaseStepSequence(useStepTest, useStepTestCase, stepNumber, act.getSequence());
                            // these actions now belong to the current test case, therefore we need to change it
                            act.setTest(test);
                            act.setTestCase(testCase);
                            act.setStep(step);
                            List<TestCaseStepActionControl> updatedControlsPerAction = new ArrayList<TestCaseStepActionControl>();
                            for (TestCaseStepActionControl ctrl : controlsPerAction) {
                                ctrl.setTest(test);
                                ctrl.setTestCase(testCase);
                                ctrl.setStep(step);
                                updatedControlsPerAction.add(ctrl);
                            }
                            act.setTestCaseStepActionControl(updatedControlsPerAction);
                        }
                        tcStep.setTestCaseStepAction(actions);
                    } else {
                        tcStep.setTestCaseStepAction(getTestCaseStepActionFromParameter(request, appContext, test, testCase, inc));
                    }
                    // clears the information about the usestep
                    tcStep.setUseStep("N");
                    tcStep.setUseStepTest("");
                    tcStep.setUseStepTestCase("");
                    tcStep.setUseStepStep(-1);
                    // updates the test step action list with the new step
                    List<TestCaseStepAction> actionsForStep = tcStep.getTestCaseStepAction();
                    for (TestCaseStepAction ac : actionsForStep) {
                        List<TestCaseStepActionControl> actionControlList = ac.getTestCaseStepActionControl();
                        for (TestCaseStepActionControl acControl : actionControlList) {
                            acControl.setStep(step);
                        }
                        ac.setStep(step);
                    }
                // update the step associated with the actions that are now the new actions
                } else {
                    TestCaseStep tcs = null;
                    if (useStepStep != -1 && !useStepTest.equals("") && !useStepTestCase.equals("")) {
                        /* If use step, verify if used step alread use another one */
                        if ((useStepChanged != null && useStepChanged.equals("Y")) || duplicate) {
                            // if it is to duplicate then we need to get the new step information
                            // save the information about the test + testcase + step that was used to duplicate the test
                            tcs = tcsService.findTestCaseStep(useStepTest, useStepTestCase, useStepStep);
                            if (tcs != null) {
                                tcStep.setUseStepTest(tcs.getTest());
                                tcStep.setUseStepTestCase(tcs.getTestCase());
                                tcStep.setUseStepStep(tcs.getStep());
                            }
                        } else {
                            // if there was no changes then it uses the same information
                            tcs = tcsService.findTestCaseStep(test, testCase, step);
                            if (tcs != null) {
                                tcStep.setUseStepTest(tcs.getUseStepTest());
                                tcStep.setUseStepTestCase(tcs.getUseStepTestCase());
                                tcStep.setUseStepStep(tcs.getUseStepStep());
                            }
                        }
                    } else {
                        // does not defines a valid step, then keep as it was before
                        tcs = tcsService.findTestCaseStep(test, testCase, step);
                        if (tcs != null) {
                            tcStep.setUseStep("N");
                            tcStep.setUseStepTest(tcs.getUseStepTest());
                            tcStep.setUseStepTestCase(tcs.getUseStepTestCase());
                            tcStep.setUseStepStep(tcs.getUseStepStep());
                            tcStep.setTestCaseStepAction(getTestCaseStepActionFromParameter(request, appContext, test, testCase, inc));
                            List<TestCaseStepAction> actionsForStep = tcStep.getTestCaseStepAction();
                            for (TestCaseStepAction ac : actionsForStep) {
                                List<TestCaseStepActionControl> actionControlList = ac.getTestCaseStepActionControl();
                                for (TestCaseStepActionControl acControl : actionControlList) {
                                    acControl.setStep(step);
                                }
                                ac.setStep(step);
                            }
                        }
                    }
                    if (tcs != null) {
                        /**
                         * If description is empty, take the one from the
                         * use step
                         */
                        if (desc.equals("")) {
                            tcStep.setDescription(tcs.getDescription());
                        }
                    } else {
                        // if the step that should be defined is not imported then we should save the data
                        // and the test case should have the useStep = 'N'
                        tcStep.setUseStep("N");
                    }
                }
                if (stepInUse != null && stepInUse.equals("Y")) {
                    tcStep.setIsStepInUseByOtherTestCase(true);
                    tcStep.setInitialStep(initialStep);
                } else {
                    tcStep.setIsStepInUseByOtherTestCase(false);
                }
                testCaseStep.add(tcStep);
            }
        }
    }
    return testCaseStep;
}
Also used : ITestCaseStepActionService(org.cerberus.crud.service.ITestCaseStepActionService) IFactoryTestCaseStepAction(org.cerberus.crud.factory.IFactoryTestCaseStepAction) TestCaseStepAction(org.cerberus.crud.entity.TestCaseStepAction) ITestCaseStepService(org.cerberus.crud.service.ITestCaseStepService) ArrayList(java.util.ArrayList) IFactoryTestCaseStep(org.cerberus.crud.factory.IFactoryTestCaseStep) IFactoryTestCaseStep(org.cerberus.crud.factory.IFactoryTestCaseStep) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) ITestCaseStepActionControlService(org.cerberus.crud.service.ITestCaseStepActionControlService) TestCaseStepActionControl(org.cerberus.crud.entity.TestCaseStepActionControl) IFactoryTestCaseStepActionControl(org.cerberus.crud.factory.IFactoryTestCaseStepActionControl)

Example 34 with TestCaseStep

use of org.cerberus.crud.entity.TestCaseStep in project cerberus-source by cerberustesting.

the class ExecutionRunService method executeTestCase.

@Override
public TestCaseExecution executeTestCase(TestCaseExecution tCExecution) throws CerberusException {
    long runID = tCExecution.getId();
    String logPrefix = runID + " - ";
    /**
     * Feeding Build Rev of main Application system to
     * testcaseexecutionsysver table. Only if execution is not manual.
     */
    try {
        if (!(tCExecution.isManualURL())) {
            /**
             * Insert SystemVersion in Database
             */
            TestCaseExecutionSysVer myExeSysVer = null;
            try {
                LOG.debug(logPrefix + "Registering Main System Version.");
                myExeSysVer = factoryTestCaseExecutionSysVer.create(runID, tCExecution.getApplicationObj().getSystem(), tCExecution.getBuild(), tCExecution.getRevision());
                testCaseExecutionSysVerService.insertTestCaseExecutionSysVer(myExeSysVer);
            } catch (CerberusException ex) {
                LOG.error(logPrefix + ex.getMessage());
            }
            LOG.debug(logPrefix + "Main System Version Registered.");
            /**
             * For all Linked environment, we also keep track on the
             * build/rev information inside testcaseexecutionsysver table.
             */
            LOG.debug(logPrefix + "Registering Linked System Version.");
            try {
                List<CountryEnvLink> ceLink = null;
                ceLink = countryEnvLinkService.convert(countryEnvLinkService.readByVarious(tCExecution.getApplicationObj().getSystem(), tCExecution.getCountry(), tCExecution.getEnvironment()));
                for (CountryEnvLink myCeLink : ceLink) {
                    LOG.debug(logPrefix + "Linked environment found : " + myCeLink.getSystemLink() + myCeLink.getCountryLink() + myCeLink.getEnvironmentLink());
                    CountryEnvParam mycountEnvParam;
                    try {
                        mycountEnvParam = this.countryEnvParamService.convert(this.countryEnvParamService.readByKey(myCeLink.getSystemLink(), myCeLink.getCountryLink(), myCeLink.getEnvironmentLink()));
                        myExeSysVer = factoryTestCaseExecutionSysVer.create(runID, myCeLink.getSystemLink(), mycountEnvParam.getBuild(), mycountEnvParam.getRevision());
                        testCaseExecutionSysVerService.insertTestCaseExecutionSysVer(myExeSysVer);
                    } catch (CerberusException ex) {
                        // Referencial Integrity link between countryEnvLink and CountryEnvParam table should secure that exception to never happen.
                        LOG.error(logPrefix + ex.getMessage());
                        throw new CerberusException(ex.getMessageError());
                    }
                }
            } catch (CerberusException ex) {
                LOG.debug(logPrefix + "No Linked environment found.");
            }
            LOG.debug(logPrefix + "Linked System Version Registered.");
        }
        /**
         * Get used SeleniumCapabilities (empty if application is not GUI)
         */
        LOG.debug(logPrefix + "Getting Selenium capabitities for GUI applications.");
        if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)) {
            try {
                Capabilities caps = this.seleniumServerService.getUsedCapabilities(tCExecution.getSession());
                tCExecution.setBrowserFullVersion(caps.getBrowserName() + " " + caps.getVersion() + " " + caps.getPlatform().toString());
                tCExecution.setVersion(caps.getVersion());
                tCExecution.setPlatform(caps.getPlatform().toString());
            } catch (Exception ex) {
                LOG.error(logPrefix + "Exception on selenium getting Used Capabilities :" + ex.toString());
            }
            LOG.debug(logPrefix + "Selenium capabitities loaded.");
        } else {
            // If Selenium is not needed, the selenium and browser info is set to empty.
            tCExecution.setSeleniumIP("");
            tCExecution.setSeleniumPort("");
            tCExecution.setBrowser("");
            tCExecution.setVersion("");
            tCExecution.setPlatform("");
            tCExecution.setRobotDecli("");
            LOG.debug(logPrefix + "No Selenium capabitities loaded because application not GUI : " + tCExecution.getApplicationObj().getType());
        }
        tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%BROWSER%", tCExecution.getBrowser()));
        tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%BROWSERVERSION%", tCExecution.getVersion()));
        tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%PLATFORM%", tCExecution.getPlatform()));
        /**
         * Load PreTestCase information and set PreTCase to the
         * TestCaseExecution object
         */
        tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_LOADINGDETAILEDDATA));
        LOG.debug(logPrefix + "Loading Pre-testcases.");
        List<TestCase> preTests = testCaseService.findTestCaseActiveByCriteria("Pre Testing", tCExecution.getTestCaseObj().getApplication(), tCExecution.getCountry());
        tCExecution.setPreTestCaseList(preTests);
        if (!(preTests == null)) {
            LOG.debug(logPrefix + "Loaded PreTest List. " + tCExecution.getPreTestCaseList().size() + " found.");
        }
        LOG.debug(logPrefix + "Pre-testcases Loaded.");
        /**
         * Load Main TestCase with Step dependencies (Actions/Control)
         */
        LOG.debug(logPrefix + "Loading all Steps information of Main testcase.");
        List<TestCaseStep> testCaseStepList;
        testCaseStepList = this.loadTestCaseService.loadTestCaseStep(tCExecution.getTestCaseObj());
        tCExecution.getTestCaseObj().setTestCaseStep(testCaseStepList);
        LOG.debug(logPrefix + "Steps information of Main testcase Loaded : " + tCExecution.getTestCaseObj().getTestCaseStep().size() + " Step(s) found.");
        /**
         * Load Pre TestCase with Step dependencies (Actions/Control)
         */
        LOG.debug(logPrefix + "Loading all Steps information (Actions & Controls) of all Pre-testcase.");
        List<TestCaseStep> preTestCaseStepList = new ArrayList<TestCaseStep>();
        List<TestCase> preTestCase = new ArrayList<TestCase>();
        for (TestCase myTCase : tCExecution.getPreTestCaseList()) {
            myTCase.setTestCaseStep(this.loadTestCaseService.loadTestCaseStep(myTCase));
            preTestCaseStepList.addAll(myTCase.getTestCaseStep());
            preTestCase.add(myTCase);
            LOG.debug(logPrefix + "Pre testcase : " + myTCase.getTest() + "-" + myTCase.getTestCase() + " Loaded With " + myTCase.getTestCaseStep().size() + " Step(s) found.");
        }
        tCExecution.setPreTestCaseList(preTestCase);
        LOG.debug(logPrefix + "All Steps information (Actions & Controls) of all Pre-testcase Loaded.");
        /**
         * Load All properties of the testcase
         */
        LOG.debug(logPrefix + "Loading all Properties.");
        List<TestCaseCountryProperties> tcProperties = new ArrayList();
        try {
            tcProperties = testCaseCountryPropertiesService.findAllWithDependencies(tCExecution.getTest(), tCExecution.getTestCase(), tCExecution.getCountry());
            tCExecution.setTestCaseCountryPropertyList(tcProperties);
        } catch (CerberusException ex) {
            LOG.warn("Exception getting all the properties : " + ex);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug(logPrefix + "All Properties Loaded. " + tcProperties.size() + " property(ies) found : " + tcProperties);
        }
        /**
         * Start Execution of the steps/Actions/controls Iterate Steps.
         * mainExecutionTestCaseStepList will contain the list of steps to
         * execute for both pretest and test. This is where we schedule the
         * execution of the steps using mainExecutionTestCaseStepList
         * object.
         */
        LOG.debug(logPrefix + "Starting the execution with step iteration.");
        List<TestCaseStep> mainExecutionTestCaseStepList;
        mainExecutionTestCaseStepList = new ArrayList<TestCaseStep>();
        mainExecutionTestCaseStepList.addAll(preTestCaseStepList);
        mainExecutionTestCaseStepList.addAll(testCaseStepList);
        /**
         * Initialize the global TestCaseExecution Data List.
         */
        // 
        tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTEXECUTING));
        try {
            testCaseExecutionService.updateTCExecution(tCExecution);
        } catch (CerberusException ex) {
            LOG.warn(ex);
        }
        // Websocket --> we refresh the corresponding Detail Execution pages attached to this execution.
        if (tCExecution.isCerberus_featureflipping_activatewebsocketpush()) {
            TestCaseExecutionEndPoint.getInstance().send(tCExecution, true);
        }
        // Evaluate the condition at the step level.
        AnswerItem<Boolean> conditionAnswerTc;
        AnswerItem<String> answerDecode = new AnswerItem();
        boolean conditionDecodeError = false;
        /**
         * If execution is not manual, evaluate the condition at the step
         * level
         */
        if (!tCExecution.getManualExecution().equals("Y")) {
            try {
                answerDecode = variableService.decodeStringCompletly(tCExecution.getConditionVal1(), tCExecution, null, false);
                tCExecution.setConditionVal1((String) answerDecode.getItem());
                if (!(answerDecode.isCodeStringEquals("OK"))) {
                    // If anything wrong with the decode --> we stop here with decode message in the action result.
                    tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_CONDITIONDECODE).resolveDescription("MES", answerDecode.getMessageDescription()).resolveDescription("FIELD", "TestCase Condition Value1"));
                    tCExecution.setEnd(new Date().getTime());
                    LOG.debug("TestCase interupted due to decode 'TestCase Condition Value1' Error.");
                    conditionDecodeError = true;
                }
            } catch (CerberusEventException cex) {
                LOG.warn(cex);
            }
            try {
                answerDecode = variableService.decodeStringCompletly(tCExecution.getConditionVal2(), tCExecution, null, false);
                tCExecution.setConditionVal2((String) answerDecode.getItem());
                if (!(answerDecode.isCodeStringEquals("OK"))) {
                    // If anything wrong with the decode --> we stop here with decode message in the action result.
                    tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_CONDITIONDECODE).resolveDescription("MES", answerDecode.getMessageDescription()).resolveDescription("FIELD", "TestCase Condition Value2"));
                    tCExecution.setEnd(new Date().getTime());
                    LOG.debug("TestCase interupted due to decode 'TestCase Condition Value2' Error.");
                    conditionDecodeError = true;
                }
            } catch (CerberusEventException cex) {
                LOG.warn(cex);
            }
        }
        if (!conditionDecodeError) {
            conditionAnswerTc = this.conditionService.evaluateCondition(tCExecution.getConditionOper(), tCExecution.getConditionVal1(), tCExecution.getConditionVal2(), tCExecution);
            boolean execute_TestCase = (boolean) conditionAnswerTc.getItem();
            if (execute_TestCase || tCExecution.getManualExecution().equals("Y")) {
                for (TestCaseStep testCaseStep : mainExecutionTestCaseStepList) {
                    // init the index of the step in case we loop.
                    int step_index = 1;
                    boolean execute_Next_Step = false;
                    TestCaseStepExecution testCaseStepExecution;
                    int maxloop = parameterService.getParameterIntegerByKey("cerberus_loopstep_max", tCExecution.getApplicationObj().getSystem(), 20);
                    do {
                        /**
                         * Start Execution of TestCaseStep
                         */
                        LOG.debug("Start execution of testcasestep");
                        long startStep = new Date().getTime();
                        /**
                         * Create and Register TestCaseStepExecution
                         */
                        MessageEvent stepMess = new MessageEvent(MessageEventEnum.STEP_PENDING).resolveDescription("STEP", String.valueOf(testCaseStep.getSort())).resolveDescription("STEPINDEX", String.valueOf(step_index));
                        testCaseStepExecution = factoryTestCaseStepExecution.create(runID, testCaseStep.getTest(), testCaseStep.getTestCase(), testCaseStep.getStep(), step_index, testCaseStep.getSort(), testCaseStep.getLoop(), testCaseStep.getConditionOper(), testCaseStep.getConditionVal1(), testCaseStep.getConditionVal2(), testCaseStep.getConditionVal1(), testCaseStep.getConditionVal2(), null, startStep, 0, startStep, 0, new BigDecimal("0"), null, stepMess, testCaseStep, tCExecution, testCaseStep.getUseStep(), testCaseStep.getUseStepTest(), testCaseStep.getUseStepTestCase(), testCaseStep.getUseStepStep(), testCaseStep.getDescription());
                        testCaseStepExecution.setLoop(testCaseStep.getLoop());
                        testCaseStepExecutionService.insertTestCaseStepExecution(testCaseStepExecution);
                        testCaseStepExecution.setExecutionResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTSTARTED));
                        /**
                         * We populate the TestCaseStep inside the execution
                         * List
                         */
                        tCExecution.addTestCaseStepExecutionList(testCaseStepExecution);
                        // determine if step is executed (execute_Step) and if we trigger a new step execution after (execute_Next_Step)
                        boolean execute_Step = true;
                        boolean conditionStepDecodeError = false;
                        boolean conditionStepError = false;
                        AnswerItem<Boolean> conditionAnswer = new AnswerItem<>(new MessageEvent(MessageEventEnum.CONDITIONEVAL_FAILED_UNKNOWNCONDITION));
                        if (testCaseStepExecution.getLoop().equals(TestCaseStep.LOOP_ONCEIFCONDITIONFALSE) || testCaseStepExecution.getLoop().equals(TestCaseStep.LOOP_ONCEIFCONDITIONTRUE) || testCaseStepExecution.getLoop().equals(TestCaseStep.LOOP_WHILECONDITIONFALSEDO) || testCaseStepExecution.getLoop().equals(TestCaseStep.LOOP_WHILECONDITIONTRUEDO) || testCaseStepExecution.getLoop().equals("") || step_index > 1) {
                            // Decode Conditionvalue1 and Conditionvalue2 and Evaluate the condition at the Step level.
                            try {
                                answerDecode = variableService.decodeStringCompletly(testCaseStepExecution.getConditionVal1(), tCExecution, null, false);
                                testCaseStepExecution.setConditionVal1((String) answerDecode.getItem());
                                if (!(answerDecode.isCodeStringEquals("OK"))) {
                                    testCaseStepExecution.setExecutionResultMessage(new MessageGeneral(answerDecode.getResultMessage().getMessage()));
                                    testCaseStepExecution.setStepResultMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "Step Condition Value1"));
                                    testCaseStepExecution.setReturnMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "Step Condition Value1").getDescription());
                                    testCaseStepExecution.setReturnCode(answerDecode.getResultMessage().getCodeString());
                                    testCaseStepExecution.setStopExecution(answerDecode.getResultMessage().isStopTest());
                                    testCaseStepExecution.setEnd(new Date().getTime());
                                    LOG.debug("Step interupted due to decode 'Step Condition Value1' Error.");
                                    conditionStepDecodeError = true;
                                }
                            } catch (CerberusEventException cex) {
                                LOG.warn(cex);
                            }
                            if (!conditionStepDecodeError) {
                                try {
                                    answerDecode = variableService.decodeStringCompletly(testCaseStepExecution.getConditionVal2(), tCExecution, null, false);
                                    testCaseStepExecution.setConditionVal2((String) answerDecode.getItem());
                                    if (!(answerDecode.isCodeStringEquals("OK"))) {
                                        testCaseStepExecution.setExecutionResultMessage(new MessageGeneral(answerDecode.getResultMessage().getMessage()));
                                        testCaseStepExecution.setStepResultMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "Step Condition Value2"));
                                        testCaseStepExecution.setReturnMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "Step Condition Value2").getDescription());
                                        testCaseStepExecution.setReturnCode(answerDecode.getResultMessage().getCodeString());
                                        testCaseStepExecution.setStopExecution(answerDecode.getResultMessage().isStopTest());
                                        testCaseStepExecution.setEnd(new Date().getTime());
                                        LOG.debug("Step interupted due to decode 'Step Condition Value2' Error.");
                                        conditionStepDecodeError = true;
                                    }
                                } catch (CerberusEventException cex) {
                                    LOG.warn(cex);
                                }
                            }
                            if (!(conditionStepDecodeError)) {
                                conditionAnswer = this.conditionService.evaluateCondition(testCaseStepExecution.getConditionOper(), testCaseStepExecution.getConditionVal1(), testCaseStepExecution.getConditionVal2(), tCExecution);
                                execute_Step = (boolean) conditionAnswer.getItem();
                                if (conditionAnswer.getResultMessage().getMessage().getCodeString().equals("PE")) {
                                    // There were no error when performing the condition evaluation.
                                    switch(testCaseStepExecution.getLoop()) {
                                        case TestCaseStep.LOOP_ONCEIFCONDITIONFALSE:
                                            execute_Step = !execute_Step;
                                            execute_Next_Step = false;
                                            break;
                                        case TestCaseStep.LOOP_ONCEIFCONDITIONTRUE:
                                        case "":
                                            execute_Next_Step = false;
                                            break;
                                        case TestCaseStep.LOOP_WHILECONDITIONFALSEDO:
                                        case TestCaseStep.LOOP_DOWHILECONDITIONFALSE:
                                            execute_Step = !execute_Step;
                                            execute_Next_Step = execute_Step;
                                            break;
                                        case TestCaseStep.LOOP_WHILECONDITIONTRUEDO:
                                        case TestCaseStep.LOOP_DOWHILECONDITIONTRUE:
                                            execute_Next_Step = execute_Step;
                                            break;
                                        default:
                                            execute_Next_Step = false;
                                    }
                                } else {
                                    // Error when performing the condition evaluation. We force no execution (false)
                                    MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_CONDITION);
                                    mes.setDescription(mes.getDescription().replace("%AREA%", "step ").replace("%COND%", testCaseStepExecution.getConditionOper()).replace("%MES%", conditionAnswer.getResultMessage().getDescription()));
                                    tCExecution.setResultMessage(mes);
                                    testCaseStepExecution.setExecutionResultMessage(mes);
                                    testCaseStepExecution.setStepResultMessage(new MessageEvent(MessageEventEnum.CONDITION_TESTCASESTEP_FAILED).resolveDescription("AREA", "").resolveDescription("COND", testCaseStepExecution.getConditionOper()).resolveDescription("MESSAGE", conditionAnswer.getResultMessage().getDescription()));
                                    testCaseStepExecution.setEnd(new Date().getTime());
                                    LOG.debug("Step interupted due to condition error.");
                                    conditionStepError = true;
                                    execute_Next_Step = false;
                                    execute_Step = false;
                                }
                            } else {
                                // If anything wrong with the decode --> we stop here with decode message in the action result.
                                tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_CONDITIONDECODE).resolveDescription("AREA", "Step ").resolveDescription("MES", answerDecode.getMessageDescription()));
                                tCExecution.setEnd(new Date().getTime());
                                LOG.debug("TestCase interupted due to decode Condition Error.");
                                // There was an error on decode so we stop everything.
                                execute_Next_Step = false;
                                execute_Step = false;
                            }
                        } else if (testCaseStepExecution.getLoop().equals(TestCaseStep.LOOP_DOWHILECONDITIONFALSE) || testCaseStepExecution.getLoop().equals(TestCaseStep.LOOP_DOWHILECONDITIONTRUE)) {
                            // First Step execution for LOOP_DOWHILECONDITIONTRUE and LOOP_DOWHILECONDITIONFALSE --> We force the step execution and activate the next step execution.
                            execute_Step = true;
                            execute_Next_Step = true;
                        } else {
                            // First Step execution for Unknown Loop --> We force the step execution only once (default behaviour).
                            execute_Step = true;
                            execute_Next_Step = false;
                            conditionAnswer.setResultMessage(new MessageEvent(MessageEventEnum.CONDITIONEVAL_FAILED_UNKNOWNCONDITION));
                        }
                        /**
                         * Execute Step
                         */
                        LOG.debug(logPrefix + "Executing step : " + testCaseStepExecution.getTest() + " - " + testCaseStepExecution.getTestCase() + " - Step " + testCaseStepExecution.getStep() + " - Index " + testCaseStepExecution.getStep());
                        if (execute_Step) {
                            /**
                             * We execute the step
                             */
                            testCaseStepExecution = this.executeStep(testCaseStepExecution, tCExecution);
                            /**
                             * Updating Execution Result Message only if
                             * execution result message of the step is not
                             * PE or OK.
                             */
                            if ((!(testCaseStepExecution.getExecutionResultMessage().equals(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTSTARTED)))) && (!(testCaseStepExecution.getExecutionResultMessage().equals(new MessageGeneral(MessageGeneralEnum.EXECUTION_OK))))) {
                                tCExecution.setResultMessage(testCaseStepExecution.getExecutionResultMessage());
                            }
                            if (testCaseStepExecution.getStepResultMessage().equals(new MessageEvent(MessageEventEnum.STEP_PENDING))) {
                                testCaseStepExecution.setStepResultMessage(new MessageEvent(MessageEventEnum.STEP_SUCCESS));
                            }
                            testCaseStepExecutionService.updateTestCaseStepExecution(testCaseStepExecution);
                            if (testCaseStepExecution.isStopExecution()) {
                                break;
                            }
                        } else // We don't execute the step and record a generic execution.
                        if ((!conditionStepDecodeError) && (!conditionStepError)) {
                            /**
                             * Register Step in database
                             */
                            LOG.debug("Registering Step : " + testCaseStepExecution.getStep());
                            // We change the Step message only if the Step is not executed due to condition.
                            MessageEvent stepMes = new MessageEvent(MessageEventEnum.CONDITION_TESTCASESTEP_NOTEXECUTED);
                            testCaseStepExecution.setStepResultMessage(stepMes);
                            testCaseStepExecution.setReturnMessage(testCaseStepExecution.getReturnMessage().replace("%COND%", testCaseStepExecution.getConditionOper()).replace("%LOOP%", testCaseStepExecution.getLoop()).replace("%MESSAGE%", conditionAnswer.getResultMessage().getDescription()));
                            testCaseStepExecution.setEnd(new Date().getTime());
                            this.testCaseStepExecutionService.updateTestCaseStepExecution(testCaseStepExecution);
                            LOG.debug("Registered Step");
                        } else {
                            // Not executed because decode error or failed condition.
                            testCaseStepExecution.setEnd(new Date().getTime());
                            testCaseStepExecution.setStopExecution(true);
                            this.testCaseStepExecutionService.updateTestCaseStepExecution(testCaseStepExecution);
                            LOG.debug("Registered Step");
                        }
                        /**
                         * Log TestCaseStepExecution
                         */
                        if (tCExecution.getVerbose() > 0) {
                            LOG.info(testCaseStepExecution.toJson(false, true));
                        }
                        // Websocket --> we refresh the corresponding Detail Execution pages attached to this execution.
                        if (tCExecution.isCerberus_featureflipping_activatewebsocketpush()) {
                            TestCaseExecutionEndPoint.getInstance().send(tCExecution, false);
                        }
                        step_index++;
                    } while (execute_Next_Step && step_index <= maxloop);
                    if (testCaseStepExecution.isStopExecution()) {
                        break;
                    }
                }
                /**
                 * If at that time the execution is still PE, we move it to
                 * OK. It means that no issue were met.
                 */
                if ((tCExecution.getResultMessage() == null) || (tCExecution.getResultMessage().equals(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTSTARTED)))) {
                    tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_OK));
                }
                /**
                 * We record Selenium log at the end of the execution.
                 */
                try {
                    tCExecution.addFileList(recorderService.recordSeleniumLog(tCExecution));
                } catch (Exception ex) {
                    LOG.error(logPrefix + "Exception Getting Selenium Logs " + tCExecution.getId() + " Exception :" + ex.toString());
                }
            } else {
                // We don't execute the testcase linked with condition.
                MessageGeneral mes;
                /**
                 * Update Execution status from condition
                 */
                if (conditionAnswerTc.getResultMessage().getMessage().getCodeString().equals("PE")) {
                    mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_NA_CONDITION);
                } else {
                    mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_CONDITION);
                }
                mes.setDescription(mes.getDescription().replace("%COND%", tCExecution.getConditionOper()).replace("%MES%", conditionAnswerTc.getResultMessage().getDescription()));
                tCExecution.setResultMessage(mes);
            }
        }
    } catch (Exception ex) {
        /**
         * If an exception is found, set the execution to FA and print the
         * exception
         */
        tCExecution.setResultMessage(new MessageGeneral(MessageGeneralEnum.EXECUTION_FA));
        tCExecution.setControlMessage(tCExecution.getControlMessage() + " Exception: " + ex);
        LOG.error(logPrefix + "Exception found Executing Test " + tCExecution.getId() + " Exception :" + ex.toString());
    } finally {
        /**
         * We stop the server session here (selenium for ex.).
         */
        try {
            tCExecution = this.stopTestCase(tCExecution);
        } catch (Exception ex) {
            LOG.error(logPrefix + "Exception Stopping Test " + tCExecution.getId() + " Exception :" + ex.toString());
        }
        /**
         * Log Execution
         */
        LOG.info(tCExecution.toJson(false));
        /**
         * Clean memory
         */
        try {
            executionUUID.removeExecutionUUID(tCExecution.getExecutionUUID());
            LOG.debug("Clean ExecutionUUID");
        } catch (Exception ex) {
            LOG.error("Exception cleaning Memory: " + ex.toString());
        }
        /**
         * Log execution is finished
         */
        LOG.info("Execution Finished : UUID=" + tCExecution.getExecutionUUID() + "__ID=" + tCExecution.getId() + "__RC=" + tCExecution.getControlStatus() + "__" + "TestName=" + tCExecution.getEnvironment() + "." + tCExecution.getCountry() + "." + tCExecution.getBuild() + "." + tCExecution.getRevision() + "." + tCExecution.getTest() + "_" + tCExecution.getTestCase() + "_" + tCExecution.getTestCaseObj().getDescription().replace(".", ""));
        /**
         * Updating queue to done status only for execution from queue
         */
        if (tCExecution.getQueueID() != 0) {
            executionQueueService.updateToDone(tCExecution.getQueueID(), "", runID);
        }
        /**
         * Retry management, in case the result is not (OK or NE), we
         * execute the job again reducing the retry to 1.
         */
        if (tCExecution.getNumberOfRetries() > 0 && !tCExecution.getResultMessage().getCodeString().equals("OK") && !tCExecution.getResultMessage().getCodeString().equals("NE")) {
            TestCaseExecutionQueue newExeQueue = new TestCaseExecutionQueue();
            if (tCExecution.getQueueID() > 0) {
                // If QueueId exist, we try to get the original execution queue.
                try {
                    newExeQueue = executionQueueService.convert(executionQueueService.readByKey(tCExecution.getQueueID()));
                } catch (Exception e) {
                    // Unfortunatly the execution no longuer exist so we pick initial value.
                    newExeQueue = tCExecution.getTestCaseExecutionQueue();
                }
            } else {
                // Initial Execution does not come from the queue so we pick the value created at the beginning of the execution.
                newExeQueue = tCExecution.getTestCaseExecutionQueue();
            }
            // Forcing init value for that new queue execution : exeid=0, no debugflag and State = QUEUED
            int newRetry = tCExecution.getNumberOfRetries() - 1;
            newExeQueue.setId(0);
            newExeQueue.setDebugFlag("N");
            if (newRetry <= 0) {
                newExeQueue.setComment("Added from Retry. Last attempt to go.");
            } else {
                newExeQueue.setComment("Added from Retry. Still " + newRetry + " attempt(s) to go.");
            }
            newExeQueue.setState(TestCaseExecutionQueue.State.QUEUED);
            newExeQueue.setRetries(newRetry);
            // Insert execution to the Queue.
            executionQueueService.create(newExeQueue);
        }
        /**
         * After every execution finished, <br>
         * if the execution has a tag that has a campaign associated  <br>
         * and no more executions are in the queue, <br>
         * we trigger : <br>
         * 1/ The update of the EndExeQueue of the tag <br>
         * 2/ We notify the Distribution List with execution report status
         */
        try {
            if (!StringUtil.isNullOrEmpty(tCExecution.getTag())) {
                Tag currentTag = tagService.convert(tagService.readByKey(tCExecution.getTag()));
                if ((currentTag != null)) {
                    if (currentTag.getDateEndQueue().before(Timestamp.valueOf("1980-01-01 01:01:01.000000001"))) {
                        AnswerList answerListQueue = new AnswerList();
                        answerListQueue = executionQueueService.readQueueOpen(tCExecution.getTag());
                        if (answerListQueue.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && (answerListQueue.getDataList().isEmpty())) {
                            LOG.debug("No More executions in (queue) on tag : " + tCExecution.getTag() + " - " + answerListQueue.getDataList().size() + " " + answerListQueue.getMessageCodeString() + " - ");
                            tagService.updateDateEndQueue(tCExecution.getTag(), new Timestamp(new Date().getTime()));
                            if (!StringUtil.isNullOrEmpty(currentTag.getCampaign())) {
                                // We get the campaig here and potencially send the notification.
                                emailService.generateAndSendNotifyEndTagExecution(tCExecution.getTag(), currentTag.getCampaign());
                            }
                        } else {
                            LOG.debug("Still executions in queue on tag : " + tCExecution.getTag() + " - " + answerListQueue.getDataList().size() + " " + answerListQueue.getMessageCodeString());
                        }
                    } else {
                        LOG.debug("Tag is already flaged with recent timstamp. " + currentTag.getDateEndQueue());
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e);
        }
        // 
        // After every execution finished we try to trigger more from the queue;-).
        executionThreadPoolService.executeNextInQueueAsynchroneously(false);
    }
    return tCExecution;
}
Also used : TestCaseCountryProperties(org.cerberus.crud.entity.TestCaseCountryProperties) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) Timestamp(java.sql.Timestamp) CerberusEventException(org.cerberus.exception.CerberusEventException) CountryEnvLink(org.cerberus.crud.entity.CountryEnvLink) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) TestCaseExecutionSysVer(org.cerberus.crud.entity.TestCaseExecutionSysVer) IFactoryTestCaseExecutionSysVer(org.cerberus.crud.factory.IFactoryTestCaseExecutionSysVer) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) CerberusException(org.cerberus.exception.CerberusException) AnswerList(org.cerberus.util.answer.AnswerList) AnswerItem(org.cerberus.util.answer.AnswerItem) CerberusEventException(org.cerberus.exception.CerberusEventException) CerberusException(org.cerberus.exception.CerberusException) WebDriverException(org.openqa.selenium.WebDriverException) Date(java.util.Date) TestCaseExecutionEndPoint(org.cerberus.websocket.TestCaseExecutionEndPoint) BigDecimal(java.math.BigDecimal) IFactoryTestCaseStepExecution(org.cerberus.crud.factory.IFactoryTestCaseStepExecution) TestCaseStepExecution(org.cerberus.crud.entity.TestCaseStepExecution) TestCase(org.cerberus.crud.entity.TestCase) Capabilities(org.openqa.selenium.Capabilities) Tag(org.cerberus.crud.entity.Tag) CountryEnvParam(org.cerberus.crud.entity.CountryEnvParam)

Example 35 with TestCaseStep

use of org.cerberus.crud.entity.TestCaseStep in project cerberus-source by cerberustesting.

the class TestCaseStepService method readByTestTestCaseWithDependency.

@Override
public AnswerList readByTestTestCaseWithDependency(String test, String testcase) {
    AnswerList steps = this.readByTestTestCase(test, testcase);
    AnswerList response = null;
    List<TestCaseStep> tcseList = new ArrayList();
    for (Object step : steps.getDataList()) {
        TestCaseStep tces = (TestCaseStep) step;
        AnswerList actions = testCaseStepActionService.readByVarious1WithDependency(test, testcase, tces.getStep());
        tces.setTestCaseStepAction(actions.getDataList());
        tcseList.add(tces);
    }
    response = new AnswerList(tcseList, steps.getTotalRows(), new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) TestCaseStep(org.cerberus.crud.entity.TestCaseStep)

Aggregations

TestCaseStep (org.cerberus.crud.entity.TestCaseStep)41 ArrayList (java.util.ArrayList)20 IFactoryTestCaseStep (org.cerberus.crud.factory.IFactoryTestCaseStep)19 ITestCaseStepService (org.cerberus.crud.service.ITestCaseStepService)16 TestCase (org.cerberus.crud.entity.TestCase)15 TestCaseStepAction (org.cerberus.crud.entity.TestCaseStepAction)13 JSONObject (org.json.JSONObject)13 ApplicationContext (org.springframework.context.ApplicationContext)12 SQLException (java.sql.SQLException)11 TestCaseCountryProperties (org.cerberus.crud.entity.TestCaseCountryProperties)11 TestCaseStepActionControl (org.cerberus.crud.entity.TestCaseStepActionControl)11 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 ResultSet (java.sql.ResultSet)10 ITestCaseService (org.cerberus.crud.service.ITestCaseService)10 JSONArray (org.json.JSONArray)10 PolicyFactory (org.owasp.html.PolicyFactory)10 ITestCaseStepActionService (org.cerberus.crud.service.ITestCaseStepActionService)9 MessageEvent (org.cerberus.engine.entity.MessageEvent)9 TestCaseCountry (org.cerberus.crud.entity.TestCaseCountry)8