Search in sources :

Example 71 with ILogEventService

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

the class CreateTestCaseLabel method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    // Parameter that we cannot secure as we need the html --> We DECODE them
    Integer myIdInt = 0;
    String[] myLabelIdList = request.getParameterValues("labelid");
    String[] myTestList = request.getParameterValues("test");
    String[] myTestCaseList = request.getParameterValues("testcase");
    if ((myTestList.length == 0) || (myTestCaseList.length == 0) || (myLabelIdList.length == 0)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Missing Parameter (either test, testcase or labelid)."));
        ans.setResultMessage(msg);
    } else if (myTestList.length != myTestCaseList.length) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Number of Test does not match number of testcase."));
        ans.setResultMessage(msg);
    }
    StringBuilder output_message = new StringBuilder();
    int massErrorCounter = 0;
    for (int i = 0; i < myLabelIdList.length; i++) {
        String myLabelId = myLabelIdList[i];
        myIdInt = 0;
        boolean label_error = true;
        try {
            if (myLabelId != null && !myLabelId.equals("")) {
                myIdInt = Integer.valueOf(policy.sanitize(myLabelId));
                label_error = false;
            }
        } catch (Exception ex) {
            label_error = true;
        }
        /**
         * Checking all constrains before calling the services.
         */
        if (label_error) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert labelid to an integer value or labelid is missing."));
            ans.setResultMessage(msg);
            massErrorCounter++;
            output_message.append("<br>id : ").append(myLabelId).append(" - ").append(msg.getDescription());
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ILabelService labelService = appContext.getBean(ILabelService.class);
            IFactoryTestCaseLabel factoryTestCaseLabel = appContext.getBean(IFactoryTestCaseLabel.class);
            ITestCaseLabelService testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);
            ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
            IApplicationService applicationService = appContext.getBean(IApplicationService.class);
            AnswerItem resp = labelService.readByKey(myIdInt);
            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%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Label does not exist."));
                ans.setResultMessage(msg);
                massErrorCounter++;
                output_message.append("<br>labelid : ").append(myLabelId).append(" - ").append(msg.getDescription());
            } else {
                Label myLab = (Label) resp.getItem();
                for (int j = 0; j < myTestList.length; j++) {
                    String myTest = myTestList[j];
                    String myTestCase = myTestCaseList[j];
                    resp = testCaseService.readByKey(myTest, myTestCase);
                    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%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Test Case does not exist."));
                        ans.setResultMessage(msg);
                        massErrorCounter++;
                        output_message.append("<br>testcase : ").append(myLabelId).append(" - ").append(msg.getDescription());
                    } else {
                        TestCase myTestCaseObj = (TestCase) resp.getItem();
                        resp = applicationService.readByKey(myTestCaseObj.getApplication());
                        if ((resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                            Application myApplication = (Application) resp.getItem();
                            if ((StringUtil.isNullOrEmpty(myLab.getSystem())) || (myApplication.getSystem().equals(myLab.getSystem()))) {
                                TestCaseLabel tcLabel = factoryTestCaseLabel.create(0, myTest, myTestCase, myIdInt, request.getRemoteUser(), null, "", null, null);
                                ans = testCaseLabelService.create(tcLabel);
                                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                                    /**
                                     * Update was successful. Adding Log
                                     * entry.
                                     */
                                    logEventService.createForPrivateCalls("/CreateTestCaseLabel", "CREATE", "Created TestCaseLabel : ['" + myIdInt + "'|'" + myTest + "'|'" + myTestCase + "']", request);
                                } else {
                                    massErrorCounter++;
                                    output_message.append("<br>Label : ").append(myLabelId).append(" Test : '").append(myTest).append("' TestCase : '").append(myTestCase).append("' - ").append(ans.getResultMessage().getDescription());
                                }
                            } else {
                                massErrorCounter++;
                                output_message.append("<br>Label : ").append(myLabelId).append(" Test : '").append(myTest).append("' TestCase : '").append(myTestCase).append("' - ").append("Label does not belong to the same system as TestCase system.");
                            }
                        }
                    }
                }
            }
        }
    }
    if (myTestList.length > 1) {
        if (massErrorCounter == myTestList.length) {
            // All updates are in ERROR.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Mass Update").replace("%REASON%", massErrorCounter + " label links(s) out of " + (myTestList.length * myLabelIdList.length) + " failed to be created due to an issue.<br>") + output_message.toString());
            ans.setResultMessage(msg);
        } else if (massErrorCounter > 0) {
            // At least 1 update in error
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Mass Update").replace("%REASON%", massErrorCounter + " label links(s) out of " + (myTestList.length * myLabelIdList.length) + " failed to be created due to an issue.<br>") + output_message.toString());
            ans.setResultMessage(msg);
        } else {
            // No error detected.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Mass Update") + "\n\nAll " + (myTestList.length * myLabelIdList.length) + " label links(s) created successfuly.");
            ans.setResultMessage(msg);
        }
        logEventService.createForPrivateCalls("/CreateTestCaseLabel", "MASSUPDATE", msg.getDescription(), request);
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) Label(org.cerberus.crud.entity.Label) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) ILabelService(org.cerberus.crud.service.ILabelService) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) Application(org.cerberus.crud.entity.Application) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) ITestCaseLabelService(org.cerberus.crud.service.ITestCaseLabelService) IApplicationService(org.cerberus.crud.service.IApplicationService)

Example 72 with ILogEventService

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

the class DeleteTest method processRequest.

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

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

Example 73 with ILogEventService

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

the class DeleteTestCaseCountry method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), "", charset);
    String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testCase"), null, charset);
    String country = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("country"), "", charset);
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    /**
     * Checking all constrains before calling the services.
     */
    if (testcase == null || (StringUtil.isNullOrEmpty(test)) || (StringUtil.isNullOrEmpty(country))) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Delete").replace("%REASON%", "test or testCase or country is missing!"));
        ans.setResultMessage(msg);
    } else {
        // Checking the autorities here.
        ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
        AnswerItem resp = testCaseService.readByKey(test, testcase);
        TestCase tc = (TestCase) resp.getItem();
        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%", "TestCaseCountry").replace("%OPERATION%", "Create").replace("%REASON%", "TestCase does not exist."));
            ans.setResultMessage(msg);
        } else if (!request.isUserInRole("Test")) {
            // We cannot update the testcase if the user is not at least in Test role.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Create").replace("%REASON%", "Not enought privilege to create the testCaseCountry. You must belong to Test Privilege."));
            ans.setResultMessage(msg);
        } else if ((tc.getStatus().equalsIgnoreCase("WORKING")) && !(request.isUserInRole("TestAdmin"))) {
            // If Test Case is WORKING we need TestAdmin priviliges.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Create").replace("%REASON%", "Not enought privilege to create the testCaseCountry. The test case is in WORKING status and needs TestAdmin privilege to be updated"));
            ans.setResultMessage(msg);
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ITestCaseCountryService testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
            resp = testCaseCountryService.readByKey(test, testcase, country);
            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%", "TestCaseCountry").replace("%OPERATION%", "Delete").replace("%REASON%", "TestCaseCountry 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.
                 */
                TestCaseCountry testCaseCountryData = (TestCaseCountry) resp.getItem();
                ans = testCaseCountryService.delete(testCaseCountryData);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Delete was successful. Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/DeleteTestCaseCountry", "DELETE", "Delete TestCaseCountry : ['" + test + "'|'" + testcase + "'|'" + country + "']", 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 : Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) PolicyFactory(org.owasp.html.PolicyFactory) TestCase(org.cerberus.crud.entity.TestCase) MessageEvent(org.cerberus.engine.entity.MessageEvent) ITestCaseService(org.cerberus.crud.service.ITestCaseService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) ILogEventService(org.cerberus.crud.service.ILogEventService) AnswerItem(org.cerberus.util.answer.AnswerItem) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService)

Example 74 with ILogEventService

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

the class CreateRobot method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.cerberus.exception.CerberusException
 * @throws org.json.JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    Gson gson = new Gson();
    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");
    String charset = request.getCharacterEncoding();
    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robot"), null, charset);
    String port = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("port"), null, charset);
    String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("platform"), null, charset);
    String browser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browser"), null, charset);
    String version = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("version"), "", charset);
    String active = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("active"), "Y", charset);
    String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
    String userAgent = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("useragent"), "", charset);
    String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("screensize"), "", charset);
    String robotDecli = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotDecli"), "", charset);
    String hostUser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("hostUsername"), null, charset);
    String hostPassword = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("hostPassword"), null, charset);
    List<RobotCapability> capabilities = (List<RobotCapability>) (request.getParameter("capabilities") == null ? Collections.emptyList() : gson.fromJson(request.getParameter("capabilities"), new TypeToken<List<RobotCapability>>() {
    }.getType()));
    // Parameter that we cannot secure as we need the html --> We DECODE them
    String host = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("host"), null, charset);
    // Securing capabilities by setting them the associated robot name
    // Check also if there is no duplicated capability
    Map<String, Object> capabilityMap = new HashMap<String, Object>();
    for (RobotCapability capability : capabilities) {
        capabilityMap.put(capability.getCapability(), null);
        capability.setRobot(robot);
    }
    Integer robotid = 0;
    boolean robotid_error = false;
    try {
        if (request.getParameter("robotid") != null && !request.getParameter("robotid").equals("")) {
            robotid = Integer.valueOf(policy.sanitize(request.getParameter("robotid")));
        }
    } catch (Exception ex) {
        robotid_error = true;
    }
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(robot)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Create").replace("%REASON%", "Robot name is missing."));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(host)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Create").replace("%REASON%", "Robot host is missing."));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(platform)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Create").replace("%REASON%", "Robot platform is missing."));
        ans.setResultMessage(msg);
    } else if (robotid_error) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Create").replace("%REASON%", "Could not manage to convert robotid to an integer value or robotid is missing."));
        ans.setResultMessage(msg);
    } else if (capabilityMap.size() != capabilities.size()) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Robot").replace("%OPERATION%", "Create").replace("%REASON%", "There is at least one duplicated capability. Please edit or remove it to continue."));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IRobotService robotService = appContext.getBean(IRobotService.class);
        IFactoryRobot robotFactory = appContext.getBean(IFactoryRobot.class);
        Robot robotData = robotFactory.create(robotid, robot, host, port, platform, browser, version, active, description, userAgent, screenSize, hostUser, hostPassword, capabilities, robotDecli);
        ans = robotService.create(robotData);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateRobot", "CREATE", "Create Robot : ['" + robot + "']", request);
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) Gson(com.google.gson.Gson) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) IRobotService(org.cerberus.crud.service.IRobotService) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) IFactoryRobot(org.cerberus.crud.factory.IFactoryRobot) JSONObject(org.json.JSONObject) ILogEventService(org.cerberus.crud.service.ILogEventService) List(java.util.List) JSONObject(org.json.JSONObject) RobotCapability(org.cerberus.crud.entity.RobotCapability) IFactoryRobot(org.cerberus.crud.factory.IFactoryRobot) Robot(org.cerberus.crud.entity.Robot)

Example 75 with ILogEventService

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

the class UpdateDeployType method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    String deployType = policy.sanitize(request.getParameter("deploytype"));
    String description = policy.sanitize(request.getParameter("description"));
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(deployType)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Deploy Type").replace("%OPERATION%", "Update").replace("%REASON%", "Deploy Type (deploytype) is missing"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IDeployTypeService deployTypeService = appContext.getBean(IDeployTypeService.class);
        AnswerItem resp = deployTypeService.readByKey(deployType);
        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%", "Deploy Type").replace("%OPERATION%", "Update").replace("%REASON%", "Deploy Type does not exist."));
            ans.setResultMessage(msg);
        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can update it.
             */
            DeployType deployTypeData = (DeployType) resp.getItem();
            deployTypeData.setDescription(description);
            ans = deployTypeService.update(deployTypeData);
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Update was successful. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/UpdateDeployType", "UPDATE", "Updated Deploy Type : ['" + deployType + "']", request);
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : DeployType(org.cerberus.crud.entity.DeployType) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) IDeployTypeService(org.cerberus.crud.service.IDeployTypeService) AnswerItem(org.cerberus.util.answer.AnswerItem)

Aggregations

ILogEventService (org.cerberus.crud.service.ILogEventService)93 ApplicationContext (org.springframework.context.ApplicationContext)92 JSONObject (org.json.JSONObject)80 MessageEvent (org.cerberus.engine.entity.MessageEvent)77 Answer (org.cerberus.util.answer.Answer)72 PolicyFactory (org.owasp.html.PolicyFactory)62 AnswerItem (org.cerberus.util.answer.AnswerItem)55 CerberusException (org.cerberus.exception.CerberusException)34 JSONException (org.json.JSONException)33 IOException (java.io.IOException)23 ServletException (javax.servlet.ServletException)23 ArrayList (java.util.ArrayList)18 PrintWriter (java.io.PrintWriter)16 TestCase (org.cerberus.crud.entity.TestCase)15 ITestCaseService (org.cerberus.crud.service.ITestCaseService)15 JSONArray (org.json.JSONArray)15 IParameterService (org.cerberus.crud.service.IParameterService)13 List (java.util.List)12 ITestCaseCountryService (org.cerberus.crud.service.ITestCaseCountryService)12 LogEventService (org.cerberus.crud.service.impl.LogEventService)12