Search in sources :

Example 11 with IParameterService

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

the class GetExecutionQueue method processRequest.

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

Example 12 with IParameterService

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

the class GetParameter method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String echo = request.getParameter("sEcho");
    String mySystem = request.getParameter("system");
    LOG.debug("System : '" + mySystem + "'.");
    // data that will be shown in the table
    JSONArray data = new JSONArray();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IParameterService parameterService = appContext.getBean(ParameterService.class);
    try {
        JSONObject jsonResponse = new JSONObject();
        try {
            for (Parameter myParameter : parameterService.findAllParameter()) {
                JSONArray row = new JSONArray();
                row.put(myParameter.getParam()).put(myParameter.getValue()).put(myParameter.getValue()).put(myParameter.getDescription());
                data.put(row);
            }
        } catch (CerberusException ex) {
            response.setContentType("text/html");
            response.getWriter().print(ex.getMessageError().getDescription());
        }
        jsonResponse.put("aaData", data);
        jsonResponse.put("sEcho", echo);
        jsonResponse.put("iTotalRecords", data.length());
        jsonResponse.put("iTotalDisplayRecords", data.length());
        response.setContentType("application/json");
        response.getWriter().print(jsonResponse.toString());
    } catch (JSONException e) {
        LOG.warn(e);
        response.setContentType("text/html");
        response.getWriter().print(e.getMessage());
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) CerberusException(org.cerberus.exception.CerberusException) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) Parameter(org.cerberus.crud.entity.Parameter) JSONException(org.json.JSONException) IParameterService(org.cerberus.crud.service.IParameterService)

Example 13 with IParameterService

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

the class SaveManualExecutionPicture method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // using commons-fileupload http://commons.apache.org/proper/commons-fileupload/using.html
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    // Collection<Part> parts = req.getParts(); //for sevlet 3.0, in glassfish 2.x does not work
    TestCaseStepActionExecution tcsae = new TestCaseStepActionExecution();
    FileItem uploadedFile = null;
    // if is multipart we need to handle the upload data
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    IRecorderService recorderService = appContext.getBean(IRecorderService.class);
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    Integer imgPathMaxSize = parameterService.getParameterIntegerByKey("cerberus_screenshot_max_size", "", UPLOAD_PICTURE_MAXSIZE);
    // Set overall request size constraint
    // max size for the file
    upload.setFileSizeMax(imgPathMaxSize);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(req);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                tcsae = processFormField(tcsae, item);
            } else {
                // uploadFileName = processUploadedFile(item);
                uploadedFile = item;
            }
        }
    // this handles an action each time
    } catch (FileSizeLimitExceededException ex) {
        LOG.warn("File size exceed the limit: " + ex.toString());
    } catch (FileUploadException ex) {
        LOG.warn("Exception occurred while uploading file: " + ex.toString());
    }
    if (uploadedFile != null) {
        if (uploadedFile.getContentType().startsWith("image/")) {
            // TODO:FN verify if this is the best approach or if we should
            // check if the mime types for images can be configured in the web.xml and then obtain the valid mime types from the servletContext
            // getServletContext().getMimeType(fileName);
            recorderService.recordUploadedFile(tcsae.getId(), tcsae, uploadedFile);
        } else {
            LOG.warn("Problem with the file you're trying to upload. It is not an image." + "Name: " + uploadedFile.getName() + "; Content-type: " + uploadedFile.getContentType());
        }
    }
// old version : TODO to be deleted after testing
// Collection<Part> parts = req.getParts();
// String runId = req.getParameter("runId");
// String test = req.getParameter("picTest");
// String testCase = req.getParameter("picTestCase");
// String step = req.getParameter("pictStep");
// String action = req.getParameter("pictAction");
// String control = req.getParameter("pictControl") == null ? "" : req.getParameter("pictControl");
// String returnCode = req.getParameter("returnCode");
// 
// ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
// IParameterService parameterService = appContext.getBean(IParameterService.class);
// //        ITestCaseStepExecutionService testCaseStepExecutionService = appContext.getBean(ITestCaseStepExecutionService.class);
// //        ITestCaseStepActionExecutionService testCaseStepActionExecutionService = appContext.getBean(ITestCaseStepActionExecutionService.class);
// 
// try {
// String imgPath = parameterService.findParameterByKey("cerberus_exeautomedia_path", "").getValue();
// 
// File dir = new File(imgPath + runId);
// dir.mkdirs();
// 
// int seq = 1;
// long runID = ParameterParserUtil.parseLongParam(runId, 0);
// //TestCaseStepActionExecution testCaseStepActionExecution = new TestCaseStepActionExecution();
// for (Part p : parts) {
// if (p.getName().equalsIgnoreCase("files[]")) {
// if (seq == 1) {
// //                        TestCaseStepExecution tcse = new TestCaseStepExecution();
// //                        tcse.setId(runID);
// //                        tcse.setTest(test);
// //                        tcse.setTestCase(testCase);
// //                        tcse.setStep(1);
// //                        testCaseStepExecutionService.insertTestCaseStepExecution(tcse);
// }
// 
// InputStream inputStream = p.getInputStream();
// String controlName = control.equals("") ? "" : "Ct"+control;
// String name = test + "-" + testCase + "-St"+step+"Sq" + action + controlName + ".jpg";
// OutputStream outputStream = new FileOutputStream(new File(this.buildScreenshotPath(imgPath, runId, name)));
// 
// int read;
// byte[] bytes = new byte[1024];
// while ((read = inputStream.read(bytes)) != -1) {
// outputStream.write(bytes, 0, read);
// }
// outputStream.close();
// 
// Date now = new Date();
// 
// //create action
// //                    testCaseStepActionExecution.setId(runID);
// //                    testCaseStepActionExecution.setTest(test);
// //                    testCaseStepActionExecution.setTestCase(testCase);
// //                    testCaseStepActionExecution.setStep(1);
// //                    testCaseStepActionExecution.setSequence(seq);
// //                    testCaseStepActionExecution.setReturnCode(returnCode);
// //                    testCaseStepActionExecution.setReturnMessage("");
// //                    testCaseStepActionExecution.setAction("screenshot");
// //                    testCaseStepActionExecution.setObject("");
// //                    testCaseStepActionExecution.setProperty("");
// //                    testCaseStepActionExecution.setStart(now.getTime());
// //                    testCaseStepActionExecution.setEnd(now.getTime());
// //                    testCaseStepActionExecution.setStartLong(now.getTime());
// //                    testCaseStepActionExecution.setEndLong(now.getTime());
// //                    testCaseStepActionExecutionService.insertTestCaseStepActionExecution(testCaseStepActionExecution);
// //
// //                    seq++;
// }
// }
// 
// } catch (CerberusException e) {
// MyLogger.log(SaveManualExecutionPicture.class.getName(), Level.ERROR, e.toString());
// }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ApplicationContext(org.springframework.context.ApplicationContext) IRecorderService(org.cerberus.engine.execution.IRecorderService) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) TestCaseStepActionExecution(org.cerberus.crud.entity.TestCaseStepActionExecution) IParameterService(org.cerberus.crud.service.IParameterService) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 14 with IParameterService

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

the class DisableEnvironmentV000 method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String charset = request.getCharacterEncoding();
    // Loading Services.
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ICountryEnvParamService countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
    IInvariantService invariantService = appContext.getBean(IInvariantService.class);
    IBuildRevisionInvariantService buildRevisionInvariantService = appContext.getBean(IBuildRevisionInvariantService.class);
    IEmailService emailService = appContext.getBean(IEmailService.class);
    ICountryEnvParam_logService countryEnvParam_logService = appContext.getBean(ICountryEnvParam_logService.class);
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createForPublicCalls("/DisableEnvironmentV000", "CALL", "DisableEnvironmentV000 called : " + request.getRequestURL(), request);
    // Parsing all parameters.
    String system = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("system"), "", charset);
    String country = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("country"), "", charset);
    String environment = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("environment"), "", charset);
    // Defining help message.
    String helpMessage = "\nThis servlet is used to inform Cerberus that a system is disabled. For example when a Revision is beeing deployed.\n\nParameter list :\n" + "- system [mandatory] : the system where the Build Revision has been deployed. [" + system + "]\n" + "- country [mandatory] : the country where the Build Revision has been deployed. You can use ALL if you want to perform the action for all countries that exist for the given system and environement. [" + country + "]\n" + "- environment [mandatory] : the environment where the Build Revision has been deployed. [" + environment + "]\n";
    // Checking the parameter validity.
    boolean error = false;
    if (system.equalsIgnoreCase("")) {
        out.println("Error - Parameter system is mandatory.");
        error = true;
    }
    if (!system.equalsIgnoreCase("") && !invariantService.isInvariantExist("SYSTEM", system)) {
        out.println("Error - System does not exist  : " + system);
        error = true;
    }
    if (environment.equalsIgnoreCase("")) {
        out.println("Error - Parameter environment is mandatory.");
        error = true;
    }
    if (!environment.equalsIgnoreCase("") && !invariantService.isInvariantExist("ENVIRONMENT", environment)) {
        out.println("Error - Environment does not exist  : " + environment);
        error = true;
    }
    if (country.equalsIgnoreCase("")) {
        out.println("Error - Parameter country is mandatory.");
        error = true;
    } else if (!country.equalsIgnoreCase(PARAMETERALL)) {
        if (!invariantService.isInvariantExist("COUNTRY", country)) {
            out.println("Error - Country does not exist  : " + country);
            error = true;
        }
        if (!error) {
            if (!countryEnvParamService.exist(system, country, environment)) {
                out.println("Error - System/Country/Environment does not exist : " + system + "/" + country + "/" + environment);
                error = true;
            }
        }
    }
    // Starting the database update only when no blocking error has been detected.
    if (error == false) {
        /**
         * Getting the list of objects to treat.
         */
        MessageEvent msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
        Answer finalAnswer = new Answer(msg);
        AnswerList answerList = new AnswerList();
        if (country.equalsIgnoreCase(PARAMETERALL)) {
            country = null;
        }
        answerList = countryEnvParamService.readByVarious(system, country, environment, null, null, null);
        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) answerList);
        for (CountryEnvParam cepData : (List<CountryEnvParam>) answerList.getDataList()) {
            /**
             * For each object, we can update it.
             */
            cepData.setActive(false);
            Answer answerUpdate = countryEnvParamService.update(cepData);
            if (!(answerUpdate.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()))) {
                /**
                 * Object could not be updated. We stop here and report the
                 * error.
                 */
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, answerUpdate);
            } else {
                /**
                 * Update was successful.
                 */
                // Adding Log entry.
                logEventService.createForPrivateCalls("/DisableEnvironmentV000", "UPDATE", "Updated CountryEnvParam : ['" + cepData.getSystem() + "','" + cepData.getCountry() + "','" + cepData.getEnvironment() + "']", request);
                // Adding CountryEnvParam Log entry.
                countryEnvParam_logService.createLogEntry(cepData.getSystem(), cepData.getCountry(), cepData.getEnvironment(), "", "", "Disabled.", "PublicCall");
                /**
                 * Email notification.
                 */
                // Email Calculation.
                String eMailContent;
                String OutputMessage = "";
                MessageEvent me = emailService.generateAndSendDisableEnvEmail(cepData.getSystem(), cepData.getCountry(), cepData.getEnvironment());
                if (!"OK".equals(me.getMessage().getCodeString())) {
                    LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched." + me.getMessage().getDescription());
                    logEventService.createForPrivateCalls("/DisableEnvironmentV000", "DISABLE", "Warning on Disable environment : ['" + cepData.getSystem() + "','" + cepData.getCountry() + "','" + cepData.getEnvironment() + "'] " + me.getMessage().getDescription(), request);
                    OutputMessage = me.getMessage().getDescription();
                }
                if (OutputMessage.equals("")) {
                    msg = new MessageEvent(MessageEventEnum.GENERIC_OK);
                    Answer answerSMTP = new AnswerList(msg);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, answerSMTP);
                } else {
                    msg = new MessageEvent(MessageEventEnum.GENERIC_WARNING);
                    msg.setDescription(msg.getDescription().replace("%REASON%", OutputMessage + " when sending email for " + cepData.getSystem() + "/" + cepData.getCountry() + "/" + cepData.getEnvironment()));
                    Answer answerSMTP = new AnswerList(msg);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, answerSMTP);
                }
            }
        }
        /**
         * Formating and returning the result.
         */
        out.println(finalAnswer.getResultMessage().getMessage().getCodeString() + " - " + finalAnswer.getResultMessage().getDescription());
    } else {
        // In case of errors, we display the help message.
        out.println(helpMessage);
    }
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) MessageEvent(org.cerberus.engine.entity.MessageEvent) IInvariantService(org.cerberus.crud.service.IInvariantService) IParameterService(org.cerberus.crud.service.IParameterService) IBuildRevisionInvariantService(org.cerberus.crud.service.IBuildRevisionInvariantService) ICountryEnvParam_logService(org.cerberus.crud.service.ICountryEnvParam_logService) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) ILogEventService(org.cerberus.crud.service.ILogEventService) AnswerList(org.cerberus.util.answer.AnswerList) List(java.util.List) ICountryEnvParamService(org.cerberus.crud.service.ICountryEnvParamService) IEmailService(org.cerberus.service.email.IEmailService) CountryEnvParam(org.cerberus.crud.entity.CountryEnvParam) PrintWriter(java.io.PrintWriter)

Example 15 with IParameterService

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

the class DeleteTestCaseExecutionFile method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException, CerberusException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    Long fileId = ParameterParserUtil.parseLongParam(request.getParameter("fileID"), 0);
    /**
     * Checking all constrains before calling the services.
     */
    if (fileId == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseExecutionFile").replace("%OPERATION%", "Delete").replace("%REASON%", "field fileID is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        ITestCaseExecutionFileService testCaseExecutionFileService = appContext.getBean(ITestCaseExecutionFileService.class);
        IParameterService parameterService = appContext.getBean(IParameterService.class);
        IRecorderService recorderService = appContext.getBean(IRecorderService.class);
        AnswerItem resp = testCaseExecutionFileService.readByKey(fileId);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseExecutionFile").replace("%OPERATION%", "Delete").replace("%REASON%", "TestCaseExecutionFile with this ID does not exist."));
            ans.setResultMessage(msg);
        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can delete it.
             */
            TestCaseExecutionFile testCaseExecutionFile = (TestCaseExecutionFile) resp.getItem();
            String rootFolder = parameterService.getParameterStringByKey("cerberus_exemanualmedia_path", "", "");
            testCaseExecutionFileService.deleteFile(rootFolder, testCaseExecutionFile.getFileName());
            ans = testCaseExecutionFileService.delete(testCaseExecutionFile);
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Delete was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteTestCaseExecutionFile", "DELETE", "Delete TestCase Execution File : ['" + testCaseExecutionFile + "']", request);
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ITestCaseExecutionFileService(org.cerberus.crud.service.ITestCaseExecutionFileService) IParameterService(org.cerberus.crud.service.IParameterService) AnswerItem(org.cerberus.util.answer.AnswerItem) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) IRecorderService(org.cerberus.engine.execution.IRecorderService) JSONObject(org.json.JSONObject) ILogEventService(org.cerberus.crud.service.ILogEventService) DeleteTestCaseExecutionFile(org.cerberus.servlet.manualtestcase.DeleteTestCaseExecutionFile) TestCaseExecutionFile(org.cerberus.crud.entity.TestCaseExecutionFile)

Aggregations

IParameterService (org.cerberus.crud.service.IParameterService)19 ApplicationContext (org.springframework.context.ApplicationContext)19 ILogEventService (org.cerberus.crud.service.ILogEventService)13 JSONObject (org.json.JSONObject)12 MessageEvent (org.cerberus.engine.entity.MessageEvent)9 JSONException (org.json.JSONException)9 PolicyFactory (org.owasp.html.PolicyFactory)9 PrintWriter (java.io.PrintWriter)8 Answer (org.cerberus.util.answer.Answer)8 CerberusException (org.cerberus.exception.CerberusException)7 AnswerItem (org.cerberus.util.answer.AnswerItem)7 IOException (java.io.IOException)5 ServletException (javax.servlet.ServletException)5 IEmailService (org.cerberus.service.email.IEmailService)4 BufferedReader (java.io.BufferedReader)3 Timestamp (java.sql.Timestamp)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 FileItem (org.apache.commons.fileupload.FileItem)3 FileUploadException (org.apache.commons.fileupload.FileUploadException)3