Search in sources :

Example 1 with Application

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

the class TestCaseExecutionQueueDAO method readDistinctColumnByTag.

@Override
public AnswerList readDistinctColumnByTag(String tag, boolean env, boolean country, boolean browser, boolean app) {
    AnswerList answer = new AnswerList();
    StringBuilder query = new StringBuilder();
    StringBuilder distinct = new StringBuilder();
    int prev = 0;
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    if (!(!env && !country && !app && !browser)) {
        if (env) {
            distinct.append("exq.Environment");
            prev++;
        }
        if (country) {
            if (prev != 0) {
                prev = 0;
                distinct.append(",");
            }
            distinct.append("exq.Country");
            prev++;
        }
        if (browser) {
            if (prev != 0) {
                prev = 0;
                distinct.append(",");
            }
            distinct.append("exq.Browser");
            prev++;
        }
        if (app) {
            if (prev != 0) {
                prev = 0;
                distinct.append(",");
            }
            distinct.append("tec.Application");
        }
        query.append("SELECT tec.test, tec.testcase, exq.tag,  ");
        query.append(distinct.toString());
        query.append(" FROM testcase tec LEFT JOIN testcaseexecutionqueue exq ON exq.Test = tec.Test AND exq.TestCase = tec.TestCase WHERE tag = ? GROUP BY ");
        query.append(distinct.toString());
    } else {
        // If there is no distinct, select nothing
        query.append("SELECT * FROM testcaseexecutionqueue exq WHERE 1=0 AND tag = ?");
    }
    Connection connection = this.databaseSpring.connect();
    List<TestCaseExecutionQueue> column = new ArrayList<TestCaseExecutionQueue>();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        preStat.setString(1, tag);
        try {
            ResultSet resultSet = preStat.executeQuery();
            try {
                while (resultSet.next()) {
                    TestCaseExecutionQueue tmp = new TestCaseExecutionQueue();
                    tmp.setTest(resultSet.getString("tec.test"));
                    tmp.setTestCase(resultSet.getString("tec.testcase"));
                    tmp.setTag(resultSet.getString("exq.tag"));
                    if (env) {
                        tmp.setEnvironment(resultSet.getString("Environment"));
                    } else {
                        tmp.setEnvironment("");
                    }
                    if (country) {
                        tmp.setCountry(resultSet.getString("Country"));
                    } else {
                        tmp.setCountry("");
                    }
                    if (browser) {
                        tmp.setBrowser(resultSet.getString("Browser"));
                    } else {
                        tmp.setBrowser("");
                    }
                    if (app) {
                        Application application = factoryApplication.create(resultSet.getString("Application"));
                        tmp.setApplicationObj(application);
                    }
                    column.add(tmp);
                }
                msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseExecution").replace("%OPERATION%", "SELECT"));
                answer = new AnswerList(column, column.size());
            } catch (SQLException exception) {
                LOG.warn("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
                column = null;
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                }
            }
        } catch (SQLException ex) {
            LOG.warn("Unable to execute query : " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
            column = null;
        } finally {
            if (preStat != null) {
                preStat.close();
            }
        }
    } catch (SQLException ex) {
        LOG.warn(ex.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            LOG.warn("Unable to execute query : " + ex.toString());
        }
    }
    answer.setResultMessage(msg);
    return answer;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) PreparedStatement(java.sql.PreparedStatement) IFactoryApplication(org.cerberus.crud.factory.IFactoryApplication) Application(org.cerberus.crud.entity.Application)

Example 2 with Application

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

the class EmailBodyGeneration method GenerateTestRecapTable.

@Override
public String GenerateTestRecapTable(String system, String build, String revision, String country) {
    String TestRecapTable;
    try (Connection conn = databaseSpring.connect();
        Statement stmtBuildContent = conn.createStatement();
        Statement stmtCountryList = conn.createStatement()) {
        List<Application> appliList = applicationService.convert(applicationService.readBySystem(system));
        String inSQL = SqlUtil.getInSQLClause(appliList);
        String contentSQL = "SELECT i.gp1, count(*) nb_exe, OK.c nb_exe_OK, format(OK.c/count(*)*100,0)  per_OK" + "     , DTC.c nb_dtc, DAPP.c nb_dapp" + " FROM testcaseexecution t" + " JOIN invariant i on i.value=t.Environment and i.idname='ENVIRONMENT'" + " LEFT OUTER JOIN ( " + " SELECT i.gp1 gp1, count(*) c" + " FROM testcaseexecution t1 " + " JOIN invariant i on i.value=t1.Environment and i.idname='ENVIRONMENT'" + " WHERE t1.ControlStatus= 'OK' and t1.Build='" + build + "' and t1.Revision='" + revision + "'";
        if (country.equalsIgnoreCase("ALL") == false) {
            contentSQL = contentSQL + " and t1.country='" + country + "'";
        }
        contentSQL = contentSQL + " and Environment not in ('PROD','DEV') " + " and (status='WORKING' or status is null) " + " and application " + inSQL + " GROUP BY gp1 " + " order by gp1) as OK" + " ON OK.gp1=i.gp1" + " LEFT OUTER JOIN ( " + " select toto.gp1 gp1, count(*) c from " + " (SELECT i.gp1 gp1,t1.test, t1.testcase " + " FROM testcaseexecution t1 " + " JOIN invariant i on i.value=t1.Environment and i.idname='ENVIRONMENT'" + " WHERE t1.ControlStatus in ('OK','KO') and t1.Build='" + build + "' and t1.Revision='" + revision + "'";
        if (country.equalsIgnoreCase("ALL") == false) {
            contentSQL = contentSQL + " and t1.country='" + country + "'";
        }
        contentSQL = contentSQL + " and Environment not in ('PROD','DEV') " + " and (status='WORKING' or status is null) " + " and application " + inSQL + " GROUP BY gp1 , t1.test, t1.testcase" + " order by gp1 , t1.test, t1.testcase ) AS toto" + " group by gp1) as DTC" + " ON DTC.gp1=i.gp1" + " LEFT OUTER JOIN ( " + " select toto.gp1 gp1, count(*) c from " + " (SELECT i.gp1 gp1,t1.application " + " FROM testcaseexecution t1 " + " JOIN invariant i on i.value=t1.Environment and i.idname='ENVIRONMENT'" + " WHERE t1.ControlStatus in ('OK','KO') and t1.Build='" + build + "' and t1.Revision='" + revision + "'";
        if (country.equalsIgnoreCase("ALL") == false) {
            contentSQL = contentSQL + " and t1.country='" + country + "'";
        }
        contentSQL = contentSQL + " and Environment not in ('PROD','DEV') " + " and (status='WORKING' or status is null) " + " and application " + inSQL + " GROUP BY gp1 , t1.application" + " order by gp1 , t1.application ) AS toto" + " group by gp1) as DAPP" + " ON DAPP.gp1=i.gp1" + " where 1=1" + " and application " + inSQL + " and t.ControlStatus in ('OK','KO') and t.Build='" + build + "' and t.Revision='" + revision + "' ";
        if (country.equalsIgnoreCase("ALL") == false) {
            contentSQL = contentSQL + " and t.country='" + country + "'";
        }
        contentSQL = contentSQL + " and Environment not in ('PROD','DEV') " + " and (status='WORKING' or status is null) " + " group by i.gp1 order by i.sort;";
        LOG.debug(Infos.getInstance().getProjectNameAndVersion() + " - SQL : " + contentSQL);
        String CountryListSQL = "SELECT value from invariant where idname='COUNTRY';";
        try (ResultSet rsBC = stmtBuildContent.executeQuery(contentSQL);
            ResultSet rsCountry = stmtCountryList.executeQuery(CountryListSQL)) {
            StringBuilder CountryList = new StringBuilder();
            while (rsCountry.next()) {
                CountryList.append(rsCountry.getString("value"));
                CountryList.append("&Country=");
            }
            if (rsBC.first()) {
                if (country.equalsIgnoreCase("ALL")) {
                    TestRecapTable = "Here is the Test Execution Recap accross all countries for " + build + "/" + revision + " :";
                } else {
                    TestRecapTable = "Here is the Test Execution Recap for your country for " + build + "/" + revision + " :";
                }
                TestRecapTable = TestRecapTable + "<table>";
                TestRecapTable = TestRecapTable + "<tr style=\"background-color:#cad3f1; font-style:bold\">" + "<td>Env</td><td>Nb Exe</td><td>% OK</td><td>Distinct TestCases</td><td>Distinct Applications</td></tr>";
                String bckColor = "#f3f6fa";
                int a = 1;
                StringBuilder buf = new StringBuilder();
                do {
                    a++;
                    int b;
                    b = a % 2;
                    if (b == 1) {
                        bckColor = "#e1e7f3";
                    } else {
                        bckColor = "White";
                    }
                    String contentEnv = "";
                    String contentNBExe = "";
                    String contentPerOK = "";
                    String contentNBDTC = "";
                    String contentNBDAPP = "";
                    if (rsBC.getString("gp1") != null) {
                        contentEnv = rsBC.getString("gp1");
                    }
                    if (rsBC.getString("nb_exe") != null) {
                        contentNBExe = rsBC.getString("nb_exe");
                    }
                    if (rsBC.getString("per_OK") != null) {
                        contentPerOK = rsBC.getString("per_OK");
                    }
                    if (rsBC.getString("nb_dtc") != null) {
                        contentNBDTC = rsBC.getString("nb_dtc");
                    }
                    if (rsBC.getString("nb_dapp") != null) {
                        contentNBDAPP = rsBC.getString("nb_dapp");
                    }
                    // TestRecapTable = TestRecapTable + "<tr style=\"background-color:" + bckColor + "; font-size:80%\"><td>"
                    buf.append("<tr style=\"background-color:").append(bckColor).append("; font-size:80%\"><td>").append(contentEnv).append("</td><td>").append(contentNBExe).append("</td><td>").append(contentPerOK).append("</td><td>").append(contentNBDTC).append("</td><td>").append(contentNBDAPP).append("</td></tr>");
                } while (rsBC.next());
                TestRecapTable += buf.toString() + "</table><br>";
            } else if (country.equalsIgnoreCase("ALL")) {
                TestRecapTable = "Unfortunatly, no test have been executed for any country for " + build + "/" + revision + " :-(<br><br>";
            } else {
                TestRecapTable = "Unfortunatly, no test have been executed for your country for " + build + "/" + revision + " :-(<br><br>";
            }
        } catch (Exception e) {
            LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched.", e);
            TestRecapTable = e.getMessage();
        }
    } catch (Exception e) {
        LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched.", e);
        TestRecapTable = e.getMessage();
    }
    return TestRecapTable;
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) Application(org.cerberus.crud.entity.Application)

Example 3 with Application

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

the class AddToExecutionQueueV001 method processRequest.

/**
 * Process request for both GET and POST method.
 *
 * <p>
 * Request processing is divided in two parts:
 * <ol>
 * <li>Getting all test cases which have been sent to this servlet;</li>
 * <li>Try to insert all these test cases to the execution queue.</li>
 * </ol>
 * </p>
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    final String charset = request.getCharacterEncoding();
    Date requestDate = new Date();
    // Loading Services.
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    inQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
    inQueueFactoryService = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
    executionThreadService = appContext.getBean(IExecutionThreadPoolService.class);
    testCaseService = appContext.getBean(ITestCaseService.class);
    invariantService = appContext.getBean(IInvariantService.class);
    applicationService = appContext.getBean(IApplicationService.class);
    testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
    campaignParameterService = appContext.getBean(ICampaignParameterService.class);
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    // Default message to unexpected error.
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    AnswerItem<List<TestCase>> testcases = null;
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createForPublicCalls("/AddToExecutionQueueV001", "CALL", "AddToExecutionQueueV001 called : " + request.getRequestURL(), request);
    // Parsing all parameters.
    // Execution scope parameters : Campaign, TestCases, Countries, Environment, Browser.
    String campaign = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_CAMPAIGN), null, charset);
    List<Map<String, String>> selectedTests;
    selectedTests = ParameterParserUtil.parseListMapParamAndDecode(request.getParameterValues(PARAMETER_SELECTED_TEST), null, charset);
    List<String> countries;
    countries = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_COUNTRY), null, charset);
    List<String> environments;
    environments = ParameterParserUtil.parseListParamAndDecodeAndDeleteEmptyValue(request.getParameterValues(PARAMETER_ENVIRONMENT), null, charset);
    List<String> browsers;
    browsers = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_BROWSER), null, charset);
    // Execution parameters.
    String tag = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_TAG), "");
    String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT), null, charset);
    String robotIP = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT_IP), null, charset);
    String robotPort = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT_PORT), null, charset);
    String browserVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_BROWSER_VERSION), null, charset);
    String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_PLATFORM), null, charset);
    String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_SCREENSIZE), null, charset);
    int manualURL = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_MANUAL_URL), DEFAULT_VALUE_MANUAL_URL, charset);
    String manualHost = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_HOST), null, charset);
    String manualContextRoot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_CONTEXT_ROOT), null, charset);
    String manualLoginRelativeURL = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_LOGIN_RELATIVE_URL), null, charset);
    String manualEnvData = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_ENV_DATA), null, charset);
    int screenshot = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_SCREENSHOT), DEFAULT_VALUE_SCREENSHOT, charset);
    int verbose = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_VERBOSE), DEFAULT_VALUE_VERBOSE, charset);
    String timeout = request.getParameter(PARAMETER_TIMEOUT);
    int pageSource = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_PAGE_SOURCE), DEFAULT_VALUE_PAGE_SOURCE, charset);
    int seleniumLog = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_SELENIUM_LOG), DEFAULT_VALUE_SELENIUM_LOG, charset);
    int retries = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_RETRIES), DEFAULT_VALUE_RETRIES, charset);
    String manualExecution = ParameterParserUtil.parseStringParamAndDecode(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION, charset);
    int priority = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_EXEPRIORITY), DEFAULT_VALUE_PRIORITY, charset);
    if (manualExecution.equals("")) {
        manualExecution = DEFAULT_VALUE_MANUAL_EXECUTION;
    }
    String outputFormat = ParameterParserUtil.parseStringParamAndDecode(request.getParameter(PARAMETER_OUTPUTFORMAT), DEFAULT_VALUE_OUTPUTFORMAT, charset);
    // Defining help message.
    String helpMessage = "This servlet is used to add to Cerberus execution queue a list of execution. Execution list will be calculated from cartesian product of " + "testcase, country, environment and browser list. Those list can be defined from the associated servlet parameter but can also be defined from campaign directy inside Cerberus.\n" + "List defined from servlet overwrite the list defined from the campaign. All other execution parameters will be taken to each execution.\n" + "Available parameters:\n" + "- " + PARAMETER_CAMPAIGN + " : Campaign name from which testcase, countries, environment and browser can be defined from Cerberus. [" + campaign + "]\n" + "- " + PARAMETER_SELECTED_TEST + " : List of testCase to trigger. That list overwrite the list coming from the Campaign (if defined). Ex : " + PARAMETER_SELECTED_TEST + "=" + PARAMETER_SELECTED_TEST_KEY_TEST + "=Cerberus%26" + PARAMETER_SELECTED_TEST_KEY_TESTCASE + "=9644A. [" + selectedTests + "]\n" + "- " + PARAMETER_COUNTRY + " : List of countries to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + countries + "]\n" + "- " + PARAMETER_ENVIRONMENT + " : List of environment to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + environments + "]\n" + "- " + PARAMETER_BROWSER + " : List of browser to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + browsers + "]\n" + "- " + PARAMETER_ROBOT + " : Robot Name that will be used for every execution triggered. [" + robot + "]\n" + "- " + PARAMETER_ROBOT_IP + " : Robot IP that will be used for every execution triggered. [" + robotIP + "]\n" + "- " + PARAMETER_ROBOT_PORT + " : Robot Port that will be used for every execution triggered. [" + robotPort + "]\n" + "- " + PARAMETER_BROWSER_VERSION + " : Browser Version that will be used for every execution triggered. [" + browserVersion + "]\n" + "- " + PARAMETER_PLATFORM + " : Platform that will be used for every execution triggered. [" + platform + "]\n" + "- " + PARAMETER_SCREENSIZE + " : Size of the screen that will be used for every execution triggered. [" + screenSize + "]\n" + "- " + PARAMETER_MANUAL_URL + " : Activate (1) or not (0) the Manual URL of the application to execute. If activated the 4 parameters after are necessary. [" + manualURL + "]\n" + "- " + PARAMETER_MANUAL_HOST + " : Host of the application to test (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualHost + "]\n" + "- " + PARAMETER_MANUAL_CONTEXT_ROOT + " : Context root of the application to test (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualContextRoot + "]\n" + "- " + PARAMETER_MANUAL_LOGIN_RELATIVE_URL + " : Relative login URL of the application (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualLoginRelativeURL + "]\n" + "- " + PARAMETER_MANUAL_ENV_DATA + " : Environment where to get the test data when a " + PARAMETER_MANUAL_URL + " is defined. (only used when manualURL is active). [" + manualEnvData + "]\n" + "- " + PARAMETER_TAG + " : Tag that will be used for every execution triggered. [" + tag + "]\n" + "- " + PARAMETER_SCREENSHOT + " : Activate or not the screenshots for every execution triggered. [" + screenshot + "]\n" + "- " + PARAMETER_VERBOSE + " : Verbose level for every execution triggered. [" + verbose + "]\n" + "- " + PARAMETER_TIMEOUT + " : Timeout used for the action that will be used for every execution triggered. [" + timeout + "]\n" + "- " + PARAMETER_PAGE_SOURCE + " : Record Page Source during for every execution triggered. [" + pageSource + "]\n" + "- " + PARAMETER_SELENIUM_LOG + " : Get the SeleniumLog at the end of the execution for every execution triggered. [" + seleniumLog + "]\n" + "- " + PARAMETER_MANUAL_EXECUTION + " : Execute testcase in manual mode for every execution triggered. [" + manualExecution + "]\n" + "- " + PARAMETER_RETRIES + " : Number of tries if the result is not OK for every execution triggered. [" + retries + "]\n" + "- " + PARAMETER_EXEPRIORITY + " : Priority that will be used in the queue for every execution triggered. [" + priority + "]\n";
    // try {
    // Checking the parameter validity.
    StringBuilder errorMessage = new StringBuilder();
    boolean error = false;
    if (tag == null || tag.isEmpty()) {
        if (request.getRemoteUser() != null) {
            tag = request.getRemoteUser();
        }
        if (tag.length() > 0) {
            tag += ".";
        }
        if (campaign != null) {
            tag += campaign;
        }
        if (tag.length() > 0) {
            tag += ".";
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String mytimestamp = sdf.format(timestamp);
        tag += mytimestamp;
    } else if (tag.length() > 255) {
        errorMessage.append("Error - Parameter " + PARAMETER_TAG + " is too big. Maximum size if 255. Current size is : " + tag.length());
        error = true;
    }
    if (campaign != null && !campaign.isEmpty()) {
        final AnswerItem<Map<String, List<String>>> parsedCampaignParameters = campaignParameterService.parseParametersByCampaign(campaign);
        if (parsedCampaignParameters.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            // If parameters are already defined from request, we ignore the campaign values.
            if (countries == null || countries.isEmpty()) {
                countries = parsedCampaignParameters.getItem().get(CampaignParameter.COUNTRY_PARAMETER);
            }
            if (environments == null || environments.isEmpty()) {
                environments = parsedCampaignParameters.getItem().get(CampaignParameter.ENVIRONMENT_PARAMETER);
            }
            if (browsers == null || browsers.isEmpty()) {
                browsers = parsedCampaignParameters.getItem().get(CampaignParameter.BROWSER_PARAMETER);
            }
        }
        if ((countries != null) && (selectedTests == null || selectedTests.isEmpty())) {
            // If no countries are found, there is no need to get the testcase list. None will be returned.
            selectedTests = new ArrayList<>();
            testcases = testCaseService.findTestCaseByCampaignNameAndCountries(campaign, countries.toArray(new String[countries.size()]));
            ListIterator<TestCase> it = testcases.getItem().listIterator();
            while (it.hasNext()) {
                TestCase str = it.next();
                selectedTests.add(new HashMap<String, String>() {

                    {
                        put(PARAMETER_SELECTED_TEST_KEY_TEST, str.getTest());
                        put(PARAMETER_SELECTED_TEST_KEY_TESTCASE, str.getTestCase());
                    }
                });
            }
        }
    }
    if (countries == null || countries.isEmpty()) {
        errorMessage.append("Error - No Country defined. You can either feed it with parameter '" + PARAMETER_COUNTRY + "' or add it into the campaign definition.");
        error = true;
    }
    if (browsers == null || browsers.isEmpty()) {
        errorMessage.append("Error - No Browser defined. You can either feed it with parameter '" + PARAMETER_BROWSER + "' or add it into the campaign definition.");
        error = true;
    }
    if (selectedTests == null || selectedTests.isEmpty()) {
        errorMessage.append("Error - No TestCases defined. You can either feed it with parameter '" + PARAMETER_SELECTED_TEST + "' or add it into the campaign definition.");
        error = true;
    }
    if (manualURL >= 1) {
        if (manualHost == null || manualEnvData == null) {
            errorMessage.append("Error - ManualURL has been activated but no ManualHost or Manual Environment defined.");
            error = true;
        }
    } else if (environments == null || environments.isEmpty()) {
        errorMessage.append("Error - No Environment defined (and " + PARAMETER_MANUAL_URL + " not activated). You can either feed it with parameter '" + PARAMETER_ENVIRONMENT + "' or add it into the campaign definition.");
        error = true;
    }
    int nbExe = 0;
    JSONArray jsonArray = new JSONArray();
    String user = request.getRemoteUser() == null ? "" : request.getRemoteUser();
    // Starting the request only if previous parameters exist.
    if (!error) {
        // Create Tag when exist.
        if (!StringUtil.isNullOrEmpty(tag)) {
            // We create or update it.
            ITagService tagService = appContext.getBean(ITagService.class);
            tagService.createAuto(tag, campaign, user);
        }
        // Part 1: Getting all possible xecution from test cases + countries + environments + browsers which have been sent to this servlet.
        Map<String, String> invariantEnv = invariantService.readToHashMapGp1StringByIdname("ENVIRONMENT", "");
        List<TestCaseExecutionQueue> toInserts = new ArrayList<TestCaseExecutionQueue>();
        try {
            LOG.debug("Nb of TestCase : " + selectedTests.size());
            for (Map<String, String> selectedTest : selectedTests) {
                String test = selectedTest.get(PARAMETER_SELECTED_TEST_KEY_TEST);
                String testCase = selectedTest.get(PARAMETER_SELECTED_TEST_KEY_TESTCASE);
                TestCase tc = testCaseService.convert(testCaseService.readByKey(test, testCase));
                // TestCases that are not active are not inserted into queue.
                if (tc.getTcActive().equals("Y")) {
                    // We only insert testcase that exist for the given country.
                    for (TestCaseCountry country : testCaseCountryService.convert(testCaseCountryService.readByTestTestCase(null, test, testCase))) {
                        if (countries.contains(country.getCountry())) {
                            // for each environment we test that correspondng gp1 is compatible with testcase environment flag activation.
                            for (String environment : environments) {
                                String envGp1 = invariantEnv.get(environment);
                                if (((envGp1.equals("PROD")) && (tc.getActivePROD().equalsIgnoreCase("Y"))) || ((envGp1.equals("UAT")) && (tc.getActiveUAT().equalsIgnoreCase("Y"))) || ((envGp1.equals("QA")) && (tc.getActiveQA().equalsIgnoreCase("Y"))) || (envGp1.equals("DEV"))) {
                                    // Getting Application in order to check application type against browser.
                                    Application app = applicationService.convert(applicationService.readByKey(tc.getApplication()));
                                    if ((app != null) && (app.getType() != null) && app.getType().equalsIgnoreCase(Application.TYPE_GUI)) {
                                        for (String browser : browsers) {
                                            try {
                                                toInserts.add(inQueueFactoryService.create(test, testCase, country.getCountry(), environment, robot, robotIP, robotPort, browser, browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, user, null, null, null));
                                            } catch (FactoryCreationException e) {
                                                LOG.error("Unable to insert record due to: " + e, e);
                                                LOG.error("test: " + test + "-" + testCase + "-" + country.getCountry() + "-" + environment + "-" + robot);
                                            }
                                        }
                                    } else {
                                        // Application does not support browser so we force an empty value.
                                        LOG.debug("Forcing Browser to empty value. Application type=" + app.getType());
                                        try {
                                            toInserts.add(inQueueFactoryService.create(test, testCase, country.getCountry(), environment, robot, robotIP, robotPort, "", browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, user, null, null, null));
                                        } catch (FactoryCreationException e) {
                                            LOG.error("Unable to insert record due to: " + e, e);
                                            LOG.error("test: " + test + "-" + testCase + "-" + country.getCountry() + "-" + environment + "-" + robot);
                                        }
                                    }
                                } else {
                                    LOG.debug("Env group not active for testcase : " + environment);
                                }
                            }
                        } else {
                            LOG.debug("Country does not match. " + countries + " " + country.getCountry());
                        }
                    }
                } else {
                    LOG.debug("TestCase not Active.");
                }
            }
        } catch (CerberusException ex) {
            LOG.warn(ex);
        }
        // Part 2: Try to insert all these test cases to the execution queue.
        List<String> errorMessages = new ArrayList<String>();
        for (TestCaseExecutionQueue toInsert : toInserts) {
            try {
                inQueueService.convert(inQueueService.create(toInsert));
                nbExe++;
                JSONObject value = new JSONObject();
                value.put("queueId", toInsert.getId());
                value.put("test", toInsert.getTest());
                value.put("testcase", toInsert.getTestCase());
                value.put("country", toInsert.getCountry());
                value.put("environment", toInsert.getEnvironment());
                jsonArray.put(value);
            } catch (CerberusException e) {
                String errorMessageTmp = "Unable to insert " + toInsert.toString() + " due to " + e.getMessage();
                LOG.warn(errorMessageTmp);
                errorMessages.add(errorMessageTmp);
                continue;
            } catch (JSONException ex) {
                java.util.logging.Logger.getLogger(AddToExecutionQueueV001.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        // Part 3 : Trigger JobQueue
        try {
            executionThreadService.executeNextInQueueAsynchroneously(false);
        } catch (CerberusException ex) {
            String errorMessageTmp = "Unable to feed the execution queue due to " + ex.getMessage();
            LOG.warn(errorMessageTmp);
            errorMessages.add(errorMessageTmp);
        }
        if (!errorMessages.isEmpty()) {
            StringBuilder errorMessageTmp = new StringBuilder();
            for (String item : errorMessages) {
                errorMessageTmp.append(item);
                errorMessageTmp.append(LINE_SEPARATOR);
            }
            errorMessage.append(errorMessageTmp.toString());
        }
        errorMessage.append(nbExe);
        errorMessage.append(" execution(s) succesfully inserted to queue. ");
        if (testcases.getResultMessage().getSource() == MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT) {
            errorMessage.append(testcases.getResultMessage().getDescription());
        }
        // Message that everything went fine.
        msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
    } else {
    // In case of errors, we display the help message.
    // errorMessage.append(helpMessage);
    }
    // Init Answer with potencial error from Parsing parameter.
    AnswerItem answer = new AnswerItem(msg);
    switch(outputFormat) {
        case "json":
            try {
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
                jsonResponse.put("message", errorMessage.toString());
                jsonResponse.put("helpMessage", helpMessage);
                jsonResponse.put("tag", tag);
                jsonResponse.put("nbExe", nbExe);
                jsonResponse.put("queueList", jsonArray);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf8");
                response.getWriter().print(jsonResponse.toString());
            } catch (JSONException e) {
                LOG.warn(e);
                // returns a default error message with the json format that is able to be parsed by the client-side
                response.setContentType("application/json");
                response.setCharacterEncoding("utf8");
                response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
            }
            break;
        default:
            response.setContentType("text");
            response.setCharacterEncoding("utf8");
            if (error) {
                errorMessage.append("\n");
                errorMessage.append(helpMessage);
            }
            response.getWriter().print(errorMessage.toString());
    }
// } catch (Exception e) {
// LOG.error(e);
// out.println(helpMessage);
// out.println(e.toString());
// }
}
Also used : MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) FactoryCreationException(org.cerberus.exception.FactoryCreationException) ApplicationContext(org.springframework.context.ApplicationContext) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) ArrayList(java.util.ArrayList) List(java.util.List) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) IApplicationService(org.cerberus.crud.service.IApplicationService) PrintWriter(java.io.PrintWriter) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService) CerberusException(org.cerberus.exception.CerberusException) IInvariantService(org.cerberus.crud.service.IInvariantService) ICampaignParameterService(org.cerberus.crud.service.ICampaignParameterService) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem) Date(java.util.Date) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) JSONObject(org.json.JSONObject) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) TestCase(org.cerberus.crud.entity.TestCase) ITagService(org.cerberus.crud.service.ITagService) HashMap(java.util.HashMap) Map(java.util.Map) Application(org.cerberus.crud.entity.Application)

Example 4 with Application

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

the class AddToExecutionQueueV002 method processRequest.

/**
 * Process request for both GET and POST method.
 *
 * <p>
 * Request processing is divided in two parts:
 * <ol>
 * <li>Getting all test cases which have been sent to this servlet;</li>
 * <li>Try to insert all these test cases to the execution queue.</li>
 * </ol>
 * </p>
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    final String charset = request.getCharacterEncoding();
    Date requestDate = new Date();
    // Loading Services.
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    inQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
    inQueueFactoryService = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
    executionThreadService = appContext.getBean(IExecutionThreadPoolService.class);
    testCaseService = appContext.getBean(ITestCaseService.class);
    invariantService = appContext.getBean(IInvariantService.class);
    applicationService = appContext.getBean(IApplicationService.class);
    testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
    campaignParameterService = appContext.getBean(ICampaignParameterService.class);
    countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    // Default message to unexpected error.
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    AnswerItem<List<TestCase>> testcases = null;
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createForPublicCalls("/AddToExecutionQueueV002", "CALL", "AddToExecutionQueueV002 called : " + request.getRequestURL(), request);
    // Parsing all parameters.
    // Execution scope parameters : Campaign, TestCases, Countries, Environment, Browser.
    String campaign = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_CAMPAIGN), null, charset);
    List<String> selectTest;
    selectTest = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_TEST), null, charset);
    List<String> selectTestCase;
    selectTestCase = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_TESTCASE), null, charset);
    List<String> countries;
    countries = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_COUNTRY), null, charset);
    List<String> environments;
    environments = ParameterParserUtil.parseListParamAndDecodeAndDeleteEmptyValue(request.getParameterValues(PARAMETER_ENVIRONMENT), null, charset);
    List<String> browsers = new ArrayList<>();
    ;
    browsers = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues(PARAMETER_BROWSER), browsers, charset);
    // Execution parameters.
    String tag = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_TAG), "");
    String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT), null, charset);
    String robotIP = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT_IP), null, charset);
    String robotPort = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_ROBOT_PORT), null, charset);
    String browserVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_BROWSER_VERSION), null, charset);
    String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_PLATFORM), null, charset);
    String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_SCREENSIZE), null, charset);
    int manualURL = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_MANUAL_URL), DEFAULT_VALUE_MANUAL_URL, charset);
    String manualHost = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_HOST), null, charset);
    String manualContextRoot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_CONTEXT_ROOT), null, charset);
    String manualLoginRelativeURL = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_LOGIN_RELATIVE_URL), null, charset);
    String manualEnvData = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter(PARAMETER_MANUAL_ENV_DATA), null, charset);
    int screenshot = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_SCREENSHOT), DEFAULT_VALUE_SCREENSHOT, charset);
    int verbose = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_VERBOSE), DEFAULT_VALUE_VERBOSE, charset);
    String timeout = request.getParameter(PARAMETER_TIMEOUT);
    int pageSource = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_PAGE_SOURCE), DEFAULT_VALUE_PAGE_SOURCE, charset);
    int seleniumLog = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_SELENIUM_LOG), DEFAULT_VALUE_SELENIUM_LOG, charset);
    int retries = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_RETRIES), DEFAULT_VALUE_RETRIES, charset);
    String manualExecution = ParameterParserUtil.parseStringParamAndDecode(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION, charset);
    int priority = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter(PARAMETER_EXEPRIORITY), DEFAULT_VALUE_PRIORITY, charset);
    if (manualExecution.equals("")) {
        manualExecution = DEFAULT_VALUE_MANUAL_EXECUTION;
    }
    String outputFormat = ParameterParserUtil.parseStringParamAndDecode(request.getParameter(PARAMETER_OUTPUTFORMAT), DEFAULT_VALUE_OUTPUTFORMAT, charset);
    // Defining help message.
    String helpMessage = "This servlet is used to add to Cerberus execution queue a list of execution. Execution list will be calculated from cartesian product of " + "testcase, country, environment and browser list. Those list can be defined from the associated servlet parameter but can also be defined from campaign directy inside Cerberus.\n" + "List defined from servlet overwrite the list defined from the campaign. All other execution parameters will be taken to each execution.\n" + "Available parameters:\n" + "- " + PARAMETER_CAMPAIGN + " : Campaign name from which testcase, countries, environment and browser can be defined from Cerberus. [" + campaign + "]\n" + "- " + PARAMETER_TEST + " : List of test to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + selectTest + "]\n" + "- " + PARAMETER_TESTCASE + " : List of testCase to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + selectTestCase + "]\n" + "- " + PARAMETER_COUNTRY + " : List of countries to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + countries + "]\n" + "- " + PARAMETER_ENVIRONMENT + " : List of environment to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + environments + "]\n" + "- " + PARAMETER_BROWSER + " : List of browser to trigger. That list overwrite the list coming from the Campaign (if defined).. [" + browsers + "]\n" + "- " + PARAMETER_ROBOT + " : Robot Name that will be used for every execution triggered. [" + robot + "]\n" + "- " + PARAMETER_ROBOT_IP + " : Robot IP that will be used for every execution triggered. [" + robotIP + "]\n" + "- " + PARAMETER_ROBOT_PORT + " : Robot Port that will be used for every execution triggered. [" + robotPort + "]\n" + "- " + PARAMETER_BROWSER_VERSION + " : Browser Version that will be used for every execution triggered. [" + browserVersion + "]\n" + "- " + PARAMETER_PLATFORM + " : Platform that will be used for every execution triggered. [" + platform + "]\n" + "- " + PARAMETER_SCREENSIZE + " : Size of the screen that will be used for every execution triggered. [" + screenSize + "]\n" + "- " + PARAMETER_MANUAL_URL + " : Activate (1) or not (0) the Manual URL of the application to execute. If activated the 4 parameters after are necessary. [" + manualURL + "]\n" + "- " + PARAMETER_MANUAL_HOST + " : Host of the application to test (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualHost + "]\n" + "- " + PARAMETER_MANUAL_CONTEXT_ROOT + " : Context root of the application to test (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualContextRoot + "]\n" + "- " + PARAMETER_MANUAL_LOGIN_RELATIVE_URL + " : Relative login URL of the application (only used when " + PARAMETER_MANUAL_URL + " is activated). [" + manualLoginRelativeURL + "]\n" + "- " + PARAMETER_MANUAL_ENV_DATA + " : Environment where to get the test data when a " + PARAMETER_MANUAL_URL + " is defined. (only used when manualURL is active). [" + manualEnvData + "]\n" + "- " + PARAMETER_TAG + " : Tag that will be used for every execution triggered. [" + tag + "]\n" + "- " + PARAMETER_SCREENSHOT + " : Activate or not the screenshots for every execution triggered. [" + screenshot + "]\n" + "- " + PARAMETER_VERBOSE + " : Verbose level for every execution triggered. [" + verbose + "]\n" + "- " + PARAMETER_TIMEOUT + " : Timeout used for the action that will be used for every execution triggered. [" + timeout + "]\n" + "- " + PARAMETER_PAGE_SOURCE + " : Record Page Source during for every execution triggered. [" + pageSource + "]\n" + "- " + PARAMETER_SELENIUM_LOG + " : Get the SeleniumLog at the end of the execution for every execution triggered. [" + seleniumLog + "]\n" + "- " + PARAMETER_MANUAL_EXECUTION + " : Execute testcase in manual mode for every execution triggered. [" + manualExecution + "]\n" + "- " + PARAMETER_RETRIES + " : Number of tries if the result is not OK for every execution triggered. [" + retries + "]\n" + "- " + PARAMETER_EXEPRIORITY + " : Priority that will be used in the queue for every execution triggered. [" + priority + "]\n" + "- " + PARAMETER_OUTPUTFORMAT + " : Format of the servlet output. can be compact, json [" + outputFormat + "]\n";
    // try {
    // Checking the parameter validity.
    StringBuilder errorMessage = new StringBuilder();
    boolean error = false;
    if (tag == null || tag.isEmpty()) {
        if (request.getRemoteUser() != null) {
            tag = request.getRemoteUser();
        }
        if (tag.length() > 0) {
            tag += ".";
        }
        if (campaign != null) {
            tag += campaign;
        }
        if (tag.length() > 0) {
            tag += ".";
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String mytimestamp = sdf.format(timestamp);
        tag += mytimestamp;
    } else if (tag.length() > 255) {
        errorMessage.append("Error - Parameter ").append(PARAMETER_TAG).append(" is too big. Maximum size if 255. Current size is : ").append(tag.length()).append("\n");
        error = true;
    }
    if (campaign != null && !campaign.isEmpty()) {
        final AnswerItem<Map<String, List<String>>> parsedCampaignParameters = campaignParameterService.parseParametersByCampaign(campaign);
        if (parsedCampaignParameters.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            // If parameters are already defined from request, we ignore the campaign values.
            if (countries == null || countries.isEmpty()) {
                countries = parsedCampaignParameters.getItem().get(CampaignParameter.COUNTRY_PARAMETER);
            }
            if (environments == null || environments.isEmpty()) {
                environments = parsedCampaignParameters.getItem().get(CampaignParameter.ENVIRONMENT_PARAMETER);
            }
            if (browsers == null || browsers.isEmpty()) {
                browsers = parsedCampaignParameters.getItem().get(CampaignParameter.BROWSER_PARAMETER);
            }
        }
        if ((countries != null) && (selectTest == null || selectTest.isEmpty())) {
            // If no countries are found, there is no need to get the testcase list. None will be returned.
            selectTest = new ArrayList<>();
            selectTestCase = new ArrayList<>();
            testcases = testCaseService.findTestCaseByCampaignNameAndCountries(campaign, countries.toArray(new String[countries.size()]));
            for (TestCase campaignTestCase : testcases.getItem()) {
                selectTest.add(campaignTestCase.getTest());
                selectTestCase.add(campaignTestCase.getTestCase());
            }
        }
    }
    if (countries == null || countries.isEmpty()) {
        errorMessage.append("Error - No Country defined. You can either feed it with parameter '" + PARAMETER_COUNTRY + "' or add it into the campaign definition.\n");
        error = true;
    }
    if ((StringUtil.isNullOrEmpty(robot)) && (browsers == null || browsers.isEmpty())) {
        errorMessage.append("Error - No Browser defined. You can either feed it with parameter '" + PARAMETER_BROWSER + "' or add it into the campaign definition.\n");
        error = true;
    }
    if (selectTest == null || selectTest.isEmpty() || selectTestCase == null || selectTestCase.isEmpty()) {
        errorMessage.append("Error - No TestCases defined. You can either feed it with parameters '" + PARAMETER_TEST + "' and '" + PARAMETER_TESTCASE + "' or add it into the campaign definition.\n");
        error = true;
    }
    if ((selectTest != null) && (selectTestCase != null) && (selectTest.size() != selectTestCase.size())) {
        errorMessage.append("Error - Test list size (").append(selectTest.size()).append(") is not the same as testcase list size (").append(selectTestCase.size()).append("). Please check that both list are consistent.\n");
        error = true;
    }
    if (manualURL >= 1) {
        if (manualHost == null || manualEnvData == null) {
            errorMessage.append("Error - ManualURL has been activated but no ManualHost or Manual Environment defined.\n");
            error = true;
        }
    } else if (environments == null || environments.isEmpty()) {
        errorMessage.append("Error - No Environment defined (and " + PARAMETER_MANUAL_URL + " not activated). You can either feed it with parameter '" + PARAMETER_ENVIRONMENT + "' or add it into the campaign definition.\n");
        error = true;
    }
    int nbExe = 0;
    JSONArray jsonArray = new JSONArray();
    String user = request.getRemoteUser() == null ? "" : request.getRemoteUser();
    int nbtestcasenotactive = 0;
    int nbtestcaseenvgroupnotallowed = 0;
    int nbenvnotexist = 0;
    boolean tagAlreadyAdded = false;
    int nbbrowser = 0;
    if (browsers.isEmpty()) {
        nbbrowser = 1;
    } else {
        nbbrowser = browsers.size();
    }
    int nbtescase = selectTest.size();
    int nbenv = environments.size();
    int nbcountries = countries.size();
    // Starting the request only if previous parameters exist.
    if (!error) {
        // Part 1: Getting all possible Execution from test cases + countries + environments + browsers which have been sent to this servlet.
        Map<String, String> invariantEnv = invariantService.readToHashMapGp1StringByIdname("ENVIRONMENT", "");
        List<TestCaseExecutionQueue> toInserts = new ArrayList<TestCaseExecutionQueue>();
        try {
            HashMap<String, CountryEnvParam> envMap = new HashMap<>();
            LOG.debug("Loading all environments.");
            for (CountryEnvParam envParam : countryEnvParamService.convert(countryEnvParamService.readActiveBySystem(null))) {
                envMap.put(envParam.getSystem() + LOCAL_SEPARATOR + envParam.getCountry() + LOCAL_SEPARATOR + envParam.getEnvironment(), envParam);
            }
            LOG.debug("Nb of TestCase : " + selectTest.size());
            for (int i = 0; i < selectTest.size(); i++) {
                // for (String localTest : selectTest) {
                String test = selectTest.get(i);
                String testCase = selectTestCase.get(i);
                TestCase tc = testCaseService.convert(testCaseService.readByKey(test, testCase));
                // TestCases that are not active are not inserted into queue.
                if (tc.getTcActive().equals("Y")) {
                    // We only insert testcase that exist for the given country.
                    for (TestCaseCountry country : testCaseCountryService.convert(testCaseCountryService.readByTestTestCase(null, test, testCase))) {
                        if (countries.contains(country.getCountry())) {
                            // for each environment we test that correspondng gp1 is compatible with testcase environment flag activation.
                            for (String environment : environments) {
                                String envGp1 = invariantEnv.get(environment);
                                if (((envGp1.equals("PROD")) && (tc.getActivePROD().equalsIgnoreCase("Y"))) || ((envGp1.equals("UAT")) && (tc.getActiveUAT().equalsIgnoreCase("Y"))) || ((envGp1.equals("QA")) && (tc.getActiveQA().equalsIgnoreCase("Y"))) || (envGp1.equals("DEV"))) {
                                    // Getting Application in order to check application type against browser.
                                    Application app = applicationService.convert(applicationService.readByKey(tc.getApplication()));
                                    if (envMap.containsKey(app.getSystem() + LOCAL_SEPARATOR + country.getCountry() + LOCAL_SEPARATOR + environment)) {
                                        // Create Tag only if not already done and defined.
                                        if (!StringUtil.isNullOrEmpty(tag) && !tagAlreadyAdded) {
                                            // We create or update it.
                                            ITagService tagService = appContext.getBean(ITagService.class);
                                            tagService.createAuto(tag, campaign, user);
                                            tagAlreadyAdded = true;
                                        }
                                        if ((app != null) && (app.getType() != null) && app.getType().equalsIgnoreCase(Application.TYPE_GUI)) {
                                            if (browsers == null || browsers.isEmpty()) {
                                                browsers.add("");
                                            }
                                            for (String browser : browsers) {
                                                try {
                                                    LOG.debug("Insert Queue Entry.");
                                                    toInserts.add(inQueueFactoryService.create(test, testCase, country.getCountry(), environment, robot, robotIP, robotPort, browser, browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, user, null, null, null));
                                                } catch (FactoryCreationException e) {
                                                    LOG.error("Unable to insert record due to: " + e, e);
                                                    LOG.error("test: " + test + "-" + testCase + "-" + country.getCountry() + "-" + environment + "-" + robot);
                                                }
                                            }
                                        } else {
                                            // Application does not support browser so we force an empty value.
                                            LOG.debug("Forcing Browser to empty value. Application type=" + app.getType());
                                            try {
                                                LOG.debug("Insert Queue Entry.");
                                                toInserts.add(inQueueFactoryService.create(test, testCase, country.getCountry(), environment, robot, robotIP, robotPort, "", browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, priority, user, null, null, null));
                                            } catch (FactoryCreationException e) {
                                                LOG.error("Unable to insert record due to: " + e, e);
                                                LOG.error("test: " + test + "-" + testCase + "-" + country.getCountry() + "-" + environment + "-" + robot);
                                            }
                                        }
                                    } else {
                                        LOG.debug("Env does not exist or is not active.");
                                        nbenvnotexist = nbenvnotexist + nbbrowser;
                                    }
                                } else {
                                    LOG.debug("Env group not active for testcase : " + environment);
                                    nbtestcaseenvgroupnotallowed = nbtestcaseenvgroupnotallowed + nbbrowser;
                                }
                            }
                        } else {
                            LOG.debug("Country does not match. " + countries + " " + country.getCountry());
                        }
                    }
                } else {
                    LOG.debug("TestCase not Active.");
                    nbtestcasenotactive = nbtestcasenotactive + (nbcountries * nbenv * nbbrowser);
                }
            }
        } catch (CerberusException ex) {
            LOG.warn(ex);
        }
        // Part 2: Try to insert all these test cases to the execution queue.
        List<String> errorMessages = new ArrayList<String>();
        for (TestCaseExecutionQueue toInsert : toInserts) {
            try {
                inQueueService.convert(inQueueService.create(toInsert));
                nbExe++;
                JSONObject value = new JSONObject();
                value.put("queueId", toInsert.getId());
                value.put("test", toInsert.getTest());
                value.put("testcase", toInsert.getTestCase());
                value.put("country", toInsert.getCountry());
                value.put("environment", toInsert.getEnvironment());
                jsonArray.put(value);
            } catch (CerberusException e) {
                String errorMessageTmp = "Unable to insert " + toInsert.toString() + " due to " + e.getMessage();
                LOG.warn(errorMessageTmp);
                errorMessages.add(errorMessageTmp);
                continue;
            } catch (JSONException ex) {
                LOG.error(ex);
            }
        }
        // Part 3 : Trigger JobQueue
        try {
            executionThreadService.executeNextInQueueAsynchroneously(false);
        } catch (CerberusException ex) {
            String errorMessageTmp = "Unable to feed the execution queue due to " + ex.getMessage();
            LOG.warn(errorMessageTmp);
            errorMessages.add(errorMessageTmp);
        }
        if (!errorMessages.isEmpty()) {
            StringBuilder errorMessageTmp = new StringBuilder();
            for (String item : errorMessages) {
                errorMessageTmp.append(item);
                errorMessageTmp.append(LINE_SEPARATOR);
            }
            errorMessage.append(errorMessageTmp.toString());
        }
        errorMessage.append(nbExe);
        errorMessage.append(" execution(s) succesfully inserted to queue. ");
        if (testcases != null && testcases.getResultMessage().getSource() == MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT) {
            errorMessage.append(testcases.getResultMessage().getDescription());
        }
        // Message that everything went fine.
        msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
    } else {
    // In case of errors, we display the help message.
    // errorMessage.append(helpMessage);
    }
    // Init Answer with potencial error from Parsing parameter.
    AnswerItem answer = new AnswerItem(msg);
    switch(outputFormat) {
        case "json":
            try {
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
                jsonResponse.put("message", errorMessage.toString());
                jsonResponse.put("helpMessage", helpMessage);
                jsonResponse.put("tag", tag);
                jsonResponse.put("nbExe", nbExe);
                jsonResponse.put("nbErrorTCNotActive", nbtestcasenotactive);
                jsonResponse.put("nbErrorTCNotAllowedOnEnv", nbtestcaseenvgroupnotallowed);
                jsonResponse.put("nbErrorEnvNotExistOrNotActive", nbenvnotexist);
                jsonResponse.put("queueList", jsonArray);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf8");
                response.getWriter().print(jsonResponse.toString());
            } catch (JSONException e) {
                LOG.warn(e);
                // returns a default error message with the json format that is able to be parsed by the client-side
                response.setContentType("application/json");
                response.setCharacterEncoding("utf8");
                response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
            }
            break;
        default:
            response.setContentType("text");
            response.setCharacterEncoding("utf8");
            if (error) {
                errorMessage.append("\n");
                errorMessage.append(helpMessage);
            }
            response.getWriter().print(errorMessage.toString());
    }
// } catch (Exception e) {
// LOG.error(e);
// out.println(helpMessage);
// out.println(e.toString());
// }
}
Also used : HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) FactoryCreationException(org.cerberus.exception.FactoryCreationException) ApplicationContext(org.springframework.context.ApplicationContext) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) ArrayList(java.util.ArrayList) List(java.util.List) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) IApplicationService(org.cerberus.crud.service.IApplicationService) PrintWriter(java.io.PrintWriter) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService) CerberusException(org.cerberus.exception.CerberusException) IInvariantService(org.cerberus.crud.service.IInvariantService) ICampaignParameterService(org.cerberus.crud.service.ICampaignParameterService) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem) Date(java.util.Date) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) JSONObject(org.json.JSONObject) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) TestCase(org.cerberus.crud.entity.TestCase) ITagService(org.cerberus.crud.service.ITagService) ICountryEnvParamService(org.cerberus.crud.service.ICountryEnvParamService) HashMap(java.util.HashMap) Map(java.util.Map) CountryEnvParam(org.cerberus.crud.entity.CountryEnvParam) Application(org.cerberus.crud.entity.Application)

Example 5 with Application

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

the class ApplicationDAO method readBySystemByCriteria.

@Override
public AnswerList<Application> readBySystemByCriteria(String system, int start, int amount, String column, String dir, String searchTerm, Map<String, List<String>> individualSearch) {
    AnswerList response = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    List<Application> objectList = new ArrayList<Application>();
    StringBuilder searchSQL = new StringBuilder();
    List<String> individalColumnSearchValues = new ArrayList<String>();
    StringBuilder query = new StringBuilder();
    // SQL_CALC_FOUND_ROWS allows to retrieve the total number of columns by disrearding the limit clauses that
    // were applied -- used for pagination p
    query.append("SELECT SQL_CALC_FOUND_ROWS * FROM application app ");
    searchSQL.append(" where 1=1 ");
    if (!StringUtil.isNullOrEmpty(searchTerm)) {
        searchSQL.append(" and (app.`application` like ?");
        searchSQL.append(" or app.`description` like ?");
        searchSQL.append(" or app.`sort` like ?");
        searchSQL.append(" or app.`type` like ?");
        searchSQL.append(" or app.`System` like ?");
        searchSQL.append(" or app.`Subsystem` like ?");
        searchSQL.append(" or app.`svnURL` like ?");
        searchSQL.append(" or app.`bugtrackerurl` like ?");
        searchSQL.append(" or app.`bugtrackernewurl` like ?");
        searchSQL.append(" or app.`deploytype` like ?");
        searchSQL.append(" or app.`mavengroupid` like ?)");
    }
    if (individualSearch != null && !individualSearch.isEmpty()) {
        searchSQL.append(" and ( 1=1 ");
        for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
            searchSQL.append(" and ");
            searchSQL.append(SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue()));
            individalColumnSearchValues.addAll(entry.getValue());
        }
        searchSQL.append(" )");
    }
    if (!StringUtil.isNullOrEmpty(system)) {
        searchSQL.append(" and (`System` = ? )");
    }
    query.append(searchSQL);
    if (!StringUtil.isNullOrEmpty(column)) {
        query.append(" order by `").append(column).append("` ").append(dir);
    }
    if ((amount <= 0) || (amount >= MAX_ROW_SELECTED)) {
        query.append(" limit ").append(start).append(" , ").append(MAX_ROW_SELECTED);
    } else {
        query.append(" limit ").append(start).append(" , ").append(amount);
    }
    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            int i = 1;
            if (!StringUtil.isNullOrEmpty(searchTerm)) {
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
            }
            for (String individualColumnSearchValue : individalColumnSearchValues) {
                preStat.setString(i++, individualColumnSearchValue);
            }
            if (!StringUtil.isNullOrEmpty(system)) {
                preStat.setString(i++, system);
            }
            ResultSet resultSet = preStat.executeQuery();
            try {
                // gets the data
                while (resultSet.next()) {
                    objectList.add(this.loadFromResultSet(resultSet));
                }
                // get the total number of rows
                resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
                int nrTotalRows = 0;
                if (resultSet != null && resultSet.next()) {
                    nrTotalRows = resultSet.getInt(1);
                }
                if (objectList.size() >= MAX_ROW_SELECTED) {
                    // Result of SQl was limited by MAX_ROW_SELECTED constrain. That means that we may miss some lines in the resultList.
                    LOG.error("Partial Result in the query.");
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT);
                    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Maximum row reached : " + MAX_ROW_SELECTED));
                    response = new AnswerList(objectList, nrTotalRows);
                } else if (objectList.size() <= 0) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND);
                    response = new AnswerList(objectList, nrTotalRows);
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                    response = new AnswerList(objectList, nrTotalRows);
                }
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                }
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
        } finally {
            if (preStat != null) {
                preStat.close();
            }
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
    } finally {
        try {
            if (!this.databaseSpring.isOnTransaction()) {
                if (connection != null) {
                    connection.close();
                }
            }
        } catch (SQLException exception) {
            LOG.warn("Unable to close connection : " + exception.toString());
        }
    }
    response.setResultMessage(msg);
    response.setDataList(objectList);
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) IFactoryApplication(org.cerberus.crud.factory.IFactoryApplication) Application(org.cerberus.crud.entity.Application) FactoryApplication(org.cerberus.crud.factory.impl.FactoryApplication) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Application (org.cerberus.crud.entity.Application)18 IApplicationService (org.cerberus.crud.service.IApplicationService)10 MessageEvent (org.cerberus.engine.entity.MessageEvent)10 AnswerItem (org.cerberus.util.answer.AnswerItem)10 JSONObject (org.json.JSONObject)10 ArrayList (java.util.ArrayList)8 ILogEventService (org.cerberus.crud.service.ILogEventService)7 CerberusException (org.cerberus.exception.CerberusException)7 ApplicationContext (org.springframework.context.ApplicationContext)7 List (java.util.List)6 IFactoryApplication (org.cerberus.crud.factory.IFactoryApplication)6 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 Connection (java.sql.Connection)5 ResultSet (java.sql.ResultSet)5 HashMap (java.util.HashMap)5 TestCase (org.cerberus.crud.entity.TestCase)5 Map (java.util.Map)4 TestCaseExecutionQueue (org.cerberus.crud.entity.TestCaseExecutionQueue)4 IFactoryTestCaseExecutionQueue (org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue)4