Search in sources :

Example 81 with PolicyFactory

use of org.owasp.html.PolicyFactory in project cerberus-source by cerberustesting.

the class CreateDeployType 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();
    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%", "Create").replace("%REASON%", "Deploy Type name 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);
        IFactoryDeployType factoryDeployType = appContext.getBean(IFactoryDeployType.class);
        DeployType deployTypeData = factoryDeployType.create(deploytype, description);
        ans = deployTypeService.create(deployTypeData);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateDeployType", "CREATE", "Create DeployType : ['" + 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 : IFactoryDeployType(org.cerberus.crud.factory.IFactoryDeployType) DeployType(org.cerberus.crud.entity.DeployType) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) IFactoryDeployType(org.cerberus.crud.factory.IFactoryDeployType) 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)

Example 82 with PolicyFactory

use of org.owasp.html.PolicyFactory in project cerberus-source by cerberustesting.

the class ReadTestCaseExecutionQueue 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 CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException {
    String echo = request.getParameter("sEcho");
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");
    // 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%", ""));
    // Init Answer with potencial error from Parsing parameter.
    String queueId = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("queueid"), "");
    Long queueid = Long.valueOf(0);
    boolean queueid_error = false;
    if (request.getParameter("queueid") != null) {
        try {
            if (request.getParameter("queueid") != null && !request.getParameter("queueid").equals("")) {
                queueid = Long.valueOf(policy.sanitize(request.getParameter("queueid")));
                queueid_error = false;
            }
        } catch (Exception ex) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Case Execution Queue"));
            msg.setDescription(msg.getDescription().replace("%OPERATION%", "Read"));
            msg.setDescription(msg.getDescription().replace("%REASON%", "queueid must be an integer value."));
            queueid_error = true;
        }
    }
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    // Global boolean on the servlet that define if the user has permition to edit and delete object.
    boolean userHasPermissions = request.isUserInRole("RunTest");
    try {
        JSONObject jsonResponse;
        if (!Strings.isNullOrEmpty(request.getParameter("columnName"))) {
            answer = findDistinctValuesOfColumn(appContext, request, request.getParameter("columnName"));
            jsonResponse = (JSONObject) answer.getItem();
        } else if (queueid != 0) {
            answer = findExecutionQueueByKeyTech(queueid, appContext, userHasPermissions);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (request.getParameter("flag") != null && request.getParameter("flag").equals("queueStatus")) {
            answer = findExecutionInQueueStatus(appContext, request);
            jsonResponse = (JSONObject) answer.getItem();
        } else {
            answer = findExecutionInQueueList(appContext, true, request);
            jsonResponse = (JSONObject) answer.getItem();
        }
        jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", answer.getResultMessage().getDescription());
        jsonResponse.put("sEcho", echo);
        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.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) PolicyFactory(org.owasp.html.PolicyFactory) JSONObject(org.json.JSONObject) MessageEvent(org.cerberus.engine.entity.MessageEvent) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException)

Example 83 with PolicyFactory

use of org.owasp.html.PolicyFactory in project cerberus-source by cerberustesting.

the class UpdateTestCaseExecutionQueue 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());
    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
    String actionState = policy.sanitize(request.getParameter("actionState"));
    String actionSave = policy.sanitize(request.getParameter("actionSave"));
    String environment = policy.sanitize(request.getParameter("environment"));
    String country = policy.sanitize(request.getParameter("country"));
    String manualEnvData = policy.sanitize(request.getParameter("manualEnvData"));
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String test = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), null, charset);
    String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testCase"), null, charset);
    int manualURL = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("manualURL"), 0, charset);
    String manualHost = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualHost"), null, charset);
    String manualContextRoot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualContextRoot"), "", charset);
    String manualLoginRelativeURL = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualLoginRelativeURL"), "", charset);
    String tag = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("tag"), null, charset);
    String robot = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robot"), null, charset);
    String robotIP = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotIP"), null, charset);
    String robotPort = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("robotPort"), null, charset);
    String browser = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browser"), null, charset);
    String browserVersion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("browserVersion"), null, charset);
    String platform = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("platform"), null, charset);
    String screenSize = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("screenSize"), null, charset);
    int verbose = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("verbose"), 1, charset);
    int screenshot = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("screenshot"), 0, charset);
    int pageSource = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("pageSource"), 0, charset);
    int seleniumLog = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("seleniumLog"), 0, charset);
    String timeout = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("timeout"), "", charset);
    int retries = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("retries"), 0, charset);
    String manualExecution = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("manualExecution"), "", charset);
    String debugFlag = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("debugFlag"), "N", charset);
    Integer priority = TestCaseExecutionQueue.PRIORITY_DEFAULT;
    boolean prio_error = false;
    try {
        if (request.getParameter("priority") != null && !request.getParameter("priority").equals("")) {
            priority = Integer.valueOf(policy.sanitize(request.getParameter("priority")));
        }
    } catch (Exception ex) {
        prio_error = true;
    }
    // Parameter that we cannot secure as we need the html --> We DECODE them
    String[] myIds = request.getParameterValues("id");
    long id = 0;
    // Create Tag when exist.
    if (!StringUtil.isNullOrEmpty(tag)) {
        // We create or update it.
        ITagService tagService = appContext.getBean(ITagService.class);
        tagService.createAuto(tag, "", request.getRemoteUser());
    }
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    boolean id_error = false;
    for (String myId : myIds) {
        id_error = false;
        try {
            id = Long.valueOf(myId);
        } catch (NumberFormatException ex) {
            id_error = true;
        }
        /**
         * Checking all constrains before calling the services.
         */
        if (id_error) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution Queue").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert id to an integer value."));
            ans.setResultMessage(msg);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        } else if (prio_error || priority > 2147483647 || priority < -2147483648) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution Queue").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert priority to an integer value."));
            ans.setResultMessage(msg);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ITestCaseExecutionQueueService executionQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
            IExecutionThreadPoolService executionThreadPoolService = appContext.getBean(IExecutionThreadPoolService.class);
            AnswerItem resp = executionQueueService.readByKey(id);
            if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                /**
                 * Object could not be found. We stop here and report the
                 * error.
                 */
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
            } else {
                TestCaseExecutionQueue executionQueueData = (TestCaseExecutionQueue) resp.getItem();
                if (actionSave.equals("save")) {
                    /**
                     * The service was able to perform the query and confirm
                     * the object exist, then we can update it.
                     */
                    executionQueueData.setTest(ParameterParserUtil.parseStringParam(test, executionQueueData.getTest()));
                    executionQueueData.setTestCase(ParameterParserUtil.parseStringParam(testcase, executionQueueData.getTestCase()));
                    executionQueueData.setTag(ParameterParserUtil.parseStringParam(tag, executionQueueData.getTag()));
                    executionQueueData.setEnvironment(ParameterParserUtil.parseStringParam(environment, executionQueueData.getEnvironment()));
                    executionQueueData.setCountry(ParameterParserUtil.parseStringParam(country, executionQueueData.getCountry()));
                    executionQueueData.setManualURL(ParameterParserUtil.parseIntegerParam(manualURL, executionQueueData.getManualURL()));
                    executionQueueData.setManualHost(ParameterParserUtil.parseStringParam(manualHost, executionQueueData.getManualHost()));
                    executionQueueData.setManualContextRoot(ParameterParserUtil.parseStringParam(manualContextRoot, executionQueueData.getManualContextRoot()));
                    executionQueueData.setManualLoginRelativeURL(ParameterParserUtil.parseStringParam(manualLoginRelativeURL, executionQueueData.getManualLoginRelativeURL()));
                    executionQueueData.setManualEnvData(ParameterParserUtil.parseStringParam(manualEnvData, executionQueueData.getManualEnvData()));
                    executionQueueData.setRobot(ParameterParserUtil.parseStringParam(robot, executionQueueData.getRobot()));
                    executionQueueData.setRobotIP(ParameterParserUtil.parseStringParam(robotIP, executionQueueData.getRobotIP()));
                    executionQueueData.setRobotPort(ParameterParserUtil.parseStringParam(robotPort, executionQueueData.getRobotPort()));
                    executionQueueData.setBrowser(ParameterParserUtil.parseStringParam(browser, executionQueueData.getBrowser()));
                    executionQueueData.setBrowserVersion(ParameterParserUtil.parseStringParam(browserVersion, executionQueueData.getBrowserVersion()));
                    executionQueueData.setPlatform(ParameterParserUtil.parseStringParam(platform, executionQueueData.getPlatform()));
                    executionQueueData.setScreenSize(ParameterParserUtil.parseStringParam(screenSize, executionQueueData.getScreenSize()));
                    executionQueueData.setVerbose(ParameterParserUtil.parseIntegerParam(verbose, executionQueueData.getVerbose()));
                    executionQueueData.setScreenshot(screenshot);
                    executionQueueData.setPageSource(pageSource);
                    executionQueueData.setSeleniumLog(seleniumLog);
                    executionQueueData.setTimeout(timeout);
                    executionQueueData.setRetries(retries);
                    executionQueueData.setManualExecution(manualExecution);
                    executionQueueData.setDebugFlag(debugFlag);
                    executionQueueData.setPriority(priority);
                    executionQueueData.setUsrModif(request.getRemoteUser());
                    ans = executionQueueService.update(executionQueueData);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                        /**
                         * Update was successfull. Adding Log entry.
                         */
                        ILogEventService logEventService = appContext.getBean(LogEventService.class);
                        logEventService.createForPrivateCalls("/UpdateTestCaseExecutionQueue", "UPDATE", "Updated ExecutionQueue : ['" + id + "']", request);
                    }
                }
                // Update is done, we now check what action needs to be performed.
                if (actionState.equals("toQUEUED")) {
                    LOG.debug("toQUEUED");
                    ans = executionQueueService.updateToQueued(id, "Trigered by user " + request.getRemoteUser() + ".");
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    executionThreadPoolService.executeNextInQueueAsynchroneously(false);
                }
                // Priority Update.
                if (actionSave.equals("priority")) {
                    executionQueueData.setPriority(priority);
                    ans = executionQueueService.update(executionQueueData);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
                // Update is done, we now check what action needs to be performed.
                if (actionState.equals("toCANCELLED")) {
                    LOG.debug("toCANCELLED");
                    ans = executionQueueService.updateToCancelled(id, "Cancelled by user " + request.getRemoteUser() + ".");
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
                // Update is done, we now check what action needs to be performed.
                if (actionState.equals("toCANCELLEDForce")) {
                    LOG.debug("toCANCELLEDForce");
                    ans = executionQueueService.updateToCancelledForce(id, "Forced Cancelled by user " + request.getRemoteUser() + ".");
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
                // Update is done, we now check what action needs to be performed.
                if (actionState.equals("toERRORForce")) {
                    LOG.debug("toERRORForce");
                    ans = executionQueueService.updateToErrorForce(id, "Forced Eroor by user " + request.getRemoteUser() + ".");
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) ITagService(org.cerberus.crud.service.ITagService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService)

Example 84 with PolicyFactory

use of org.owasp.html.PolicyFactory in project cerberus-source by cerberustesting.

the class CreateInvariant 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();
    String id = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("idName"), "", charset);
    String value = request.getParameter("value");
    String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
    String veryShortDescField = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("veryShortDesc"), "", charset);
    String gp1 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp1"), "", charset);
    String gp2 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp2"), "", charset);
    String gp3 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp3"), "", charset);
    String gp4 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp4"), "", charset);
    String gp5 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp5"), "", charset);
    String gp6 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp6"), "", charset);
    String gp7 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp7"), "", charset);
    String gp8 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp8"), "", charset);
    String gp9 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp9"), "", charset);
    Integer sort = 10;
    boolean sort_error = false;
    try {
        if (request.getParameter("Sort") != null && !request.getParameter("Sort").equals("")) {
            sort = Integer.valueOf(policy.sanitize(request.getParameter("Sort")));
        }
    } catch (Exception ex) {
        sort_error = true;
    }
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(id)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Create").replace("%REASON%", "Invariant name is missing!"));
        ans.setResultMessage(msg);
    } else if (sort_error) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Create").replace("%REASON%", "Could not manage to convert sort to an integer value!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IInvariantService invariantService = appContext.getBean(IInvariantService.class);
        IFactoryInvariant factoryInvariant = appContext.getBean(IFactoryInvariant.class);
        Invariant invariantData = factoryInvariant.create(id, value, sort, description, veryShortDescField, gp1, gp2, gp3, gp4, gp5, gp6, gp7, gp8, gp9);
        if (invariantService.hasPermissionsCreate(invariantData, request)) {
            ans = invariantService.create(invariantData);
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Object updated. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/CreateInvariant2", "CREATE", "Create Invariant : ['" + id + "']", request);
            }
        } else {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Create").replace("%REASON%", "You are not allowed to do that or invariant is not public."));
            ans.setResultMessage(msg);
        }
    }
    /**
     * 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 : Invariant(org.cerberus.crud.entity.Invariant) IFactoryInvariant(org.cerberus.crud.factory.IFactoryInvariant) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) IInvariantService(org.cerberus.crud.service.IInvariantService) LogEventService(org.cerberus.crud.service.impl.LogEventService) ILogEventService(org.cerberus.crud.service.ILogEventService) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) JSONException(org.json.JSONException) IFactoryInvariant(org.cerberus.crud.factory.IFactoryInvariant) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) ILogEventService(org.cerberus.crud.service.ILogEventService)

Example 85 with PolicyFactory

use of org.owasp.html.PolicyFactory in project cerberus-source by cerberustesting.

the class UpdateTestCase 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 {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("test"), "");
    String testCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("testCase"), null);
    String keyTest = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTest"), "");
    String keyTestCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTestCase"), null);
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    /**
     * Checking all constrains before calling the services.
     */
    if ((StringUtil.isNullOrEmpty(test)) || (StringUtil.isNullOrEmpty(testCase)) || (StringUtil.isNullOrEmpty(keyTest)) || (StringUtil.isNullOrEmpty(keyTestCase))) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Case").replace("%OPERATION%", "Update").replace("%REASON%", "mandatory fields (test, testcase) are missing."));
        finalAnswer.setResultMessage(msg);
    } else {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        testCaseService = appContext.getBean(ITestCaseService.class);
        testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);
        testCaseLabelFactory = appContext.getBean(IFactoryTestCaseLabel.class);
        testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
        testCaseCountryFactory = appContext.getBean(IFactoryTestCaseCountry.class);
        AnswerItem resp = testCaseService.readByKey(keyTest, keyTestCase);
        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%", "TestCase").replace("%OPERATION%", "Update").replace("%REASON%", "TestCase does not exist."));
            finalAnswer.setResultMessage(msg);
        } else /**
         * The service was able to perform the query and confirm the object
         * exist, then we can update it.
         */
        {
            if (!testCaseService.hasPermissionsUpdate(tc, request)) {
                // 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%", "TestCase").replace("%OPERATION%", "Update").replace("%REASON%", "Not enought privilege to update the testcase. You must belong to Test Privilege or even TestAdmin in case the test is in WORKING status."));
                finalAnswer.setResultMessage(msg);
            } else {
                tc = getTestCaseFromRequest(request, tc);
                tc.setTestCaseVersion(tc.getTestCaseVersion() + 1);
                // Update testcase
                ans = testCaseService.update(keyTest, keyTestCase, tc);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Update was successful. Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/UpdateTestCase", "UPDATE", "Update testcase : ['" + keyTest + "'|'" + keyTestCase + "'] " + "version : " + tc.getTestCaseVersion(), request);
                    // Update labels
                    if (request.getParameter("labelList") != null) {
                        JSONArray objLabelArray = new JSONArray(request.getParameter("labelList"));
                        List<TestCaseLabel> labelList = new ArrayList();
                        labelList = getLabelListFromRequest(request, appContext, test, testCase, objLabelArray);
                        // Update the Database with the new list.
                        ans = testCaseLabelService.compareListAndUpdateInsertDeleteElements(tc.getTest(), tc.getTestCase(), labelList);
                        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    }
                    // Update Countries
                    if (request.getParameter("countryList") != null) {
                        JSONArray objCountryArray = new JSONArray(request.getParameter("countryList"));
                        List<TestCaseCountry> tccList = new ArrayList();
                        tccList = getCountryListFromRequest(request, appContext, test, testCase, objCountryArray);
                        // Update the Database with the new list.
                        ans = testCaseCountryService.compareListAndUpdateInsertDeleteElements(tc.getTest(), tc.getTestCase(), tccList);
                        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    }
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) AnswerItem(org.cerberus.util.answer.AnswerItem) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) 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) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) ITestCaseLabelService(org.cerberus.crud.service.ITestCaseLabelService) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel)

Aggregations

PolicyFactory (org.owasp.html.PolicyFactory)123 ApplicationContext (org.springframework.context.ApplicationContext)116 JSONObject (org.json.JSONObject)115 MessageEvent (org.cerberus.engine.entity.MessageEvent)93 AnswerItem (org.cerberus.util.answer.AnswerItem)74 JSONException (org.json.JSONException)70 ILogEventService (org.cerberus.crud.service.ILogEventService)62 Answer (org.cerberus.util.answer.Answer)60 CerberusException (org.cerberus.exception.CerberusException)35 IOException (java.io.IOException)32 ServletException (javax.servlet.ServletException)31 JSONArray (org.json.JSONArray)24 ITestCaseService (org.cerberus.crud.service.ITestCaseService)19 TestCase (org.cerberus.crud.entity.TestCase)17 ArrayList (java.util.ArrayList)14 LogEventService (org.cerberus.crud.service.impl.LogEventService)11 TestCaseStep (org.cerberus.crud.entity.TestCaseStep)10 IParameterService (org.cerberus.crud.service.IParameterService)9 TestCaseCountry (org.cerberus.crud.entity.TestCaseCountry)7 ICountryEnvParamService (org.cerberus.crud.service.ICountryEnvParamService)7