Search in sources :

Example 1 with ITestCaseService

use of org.cerberus.crud.service.ITestCaseService in project cerberus-source by cerberustesting.

the class RunTestCase method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createForPublicCalls("/RunTestCase", "CALL", "RunTestCase called : " + request.getRequestURL(), request);
    // Tool
    // Selenium IP
    String ss_ip = "";
    // Selenium Host (optional)
    String ss_ip_user = "";
    // Selenium Password (optional)
    String ss_ip_pass = "";
    // Selenium Port
    String ss_p = "";
    String browser = "";
    String robotDecli = "";
    String version = "";
    String platform = "";
    String robot = "";
    String active = "";
    String timeout = "";
    String userAgent = "";
    String screenSize = "";
    boolean synchroneous = true;
    int getPageSource = 0;
    int getSeleniumLog = 0;
    String manualExecution = "N";
    List<RobotCapability> capabilities = null;
    // Test
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Test"), "");
    String testCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("TestCase"), "");
    String country = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Country"), "");
    String environment = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Environment"), "");
    // Test Dev Environment
    boolean manualURL = ParameterParserUtil.parseBooleanParam(request.getParameter("manualURL"), false);
    String myHost = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("myhost"), "");
    String myContextRoot = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("mycontextroot"), "");
    String myLoginRelativeURL = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("myloginrelativeurl"), "");
    // TODO find another solution
    myLoginRelativeURL = myLoginRelativeURL.replace("&#61;", "=");
    String myEnvData = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("myenvdata"), "");
    // Execution
    String tag = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Tag"), "");
    String outputFormat = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("outputformat"), "compact");
    int screenshot = ParameterParserUtil.parseIntegerParam(request.getParameter("screenshot"), 1);
    int verbose = ParameterParserUtil.parseIntegerParam(request.getParameter("verbose"), 0);
    timeout = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("timeout"), "");
    synchroneous = ParameterParserUtil.parseBooleanParam(request.getParameter("synchroneous"), false);
    getPageSource = ParameterParserUtil.parseIntegerParam(request.getParameter("pageSource"), 1);
    getSeleniumLog = ParameterParserUtil.parseIntegerParam(request.getParameter("seleniumLog"), 1);
    manualExecution = ParameterParserUtil.parseStringParam(request.getParameter("manualExecution"), "N");
    int numberOfRetries = ParameterParserUtil.parseIntegerParam(request.getParameter("retries"), 0);
    screenSize = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("screenSize"), "");
    robot = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("robot"), "");
    ss_ip = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("ss_ip"), "");
    ss_p = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("ss_p"), "");
    browser = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Browser"), ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("browser"), ""));
    version = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("version"), "");
    platform = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("platform"), "");
    // hidden parameters.
    long idFromQueue = ParameterParserUtil.parseIntegerParam(request.getParameter("IdFromQueue"), 0);
    String executor = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("executor"), ParameterParserUtil.parseStringParamAndSanitize(request.getRemoteUser(), null));
    String helpMessage = "\nThis servlet is used to start the execution of a test case.\n" + "Parameter list :\n" + "- Test [mandatory] : Test to execute. [" + test + "]\n" + "- TestCase [mandatory] : Test Case reference to execute. [" + testCase + "]\n" + "- Country [mandatory] : Country where the test case will execute. [" + country + "]\n" + "- Environment : Environment where the test case will execute. This parameter is mandatory only if manualURL is not set to Y. [" + environment + "]\n" + "- robot : robot name on which the test will be executed. [" + robot + "]\n" + "- ss_ip : Host of the Robot where the test will be executed. (Can be overwriten if robot is defined) [" + ss_ip + "]\n" + "- ss_p : Port of the Robot. (Can be overwriten if robot is defined) [" + ss_p + "]\n" + "- browser : Browser to use for the execution. (Can be overwriten if robot is defined) [" + browser + "]\n" + "- version : Version to use for the execution. (Can be overwriten if robot is defined) [" + version + "]\n" + "- platform : Platform to use for the execution. (Can be overwriten if robot is defined) [" + platform + "]\n" + "- screenSize : Size of the screen to set for the execution. [" + screenSize + "]\n" + "- manualURL : Activate or not the Manual URL of the application to execute. If activated the 4 parameters after (myhost, mycontextroot, myloginrelativeurl, myenvdata) are necessary. [" + manualURL + "]\n" + "- myhost : Host of the application to test (only used when manualURL is feed). [" + myHost + "]\n" + "- mycontextroot : Context root of the application to test (only used when manualURL is feed). [" + myContextRoot + "]\n" + "- myloginrelativeurl : Relative login URL of the application (only used when manualURL is feed). [" + myLoginRelativeURL + "]\n" + "- myenvdata : Environment where to get the test data when a manualURL is defined. (only used when manualURL is feed) [" + myEnvData + "]\n" + "- Tag : Tag that will be stored on the execution. [" + tag + "]\n" + "- outputformat : Format of the output of the execution. [" + outputFormat + "]\n" + "- screenshot : Activate or not the screenshots. [" + screenshot + "]\n" + "- verbose : Verbose level of the execution. [" + verbose + "]\n" + "- timeout : Timeout used for the action. If empty, the default value will be the one configured in parameter table. [" + timeout + "]\n" + "- synchroneous : Synchroneous define if the servlet wait for the end of the execution to report its execution. [" + synchroneous + "\n" + "- pageSource : Record Page Source during the execution. [" + getPageSource + "]\n" + "- seleniumLog : Get the SeleniumLog at the end of the execution. [" + getSeleniumLog + "]\n" + "- manualExecution : Execute testcase in manual mode. [" + manualExecution + "]\n" + "- retries : Number of tries if the result is not OK. [" + numberOfRetries + "]\n";
    boolean error = false;
    String errorMessage = "";
    // test, testcase and country parameters are mandatory
    if (StringUtils.isBlank(test)) {
        errorMessage += "Error - Parameter test is mandatory. ";
        error = true;
    }
    if (StringUtils.isBlank(testCase)) {
        errorMessage += "Error - Parameter testCase is mandatory. ";
        error = true;
    }
    if (!StringUtils.isBlank(tag) && tag.length() > 255) {
        errorMessage += "Error - Parameter tag value is too big. Tag cannot be larger than 255 Characters. Currently has : " + tag.length();
        error = true;
    }
    if (StringUtils.isBlank(country)) {
        errorMessage += "Error - Parameter country is mandatory. ";
        error = true;
    }
    // environment is mandatory when manualURL is not activated.
    if (StringUtils.isBlank(environment) && !manualURL) {
        errorMessage += "Error - Parameter environment is mandatory (or use the manualURL parameter). ";
        error = true;
    }
    // We check that execution is not desactivated by cerberus_automaticexecution_enable parameter.
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    if (!(parameterService.getParameterBooleanByKey("cerberus_automaticexecution_enable", "", true))) {
        errorMessage += "Error - Execution disable by configuration (cerberus_automaticexecution_enable <> Y). ";
        error = true;
        LOG.info("Execution request ignored by cerberus_automaticexecution_enable parameter. " + test + " / " + testCase);
    }
    // If Robot is feeded, we check it exist. If it exist, we overwrite the associated parameters.
    if (!StringUtil.isNullOrEmpty(robot)) {
        IRobotService robotService = appContext.getBean(IRobotService.class);
        try {
            Robot robObj = robotService.readByKey(robot);
            // If Robot parameter is defined and we can find the robot, we overwrite the corresponding parameters.
            ss_ip = ParameterParserUtil.parseStringParam(robObj.getHost(), ss_ip);
            ss_ip_user = robObj.getHostUser();
            ss_ip_pass = robObj.getHostPassword();
            ss_p = ParameterParserUtil.parseStringParam(String.valueOf(robObj.getPort()), ss_p);
            browser = ParameterParserUtil.parseStringParam(robObj.getBrowser(), browser);
            robotDecli = ParameterParserUtil.parseStringParam(robObj.getRobotDecli(), "");
            if (StringUtil.isNullOrEmpty(robotDecli)) {
                robotDecli = robObj.getRobot();
            }
            version = ParameterParserUtil.parseStringParam(robObj.getVersion(), version);
            platform = ParameterParserUtil.parseStringParam(robObj.getPlatform(), platform);
            active = robObj.getActive();
            userAgent = robObj.getUserAgent();
            capabilities = robObj.getCapabilities();
            screenSize = robObj.getScreenSize();
        } catch (CerberusException ex) {
            errorMessage += "Error - Robot [" + robot + "] does not exist. ";
            error = true;
        }
    } else {
        robotDecli = browser;
    }
    // We cannot execute a testcase on a desactivated Robot.
    if (active.equals("N")) {
        errorMessage += "Error - Robot is not Active. ";
        error = true;
    }
    // verify the format of the ScreenSize. It must be 2 integer separated by a *. For example : 1024*768
    if (!"".equals(screenSize)) {
        if (!screenSize.contains("*")) {
            errorMessage += "Error - ScreenSize format is not Correct. It must be 2 Integer separated by a *. ";
            error = true;
        } else {
            try {
                String screenWidth = screenSize.split("\\*")[0];
                String screenLength = screenSize.split("\\*")[1];
                Integer.parseInt(screenWidth);
                Integer.parseInt(screenLength);
            } catch (Exception e) {
                errorMessage += "Error - ScreenSize format is not Correct. It must be 2 Integer separated by a *. ";
                error = true;
            }
        }
    }
    // check if the test case is to be executed in the specific parameters
    try {
        ITestCaseCountryService tccService = appContext.getBean(ITestCaseCountryService.class);
        TestCaseCountry tcc = tccService.findTestCaseCountryByKey(test, testCase, country);
        if (tcc == null) {
            error = true;
        }
    } catch (CerberusException ex) {
        error = true;
        errorMessage += "Error - Test Case is not selected for country. ";
    }
    // Create Tag when exist.
    if (!StringUtil.isNullOrEmpty(tag)) {
        // We create or update it.
        ITagService tagService = appContext.getBean(ITagService.class);
        tagService.createAuto(tag, "", executor);
    }
    if (!error) {
        // TODO:FN debug messages to be removed
        LOG.debug("STARTED: Test " + test + "-" + testCase);
        IRunTestCaseService runTestCaseService = appContext.getBean(IRunTestCaseService.class);
        IFactoryTestCase factoryTCase = appContext.getBean(IFactoryTestCase.class);
        IFactoryTestCaseExecution factoryTCExecution = appContext.getBean(IFactoryTestCaseExecution.class);
        IFactoryTestCaseExecutionQueue factoryTCExecutionQueue = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
        ITestCaseExecutionService tces = appContext.getBean(ITestCaseExecutionService.class);
        ITestCaseService tcs = appContext.getBean(ITestCaseService.class);
        TestCase tCase = factoryTCase.create(test, testCase);
        // Building Execution Object.
        TestCaseExecution tCExecution = factoryTCExecution.create(0, test, testCase, null, null, null, environment, country, browser, version, platform, "", 0, 0, "", "", "", null, ss_ip, null, ss_p, tag, verbose, screenshot, getPageSource, getSeleniumLog, synchroneous, timeout, outputFormat, null, Infos.getInstance().getProjectNameAndVersion(), tCase, null, null, manualURL, myHost, myContextRoot, myLoginRelativeURL, myEnvData, ss_ip, ss_p, null, new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTSTARTED), executor, numberOfRetries, screenSize, capabilities, "", "", "", "", "", manualExecution, userAgent, 0, "", robotDecli);
        tCExecution.setSeleniumIPUser(ss_ip_user);
        tCExecution.setSeleniumIPPassword(ss_ip_pass);
        /**
         * Set IdFromQueue
         */
        try {
            tCExecution.setQueueID(idFromQueue);
            TestCaseExecutionQueue queueExecution = factoryTCExecutionQueue.create(idFromQueue, test, testCase, country, environment, robot, ss_ip, ss_p, browser, version, platform, screenSize, 0, myHost, myContextRoot, myLoginRelativeURL, myEnvData, tag, screenshot, verbose, timeout, getPageSource, getSeleniumLog, 0, numberOfRetries, manualExecution, executor, null, null, null);
            tCExecution.setTestCaseExecutionQueue(queueExecution);
        } catch (FactoryCreationException ex) {
            LOG.error(ex);
        }
        /**
         * Set UUID
         */
        ExecutionUUID executionUUIDObject = appContext.getBean(ExecutionUUID.class);
        UUID executionUUID = UUID.randomUUID();
        executionUUIDObject.setExecutionUUID(executionUUID.toString(), tCExecution);
        tCExecution.setExecutionUUID(executionUUID.toString());
        LOG.info("Execution Requested : UUID=" + executionUUID);
        /**
         * Execution of the testcase.
         */
        LOG.debug("Start execution " + tCExecution.getId());
        tCExecution = runTestCaseService.runTestCase(tCExecution);
        /**
         * Clean memory in case testcase has not been launched(Remove all
         * object put in memory)
         */
        try {
            if (tCExecution.getId() == 0) {
                executionUUIDObject.removeExecutionUUID(tCExecution.getExecutionUUID());
                LOG.debug("Clean ExecutionUUID");
            }
        } catch (Exception ex) {
            LOG.error("Exception cleaning Memory: ", ex);
        }
        /**
         * Execution is finished we report the result.
         */
        long runID = tCExecution.getId();
        if (outputFormat.equalsIgnoreCase("gui")) {
            // HTML GUI output. either the detailed execution page or an error page when the execution is not created.
            if (runID > 0) {
                // Execution has been created.
                response.sendRedirect("TestCaseExecution.jsp?executionId=" + runID);
            } else {
                // Execution was not even created.
                response.setContentType("text/html");
                out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>Test Execution Result</title></head>");
                out.println("<body>");
                out.println("<table>");
                out.println("<tr><td>RunID</td><td><span id='RunID'>" + runID + "</span></td></tr>");
                out.println("<tr><td>IdFromQueue</td><td><b><span id='IdFromQueue'>" + tCExecution.getQueueID() + "</span></b></td></tr>");
                out.println("<tr><td>Test</td><td><span id='Test'>" + test + "</span></td></tr>");
                out.println("<tr><td>TestCase</td><td><span id='TestCase'>" + testCase + "</span></td></tr>");
                out.println("<tr><td>Country</td><td><span id='Country'>" + country + "</span></td></tr>");
                out.println("<tr><td>Environment</td><td><span id='Environment'>" + environment + "</span></td></tr>");
                out.println("<tr><td>TimestampStart</td><td><span id='TimestampStart'>" + new Timestamp(tCExecution.getStart()) + "</span></td></tr>");
                out.println("<tr><td>TimestampEnd</td><td><span id='TimestampEnd'>" + new Timestamp(tCExecution.getEnd()) + "</span></td></tr>");
                out.println("<tr><td>OutputFormat</td><td><span id='OutputFormat'>" + outputFormat + "</span></td></tr>");
                out.println("<tr><td>Verbose</td><td><span id='Verbose'>" + verbose + "</span></td></tr>");
                out.println("<tr><td>Screenshot</td><td><span id='Screenshot'>" + screenshot + "</span></td></tr>");
                out.println("<tr><td>PageSource</td><td><span id='PageSource'>" + getPageSource + "</span></td></tr>");
                out.println("<tr><td>SeleniumLog</td><td><span id='SeleniumLog'>" + getSeleniumLog + "</span></td></tr>");
                out.println("<tr><td>Robot</td><td><span id='Robot'>" + robot + "</span></td></tr>");
                out.println("<tr><td>Selenium Server IP</td><td><span id='SeleniumIP'>" + ss_ip + "</span></td></tr>");
                out.println("<tr><td>Selenium Server Port</td><td><span id='SeleniumPort'>" + ss_p + "</span></td></tr>");
                out.println("<tr><td>Timeout</td><td><span id='Timeout'>" + timeout + "</span></td></tr>");
                out.println("<tr><td>Synchroneous</td><td><span id='Synchroneous'>" + synchroneous + "</span></td></tr>");
                out.println("<tr><td>Browser</td><td><span id='Browser'>" + browser + "</span></td></tr>");
                out.println("<tr><td>Version</td><td><span id='Version'>" + version + "</span></td></tr>");
                out.println("<tr><td>Platform</td><td><span id='Platform'>" + platform + "</span></td></tr>");
                out.println("<tr><td>Screen Size</td><td><span id='screenSize'>" + screenSize + "</span></td></tr>");
                out.println("<tr><td>Number of Retry</td><td><span id='nbretry'>" + numberOfRetries + "</span></td></tr>");
                out.println("<tr><td>ManualURL</td><td><span id='ManualURL'>" + tCExecution.isManualURL() + "</span></td></tr>");
                out.println("<tr><td>MyHost</td><td><span id='MyHost'>" + tCExecution.getMyHost() + "</span></td></tr>");
                out.println("<tr><td>MyContextRoot</td><td><span id='MyContextRoot'>" + tCExecution.getMyContextRoot() + "</span></td></tr>");
                out.println("<tr><td>MyLoginRelativeURL</td><td><span id='MyLoginRelativeURL'>" + tCExecution.getMyLoginRelativeURL() + "</span></td></tr>");
                out.println("<tr><td>myEnvironmentData</td><td><span id='myEnvironmentData'>" + tCExecution.getEnvironmentData() + "</span></td></tr>");
                out.println("<tr><td>ReturnCode</td><td><b><span id='ReturnCodeDescription'>" + tCExecution.getResultMessage().getCode() + "</span></b></td></tr>");
                out.println("<tr><td>ReturnCodeDescription</td><td><b><span id='ReturnCodeDescription'>" + tCExecution.getResultMessage().getDescription() + "</span></b></td></tr>");
                out.println("<tr><td>ControlStatus</td><td><b><span id='ReturnCodeMessage'>" + tCExecution.getResultMessage().getCodeString() + "</span></b></td></tr>");
                out.println("<tr><td></td><td></td></tr>");
                out.println("</table><br><br>");
                out.println("<table border>");
                out.println("<tr>" + "<td><input id=\"ButtonRetry\" type=\"button\" value=\"Retry\" onClick=\"window.location.reload()\"></td>" + "<td><input id=\"ButtonBack\" type=\"button\" value=\"Go Back\" onClick=\"window.history.back()\"></td>" + "<td><input id=\"ButtonOpenTC\" type=\"button\" value=\"Open Test Case\" onClick=\"window.open('TestCaseScript.jsp?test=" + test + "&testcase=" + testCase + "')\"></td>" + "</tr>");
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
            }
        } else if (outputFormat.equalsIgnoreCase("redirectToReport")) {
            // Redirect to the reporting page by tag.
            response.sendRedirect("./ReportingExecutionByTag.jsp?Tag=" + StringUtil.encodeAsJavaScriptURIComponent(tag));
        } else if (outputFormat.equalsIgnoreCase("verbose-txt")) {
            // Text verbose output.
            response.setContentType("text/plain");
            String separator = " = ";
            out.println("RunID" + separator + runID);
            out.println("QueueID" + separator + idFromQueue);
            out.println("Test" + separator + test);
            out.println("TestCase" + separator + testCase);
            out.println("Country" + separator + country);
            out.println("Environment" + separator + environment);
            out.println("Time Start" + separator + new Timestamp(tCExecution.getStart()));
            out.println("Time End" + separator + new Timestamp(tCExecution.getEnd()));
            out.println("OutputFormat" + separator + outputFormat);
            out.println("Verbose" + separator + verbose);
            out.println("Screenshot" + separator + screenshot);
            out.println("PageSource" + separator + getPageSource);
            out.println("SeleniumLog" + separator + getSeleniumLog);
            out.println("Robot" + separator + robot);
            out.println("Selenium Server IP" + separator + ss_ip);
            out.println("Selenium Server Port" + separator + ss_p);
            out.println("Timeout" + separator + timeout);
            out.println("Synchroneous" + separator + synchroneous);
            out.println("Browser" + separator + browser);
            out.println("Version" + separator + version);
            out.println("Platform" + separator + platform);
            out.println("ScreenSize" + separator + screenSize);
            out.println("Nb Of Retry" + separator + numberOfRetries);
            out.println("ManualURL" + separator + tCExecution.isManualURL());
            out.println("MyHost" + separator + tCExecution.getMyHost());
            out.println("MyContextRoot" + separator + tCExecution.getMyContextRoot());
            out.println("MyLoginRelativeURL" + separator + tCExecution.getMyLoginRelativeURL());
            out.println("myEnvironmentData" + separator + tCExecution.getEnvironmentData());
            out.println("ReturnCode" + separator + tCExecution.getResultMessage().getCode());
            out.println("ReturnCodeDescription" + separator + tCExecution.getResultMessage().getDescription());
            out.println("ControlStatus" + separator + tCExecution.getResultMessage().getCodeString());
        } else if (outputFormat.equalsIgnoreCase("verbose-json")) {
            // JSON verbose output.
            response.setContentType("application/json");
            TestCaseExecution t = (TestCaseExecution) tces.readByKeyWithDependency(tCExecution.getId()).getItem();
            out.print(tCExecution.toJson(true).toString());
        } else {
            // Default behaviour when not outputformat is defined : compact mode.
            response.setContentType("text/plain");
            DateFormat df = new SimpleDateFormat(DateUtil.DATE_FORMAT_DISPLAY);
            out.println(df.format(tCExecution.getStart()) + " - " + runID + " [" + test + "|" + testCase + "|" + country + "|" + environment + "] : '" + tCExecution.getResultMessage().getCodeString() + "' - " + tCExecution.getResultMessage().getCode() + " " + tCExecution.getResultMessage().getDescription());
        }
    } else {
        // Error occured in the servlet.
        if (outputFormat.equalsIgnoreCase("verbose-txt")) {
            // Text verbose output.
            response.setContentType("text/plain");
            String separator = " = ";
            out.println("RunID" + separator + 0);
            out.println("QueueID" + separator + idFromQueue);
            out.println("Test" + separator + test);
            out.println("TestCase" + separator + testCase);
            out.println("Country" + separator + country);
            out.println("Environment" + separator + environment);
            out.println("OutputFormat" + separator + outputFormat);
            out.println("Verbose" + separator + verbose);
            out.println("Screenshot" + separator + screenshot);
            out.println("PageSource" + separator + getPageSource);
            out.println("SeleniumLog" + separator + getSeleniumLog);
            out.println("Robot" + separator + robot);
            out.println("Selenium Server IP" + separator + ss_ip);
            out.println("Selenium Server Port" + separator + ss_p);
            out.println("Timeout" + separator + timeout);
            out.println("Synchroneous" + separator + synchroneous);
            out.println("Browser" + separator + browser);
            out.println("Version" + separator + version);
            out.println("Platform" + separator + platform);
            out.println("ScreenSize" + separator + screenSize);
            out.println("Nb Of Retry" + separator + numberOfRetries);
            out.println("ManualURL" + separator + manualURL);
            out.println("MyHost" + separator + myHost);
            out.println("MyContextRoot" + separator + myContextRoot);
            out.println("MyLoginRelativeURL" + separator + myLoginRelativeURL);
            out.println("myEnvironmentData" + separator + myEnvData);
            out.println("ReturnCode" + separator + MessageGeneralEnum.EXECUTION_FA_SERVLETVALIDATONS.getCode());
            out.println("ReturnCodeDescription" + separator + MessageGeneralEnum.EXECUTION_FA_SERVLETVALIDATONS.getDescription() + " " + errorMessage);
            out.println("ControlStatus" + separator + MessageGeneralEnum.EXECUTION_FA_SERVLETVALIDATONS.getCodeString());
        } else {
            // In case of errors, we display the help message.
            response.setContentType("text/plain");
            DateFormat df = new SimpleDateFormat(DateUtil.DATE_FORMAT_DISPLAY);
            String errorMessageFinal = df.format(new Date()) + " - " + 0 + " [" + test + "|" + testCase + "|" + country + "|" + environment + "] : '" + MessageGeneralEnum.EXECUTION_FA_SERVLETVALIDATONS.getCodeString() + "' - " + MessageGeneralEnum.EXECUTION_FA_SERVLETVALIDATONS.getCode() + " " + MessageGeneralEnum.EXECUTION_FA_SERVLETVALIDATONS.getDescription() + " " + errorMessage;
            out.println(errorMessageFinal);
        }
    }
}
Also used : IParameterService(org.cerberus.crud.service.IParameterService) IFactoryTestCaseExecution(org.cerberus.crud.factory.IFactoryTestCaseExecution) ITestCaseExecutionService(org.cerberus.crud.service.ITestCaseExecutionService) Timestamp(java.sql.Timestamp) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) FactoryCreationException(org.cerberus.exception.FactoryCreationException) ApplicationContext(org.springframework.context.ApplicationContext) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) RobotCapability(org.cerberus.crud.entity.RobotCapability) UUID(java.util.UUID) ExecutionUUID(org.cerberus.engine.entity.ExecutionUUID) PrintWriter(java.io.PrintWriter) CerberusException(org.cerberus.exception.CerberusException) IFactoryTestCaseExecution(org.cerberus.crud.factory.IFactoryTestCaseExecution) TestCaseExecution(org.cerberus.crud.entity.TestCaseExecution) ExecutionUUID(org.cerberus.engine.entity.ExecutionUUID) IRunTestCaseService(org.cerberus.engine.execution.IRunTestCaseService) ServletException(javax.servlet.ServletException) FactoryCreationException(org.cerberus.exception.FactoryCreationException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) Date(java.util.Date) IRobotService(org.cerberus.crud.service.IRobotService) TestCase(org.cerberus.crud.entity.TestCase) IFactoryTestCase(org.cerberus.crud.factory.IFactoryTestCase) ITagService(org.cerberus.crud.service.ITagService) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) IFactoryTestCase(org.cerberus.crud.factory.IFactoryTestCase) Robot(org.cerberus.crud.entity.Robot) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with ITestCaseService

use of org.cerberus.crud.service.ITestCaseService in project cerberus-source by cerberustesting.

the class UpdateTestCaseWithDependencies method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.cerberus.exception.CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    String initialTest = request.getParameter("informationInitialTest");
    String initialTestCase = request.getParameter("informationInitialTestCase");
    String test = request.getParameter("informationTest");
    String testCase = request.getParameter("informationTestCase");
    TestCase tc = getTestCaseFromParameter(request, appContext, test, testCase);
    boolean duplicate = false;
    ITestService tService = appContext.getBean(ITestService.class);
    ITestCaseService tcService = appContext.getBean(ITestCaseService.class);
    ITestCaseCountryService tccService = appContext.getBean(ITestCaseCountryService.class);
    ITestCaseCountryPropertiesService tccpService = appContext.getBean(ITestCaseCountryPropertiesService.class);
    ITestCaseStepService tcsService = appContext.getBean(ITestCaseStepService.class);
    ITestCaseStepActionService tcsaService = appContext.getBean(ITestCaseStepActionService.class);
    ITestCaseStepActionControlService tcsacService = appContext.getBean(ITestCaseStepActionControlService.class);
    IInvariantService invariantService = appContext.getBean(IInvariantService.class);
    IUserService userService = appContext.getBean(IUserService.class);
    IUserGroupService userGroupService = appContext.getBean(IUserGroupService.class);
    /**
     * Get User and Groups of this user
     */
    User user = userService.findUserByKey(request.getUserPrincipal().getName());
    // List<UserGroup> userGroupList = groupService.findGroupByUser(user);
    List<UserGroup> userGroupList = userGroupService.convert(userGroupService.readByUser(user.getLogin()));
    List<String> groupList = new ArrayList();
    for (UserGroup group : userGroupList) {
        groupList.add(group.getGroup());
    }
    /**
     * Verify the Test is the same than initialTest If it is the same > Do
     * nothing If it is not the same > Verify if test already exists If not
     * exist > create it If exist > do nothing
     */
    if (!tc.getTest().equals(initialTest)) {
        if (tService.findTestByKey(tc.getTest()) == null) {
            if (groupList.contains("TestAdmin")) {
                Test newTest = tService.findTestByKey(initialTest);
                newTest.setTest(tc.getTest());
                tService.convert(tService.create(newTest));
            } else {
                response.sendError(403, MessageGeneralEnum.GUI_TEST_CREATION_NOT_HAVE_RIGHT.getDescription());
                return;
            }
        }
    }
    if (!tc.getTest().equals(initialTest) || !tc.getTestCase().equals(initialTestCase)) {
        duplicate = true;
    }
    /**
     * If the testcase is a duplication, set the creator as the one which
     * duplicate the testcase and the status in the initial one.
     */
    if (duplicate) {
        tc.setUsrCreated(user.getLogin());
        // TODO: handle if the response does not turn ok
        AnswerList answer = invariantService.readByIdname("TCSTATUS");
        tc.setStatus(((List<Invariant>) answer.getDataList()).get(0).getValue());
    }
    /**
     * If not duplicate and test in Working status and user with no admin
     * right, raise an error
     */
    if (!duplicate && "WORKING".equals(tc.getStatus()) && !groupList.contains("TestAdmin")) {
        response.sendError(403, MessageGeneralEnum.GUI_TESTCASE_NON_ADMIN_SAVE_WORKING_TESTCASE.getDescription());
        return;
    }
    /**
     * Verify testcase is the same than initialTestCase If it is the same >
     * update If it is not the same, > verify if testcase already exist If
     * it already exist > Send Error If it do not already exists > Create it
     */
    if (!duplicate) {
        tcService.updateTestCase(tc);
    } else if (tcService.findTestCaseByKey(tc.getTest(), tc.getTestCase()) != null) {
        response.sendError(403, MessageGeneralEnum.GUI_TESTCASE_DUPLICATION_ALREADY_EXISTS.getDescription());
        return;
    } else {
        tcService.createTestCase(tc);
    }
    /**
     * For the list of testcase country verify it exists. If it does not
     * exists > create it If it exist, verify if it's the
     */
    List<TestCaseCountry> tccFromPage = getTestCaseCountryFromParameter(request, appContext, test, testCase);
    List<TestCaseCountry> tccFromDtb = tccService.findTestCaseCountryByTestTestCase(initialTest, initialTestCase);
    /**
     * Iterate on (TestCaseCountry From Page - TestCaseCountry From
     * Database) If TestCaseCountry in Database has same key : Update and
     * remove from the list. If TestCaseCountry in database does ot exist :
     * Insert it.
     */
    List<TestCaseCountry> tccToUpdateOrInsert = new ArrayList(tccFromPage);
    tccToUpdateOrInsert.removeAll(tccFromDtb);
    List<TestCaseCountry> tccToUpdateOrInsertToIterate = new ArrayList(tccToUpdateOrInsert);
    for (TestCaseCountry tccDifference : tccToUpdateOrInsertToIterate) {
        for (TestCaseCountry tccInDatabase : tccFromDtb) {
            if (tccDifference.hasSameKey(tccInDatabase)) {
                tccToUpdateOrInsert.remove(tccDifference);
            }
        }
    }
    tccService.insertListTestCaseCountry(tccToUpdateOrInsert);
    /**
     * Iterate on (TestCaseCountry From Database - TestCaseCountry From
     * Page). If TestCaseCountry in Page has same key : remove from the
     * list. Then delete the list of TestCaseCountry
     */
    if (!duplicate) {
        List<TestCaseCountry> tccToDelete = new ArrayList(tccFromDtb);
        tccToDelete.removeAll(tccFromPage);
        List<TestCaseCountry> tccToDeleteToIterate = new ArrayList(tccToDelete);
        for (TestCaseCountry tccDifference : tccToDeleteToIterate) {
            for (TestCaseCountry tccInPage : tccFromPage) {
                if (tccDifference.hasSameKey(tccInPage)) {
                    tccToDelete.remove(tccDifference);
                }
            }
        }
        tccService.deleteListTestCaseCountry(tccToDelete);
    }
    /**
     * For the list of testcase country verify it exists. If it does not
     * exists > create it If it exist, verify if it's the
     */
    List<TestCaseCountryProperties> tccpFromPage = getTestCaseCountryPropertiesFromParameter(request, appContext, test, testCase);
    List<TestCaseCountryProperties> tccpFromDtb = tccpService.findListOfPropertyPerTestTestCase(initialTest, initialTestCase);
    /**
     * Iterate on (TestCaseCountryProperties From Page -
     * TestCaseCountryProperties From Database) If TestCaseCountryProperties
     * in Database has same key : Update and remove from the list. If
     * TestCaseCountryProperties in database does ot exist : Insert it.
     */
    List<TestCaseCountryProperties> tccpToUpdateOrInsert = new ArrayList(tccpFromPage);
    tccpToUpdateOrInsert.removeAll(tccpFromDtb);
    List<TestCaseCountryProperties> tccpToUpdateOrInsertToIterate = new ArrayList(tccpToUpdateOrInsert);
    for (TestCaseCountryProperties tccpDifference : tccpToUpdateOrInsertToIterate) {
        for (TestCaseCountryProperties tccpInDatabase : tccpFromDtb) {
            if (tccpDifference.hasSameKey(tccpInDatabase)) {
                tccpService.updateTestCaseCountryProperties(tccpDifference);
                tccpToUpdateOrInsert.remove(tccpDifference);
            }
        }
    }
    tccpService.insertListTestCaseCountryProperties(tccpToUpdateOrInsert);
    /**
     * Iterate on (TestCaseCountryProperties From Database -
     * TestCaseCountryProperties From Page). If TestCaseCountryProperties in
     * Page has same key : remove from the list. Then delete the list of
     * TestCaseCountryProperties
     */
    if (!duplicate) {
        List<TestCaseCountryProperties> tccpToDelete = new ArrayList(tccpFromDtb);
        tccpToDelete.removeAll(tccpFromPage);
        List<TestCaseCountryProperties> tccpToDeleteToIterate = new ArrayList(tccpToDelete);
        for (TestCaseCountryProperties tccpDifference : tccpToDeleteToIterate) {
            for (TestCaseCountryProperties tccpInPage : tccpFromPage) {
                if (tccpDifference.hasSameKey(tccpInPage)) {
                    tccpToDelete.remove(tccpDifference);
                }
            }
        }
        tccpService.deleteListTestCaseCountryProperties(tccpToDelete);
    }
    /*
         * Get steps, actions and controls from page by:
         * - generating a new step, action or control number,
         * - setting the correct related step and action for action or control
         */
    List<TestCaseStep> tcsFromPage = getTestCaseStepFromParameter(request, appContext, test, testCase, duplicate);
    List<TestCaseStepAction> tcsaFromPage = new ArrayList();
    List<TestCaseStepActionControl> tcsacFromPage = new ArrayList();
    int nextStepNumber = getMaxStepNumber(tcsFromPage);
    for (TestCaseStep tcs : tcsFromPage) {
        if (tcs.getStep() == -1) {
            tcs.setStep(++nextStepNumber);
        }
        if (tcs.getTestCaseStepAction() != null) {
            int nextSequenceNumber = getMaxSequenceNumber(tcs.getTestCaseStepAction());
            for (TestCaseStepAction tcsa : tcs.getTestCaseStepAction()) {
                if (tcsa.getSequence() == -1) {
                    tcsa.setSequence(++nextSequenceNumber);
                }
                tcsa.setStep(tcs.getStep());
                if (tcsa.getTestCaseStepActionControl() != null) {
                    int nextControlNumber = getMaxControlNumber(tcsa.getTestCaseStepActionControl());
                    for (TestCaseStepActionControl tscac : tcsa.getTestCaseStepActionControl()) {
                        if (tscac.getControlSequence() == -1) {
                            tscac.setControlSequence(++nextControlNumber);
                        }
                        tscac.setStep(tcs.getStep());
                        tscac.setSequence(tcsa.getSequence());
                    }
                    tcsacFromPage.addAll(tcsa.getTestCaseStepActionControl());
                }
            }
            tcsaFromPage.addAll(tcs.getTestCaseStepAction());
        }
    }
    /*
         * Create, update or delete step, action and control according to the needs
         */
    List<TestCaseStep> tcsFromDtb = new ArrayList(tcsService.getListOfSteps(initialTest, initialTestCase));
    tcsService.compareListAndUpdateInsertDeleteElements(tcsFromPage, tcsFromDtb, duplicate);
    List<TestCaseStepAction> tcsaFromDtb = new ArrayList(tcsaService.findTestCaseStepActionbyTestTestCase(initialTest, initialTestCase));
    tcsaService.compareListAndUpdateInsertDeleteElements(tcsaFromPage, tcsaFromDtb, duplicate);
    List<TestCaseStepActionControl> tcsacFromDtb = new ArrayList(tcsacService.findControlByTestTestCase(initialTest, initialTestCase));
    tcsacService.compareListAndUpdateInsertDeleteElements(tcsacFromPage, tcsacFromDtb, duplicate);
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    logEventService.createForPrivateCalls("/UpdateTestCase", "UPDATE", "Update testcase : ['" + tc.getTest() + "'|'" + tc.getTestCase() + "']", request);
    String encodedTest = URLEncoder.encode(tc.getTest(), "UTF-8");
    String encodedTestCase = URLEncoder.encode(tc.getTestCase(), "UTF-8");
    response.sendRedirect(response.encodeRedirectURL("TestCase.jsp?Load=Load&Test=" + encodedTest + "&TestCase=" + encodedTestCase));
}
Also used : ITestCaseStepActionService(org.cerberus.crud.service.ITestCaseStepActionService) IFactoryTestCaseStepAction(org.cerberus.crud.factory.IFactoryTestCaseStepAction) TestCaseStepAction(org.cerberus.crud.entity.TestCaseStepAction) User(org.cerberus.crud.entity.User) TestCaseCountryProperties(org.cerberus.crud.entity.TestCaseCountryProperties) IFactoryTestCaseCountryProperties(org.cerberus.crud.factory.IFactoryTestCaseCountryProperties) ArrayList(java.util.ArrayList) IFactoryTestCaseStep(org.cerberus.crud.factory.IFactoryTestCaseStep) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) IUserGroupService(org.cerberus.crud.service.IUserGroupService) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) UserGroup(org.cerberus.crud.entity.UserGroup) ApplicationContext(org.springframework.context.ApplicationContext) ITestService(org.cerberus.crud.service.ITestService) Test(org.cerberus.crud.entity.Test) ITestCaseCountryPropertiesService(org.cerberus.crud.service.ITestCaseCountryPropertiesService) ITestCaseService(org.cerberus.crud.service.ITestCaseService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) ILogEventService(org.cerberus.crud.service.ILogEventService) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) TestCaseStepActionControl(org.cerberus.crud.entity.TestCaseStepActionControl) IFactoryTestCaseStepActionControl(org.cerberus.crud.factory.IFactoryTestCaseStepActionControl) AnswerList(org.cerberus.util.answer.AnswerList) ITestCaseStepService(org.cerberus.crud.service.ITestCaseStepService) IInvariantService(org.cerberus.crud.service.IInvariantService) ITestCaseStepActionControlService(org.cerberus.crud.service.ITestCaseStepActionControlService) TestCase(org.cerberus.crud.entity.TestCase) IFactoryTestCase(org.cerberus.crud.factory.IFactoryTestCase) IUserService(org.cerberus.crud.service.IUserService)

Example 3 with ITestCaseService

use of org.cerberus.crud.service.ITestCaseService in project cerberus-source by cerberustesting.

the class CalculatePropertyForTestCase method doGet.

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS);
    String type = policy.sanitize(httpServletRequest.getParameter("type"));
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    String result = null;
    String description = null;
    String system = "";
    String property = httpServletRequest.getParameter("property");
    String testName = policy.sanitize(httpServletRequest.getParameter("test"));
    String testCaseName = policy.sanitize(httpServletRequest.getParameter("testCase"));
    String country = policy.sanitize(httpServletRequest.getParameter("country"));
    String environment = policy.sanitize(httpServletRequest.getParameter("environment"));
    try {
        if (type.equals("executeSoapFromLib")) {
            IAppServiceService appServiceService = appContext.getBean(AppServiceService.class);
            ISoapService soapService = appContext.getBean(ISoapService.class);
            IXmlUnitService xmlUnitService = appContext.getBean(IXmlUnitService.class);
            AppService appService = appServiceService.findAppServiceByKey(property);
            if (appService != null) {
                ExecutionUUID executionUUIDObject = appContext.getBean(ExecutionUUID.class);
                UUID executionUUID = UUID.randomUUID();
                executionUUIDObject.setExecutionUUID(executionUUID.toString(), null);
                soapService.callSOAP(appService.getServiceRequest(), appService.getServicePath(), appService.getOperation(), appService.getAttachementURL(), null, null, 60000, system);
                result = xmlUnitService.getFromXml(executionUUID.toString(), appService.getAttachementURL());
                description = appService.getDescription();
                executionUUIDObject.removeExecutionUUID(executionUUID.toString());
                LOG.debug("Clean ExecutionUUID");
            }
        } else {
            try {
                ITestCaseService testCaseService = appContext.getBean(TestCaseService.class);
                IApplicationService applicationService = appContext.getBean(ApplicationService.class);
                TestCase testCase = testCaseService.findTestCaseByKey(testName, testCaseName);
                if (testCase != null) {
                    system = applicationService.convert(applicationService.readByKey(testCase.getApplication())).getSystem();
                } else {
                    throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
                }
            } catch (CerberusException ex) {
                LOG.warn(ex);
            }
            if (system != null) {
                String database = policy.sanitize(httpServletRequest.getParameter("database"));
                ICountryEnvironmentDatabaseService countryEnvironmentDatabaseService = appContext.getBean(CountryEnvironmentDatabaseService.class);
                CountryEnvironmentDatabase countryEnvironmentDatabase;
                countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(countryEnvironmentDatabaseService.readByKey(system, country, environment, database));
                String connectionName = countryEnvironmentDatabase.getConnectionPoolName();
                if (type.equals("executeSqlFromLib")) {
                    ISqlLibraryService sqlLibraryService = appContext.getBean(SqlLibraryService.class);
                    SqlLibrary sl = sqlLibraryService.findSqlLibraryByKey(policy.sanitize(property));
                    property = sl.getScript();
                    if (!(StringUtil.isNullOrEmpty(connectionName)) && !(StringUtil.isNullOrEmpty(policy.sanitize(property)))) {
                        ISQLService sqlService = appContext.getBean(ISQLService.class);
                        IParameterService parameterService = appContext.getBean(IParameterService.class);
                        Integer sqlTimeout = parameterService.getParameterIntegerByKey("cerberus_propertyexternalsql_timeout", system, 60);
                        result = sqlService.queryDatabase(connectionName, policy.sanitize(property), 1, sqlTimeout).get(0);
                        description = sl.getDescription();
                    }
                }
            }
        }
    } catch (CerberusException ex) {
        LOG.warn(ex);
        result = ex.getMessageError().getDescription();
        description = ex.getMessageError().getDescription();
    } catch (CerberusEventException ex) {
        LOG.warn(ex);
        result = ex.getMessageError().getDescription();
        description = ex.getMessageError().getDescription();
    }
    if (result != null) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resultList", result);
            jsonObject.put("description", description);
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().print(jsonObject.toString());
        } catch (JSONException exception) {
            LOG.warn(exception.toString());
        }
    }
}
Also used : AppService(org.cerberus.crud.entity.AppService) CerberusException(org.cerberus.exception.CerberusException) PolicyFactory(org.owasp.html.PolicyFactory) ExecutionUUID(org.cerberus.engine.entity.ExecutionUUID) SqlLibrary(org.cerberus.crud.entity.SqlLibrary) JSONException(org.json.JSONException) IAppServiceService(org.cerberus.crud.service.IAppServiceService) IParameterService(org.cerberus.crud.service.IParameterService) CerberusEventException(org.cerberus.exception.CerberusEventException) ApplicationContext(org.springframework.context.ApplicationContext) ISQLService(org.cerberus.service.sql.ISQLService) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) JSONObject(org.json.JSONObject) ISoapService(org.cerberus.service.soap.ISoapService) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ISqlLibraryService(org.cerberus.crud.service.ISqlLibraryService) ICountryEnvironmentDatabaseService(org.cerberus.crud.service.ICountryEnvironmentDatabaseService) UUID(java.util.UUID) ExecutionUUID(org.cerberus.engine.entity.ExecutionUUID) IXmlUnitService(org.cerberus.service.xmlunit.IXmlUnitService) IApplicationService(org.cerberus.crud.service.IApplicationService) CountryEnvironmentDatabase(org.cerberus.crud.entity.CountryEnvironmentDatabase)

Example 4 with ITestCaseService

use of org.cerberus.crud.service.ITestCaseService in project cerberus-source by cerberustesting.

the class GetTestCase method doGet.

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    try {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseService testService = appContext.getBean(ITestCaseService.class);
        // TODO pass DAO to Service
        ITestCaseCountryPropertiesDAO testCaseDAO = appContext.getBean(TestCaseCountryPropertiesDAO.class);
        ILoadTestCaseService loadTestCaseService = appContext.getBean(ILoadTestCaseService.class);
        PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
        String test = policy.sanitize(httpServletRequest.getParameter("test"));
        String testcase = policy.sanitize(httpServletRequest.getParameter("testcase"));
        TestCase tcInfo = testService.findTestCaseByKeyWithDependency(test, testcase);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("origin", tcInfo.getOrigine());
            jsonObject.put("refOrigin", tcInfo.getRefOrigine());
            jsonObject.put("creator", tcInfo.getUsrCreated());
            jsonObject.put("implementer", tcInfo.getImplementer());
            jsonObject.put("lastModifier", tcInfo.getUsrModif());
            jsonObject.put("project", tcInfo.getProject());
            jsonObject.put("ticket", tcInfo.getTicket());
            jsonObject.put("application", tcInfo.getApplication());
            jsonObject.put("runQA", tcInfo.getActiveQA());
            jsonObject.put("runUAT", tcInfo.getActiveUAT());
            jsonObject.put("runPROD", tcInfo.getActivePROD());
            jsonObject.put("priority", tcInfo.getPriority());
            jsonObject.put("group", tcInfo.getGroup());
            jsonObject.put("status", tcInfo.getStatus());
            JSONArray countryList = new JSONArray();
            for (TestCaseCountry tcc : tcInfo.getTestCaseCountry()) {
                countryList.put(tcc.getCountry());
            }
            jsonObject.put("countriesList", countryList);
            jsonObject.put("shortDescription", tcInfo.getDescription());
            jsonObject.put("description", tcInfo.getBehaviorOrValueExpected());
            jsonObject.put("howTo", tcInfo.getHowTo());
            jsonObject.put("active", tcInfo.getTcActive());
            jsonObject.put("fromSprint", tcInfo.getFromBuild());
            jsonObject.put("fromRevision", tcInfo.getFromRev());
            jsonObject.put("toSprint", tcInfo.getToBuild());
            jsonObject.put("toRevision", tcInfo.getToRev());
            jsonObject.put("lastExecutionStatus", tcInfo.getLastExecutionStatus());
            jsonObject.put("bugID", tcInfo.getBugID());
            jsonObject.put("targetSprint", tcInfo.getTargetBuild());
            jsonObject.put("targetRevision", tcInfo.getTargetRev());
            jsonObject.put("comment", tcInfo.getComment());
            jsonObject.put("test", tcInfo.getTest());
            jsonObject.put("testcase", tcInfo.getTestCase());
            JSONArray propertyList = new JSONArray();
            List<TestCaseCountryProperties> properties = testCaseDAO.findDistinctPropertiesOfTestCase(test, testcase);
            for (TestCaseCountryProperties prop : properties) {
                JSONObject property = new JSONObject();
                property.put("property", prop.getProperty());
                property.put("description", prop.getDescription());
                property.put("type", prop.getType());
                property.put("database", prop.getDatabase());
                property.put("value1", prop.getValue1());
                property.put("value2", prop.getValue2());
                property.put("length", prop.getLength());
                property.put("rowLimit", prop.getRowLimit());
                property.put("nature", prop.getNature());
                List<String> countriesSelected = testCaseDAO.findCountryByProperty(prop);
                for (TestCaseCountry tcc : tcInfo.getTestCaseCountry()) {
                    if (!(countriesSelected == null) && (countriesSelected.contains(tcc.getCountry()))) {
                        property.put(tcc.getCountry(), true);
                    } else {
                        property.put(tcc.getCountry(), false);
                    }
                }
                propertyList.put(property);
            }
            jsonObject.put("properties", propertyList);
            List<TestCaseStep> tcs = loadTestCaseService.loadTestCaseStep(tcInfo);
            JSONArray list = new JSONArray();
            for (TestCaseStep step : tcs) {
                JSONObject stepObject = new JSONObject();
                stepObject.put("number", step.getStep());
                stepObject.put("name", step.getDescription());
                int i = 1;
                JSONArray actionList = new JSONArray();
                JSONArray controlList = new JSONArray();
                JSONArray sequenceList = new JSONArray();
                for (TestCaseStepAction action : step.getTestCaseStepAction()) {
                    JSONObject actionObject = new JSONObject();
                    actionObject.put("sequence", i);
                    actionObject.put("action", action.getAction());
                    actionObject.put("object", action.getValue1());
                    actionObject.put("property", action.getValue2());
                    actionObject.put("fatal", "");
                    actionList.put(actionObject);
                    sequenceList.put(actionObject);
                    for (TestCaseStepActionControl control : action.getTestCaseStepActionControl()) {
                        JSONObject controlObject = new JSONObject();
                        controlObject.put("step", control.getStep());
                        controlObject.put("sequence", control.getSequence());
                        controlObject.put("order", control.getControlSequence());
                        controlObject.put("action", control.getControl());
                        controlObject.put("object", control.getValue2());
                        controlObject.put("property", control.getValue1());
                        controlObject.put("fatal", control.getFatal());
                        controlList.put(controlObject);
                        // test
                        controlObject = new JSONObject();
                        controlObject.put("sequence", i);
                        controlObject.put("action", control.getControl());
                        controlObject.put("object", control.getValue2());
                        controlObject.put("property", control.getValue1());
                        controlObject.put("fatal", control.getFatal());
                        sequenceList.put(controlObject);
                    }
                    i++;
                }
                stepObject.put("actions", actionList);
                stepObject.put("controls", controlList);
                stepObject.put("sequences", sequenceList);
                list.put(stepObject);
            }
            // jsonObject.put("actions", actionList);
            // jsonObject.put("controls", controlList);
            jsonObject.put("list", list);
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().print(jsonObject.toString());
        } catch (JSONException exception) {
            LOG.warn(exception.toString());
        }
    } catch (CerberusException ex) {
        LOG.warn(ex);
    }
}
Also used : TestCaseStepAction(org.cerberus.crud.entity.TestCaseStepAction) CerberusException(org.cerberus.exception.CerberusException) TestCaseCountryProperties(org.cerberus.crud.entity.TestCaseCountryProperties) PolicyFactory(org.owasp.html.PolicyFactory) JSONArray(org.json.JSONArray) ILoadTestCaseService(org.cerberus.crud.service.ILoadTestCaseService) JSONException(org.json.JSONException) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) ApplicationContext(org.springframework.context.ApplicationContext) ITestCaseCountryPropertiesDAO(org.cerberus.crud.dao.ITestCaseCountryPropertiesDAO) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) TestCaseStepActionControl(org.cerberus.crud.entity.TestCaseStepActionControl)

Example 5 with ITestCaseService

use of org.cerberus.crud.service.ITestCaseService in project cerberus-source by cerberustesting.

the class GetTestCaseList method doGet.

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ITestCaseService testService = appContext.getBean(ITestCaseService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String test = policy.sanitize(httpServletRequest.getParameter("test"));
    JSONArray array = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    for (TestCase testcase : testService.findTestCaseByTest(test)) {
        array.put(testcase.getTestCase());
    }
    try {
        jsonObject.put("testcasesList", array);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(jsonObject.toString());
    } catch (JSONException exception) {
        LOG.warn(exception.toString());
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) PolicyFactory(org.owasp.html.PolicyFactory) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Aggregations

ITestCaseService (org.cerberus.crud.service.ITestCaseService)24 ApplicationContext (org.springframework.context.ApplicationContext)21 TestCase (org.cerberus.crud.entity.TestCase)20 JSONObject (org.json.JSONObject)20 PolicyFactory (org.owasp.html.PolicyFactory)16 AnswerItem (org.cerberus.util.answer.AnswerItem)12 JSONArray (org.json.JSONArray)11 ILogEventService (org.cerberus.crud.service.ILogEventService)10 MessageEvent (org.cerberus.engine.entity.MessageEvent)9 JSONException (org.json.JSONException)9 TestCaseStep (org.cerberus.crud.entity.TestCaseStep)8 Answer (org.cerberus.util.answer.Answer)8 TestCaseCountry (org.cerberus.crud.entity.TestCaseCountry)7 CerberusException (org.cerberus.exception.CerberusException)7 ArrayList (java.util.ArrayList)5 TestCaseCountryProperties (org.cerberus.crud.entity.TestCaseCountryProperties)5 TestCaseStepAction (org.cerberus.crud.entity.TestCaseStepAction)5 TestCaseStepActionControl (org.cerberus.crud.entity.TestCaseStepActionControl)5 ITestCaseStepService (org.cerberus.crud.service.ITestCaseStepService)5 List (java.util.List)4