Search in sources :

Example 76 with CerberusException

use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.

the class ExportTestCase method processRequest.

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

Example 77 with CerberusException

use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.

the class ReadApplicationObject 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%", ""));
    // Get Parameters
    String columnName = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
    /**
     * Parsing and securing all required parameters.
     */
    // Nothing to do here as no parameter to check.
    // 
    // Global boolean on the servlet that define if the user has permition to edit and delete object.
    boolean userHasPermissions = request.isUserInRole("Integrator");
    // Init Answer with potencial error from Parsing parameter.
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    try {
        JSONObject jsonResponse = new JSONObject();
        if (request.getParameter("application") != null && request.getParameter("object") != null) {
            answer = findApplicationObject(request.getParameter("application"), request.getParameter("object"), appContext, userHasPermissions, request);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (request.getParameter("id") != null) {
            int id = -1;
            boolean int_error = false;
            try {
                id = Integer.getInteger(request.getParameter("id"));
            } catch (Exception e) {
                int_error = true;
            }
            if (!int_error) {
                answer = findApplicationObject(id, appContext, userHasPermissions, request);
                jsonResponse = (JSONObject) answer.getItem();
            }
        } else if (request.getParameter("columnName") != null) {
            answer = findValuesForColumnFilter(appContext, request);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (request.getParameter("application") == null) {
            answer = findApplicationObjectList(null, appContext, userHasPermissions, request);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (request.getParameter("iDisplayStart") == null) {
            answer = findApplicationObjectList(request.getParameter("application"), appContext, userHasPermissions);
            jsonResponse = (JSONObject) answer.getItem();
        } else {
            answer = findApplicationObjectList(request.getParameter("application"), appContext, userHasPermissions, 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 78 with CerberusException

use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.

the class DeleteBuildRevisionParameters 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);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    Integer brpid = 0;
    String[] myId = request.getParameterValues("id");
    StringBuilder output_message = new StringBuilder();
    MessageEvent final_msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    int massErrorCounter = 0;
    for (String myId1 : myId) {
        /**
         * Parsing and securing all required parameters.
         */
        brpid = 0;
        boolean brpid_error = true;
        try {
            if (myId1 != null && !myId1.equals("")) {
                brpid = Integer.valueOf(policy.sanitize(myId1));
                brpid_error = false;
            }
        } catch (Exception ex) {
            brpid_error = true;
        }
        /**
         * Checking all constrains before calling the services.
         */
        if (brpid_error) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Delete").replace("%REASON%", "BuildRevisionParameters ID (id) : Could not manage to convert id to an integer value or id is missing."));
            ans.setResultMessage(msg);
            massErrorCounter++;
            output_message.append("<br>id : ").append(myId1).append(" - ").append(msg.getDescription());
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            IBuildRevisionParametersService brpService = appContext.getBean(IBuildRevisionParametersService.class);
            AnswerItem resp = brpService.readByKeyTech(brpid);
            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%", "Delete").replace("%REASON%", "BuildRevisionParameter does not exist."));
                ans.setResultMessage(msg);
                massErrorCounter++;
                output_message.append("<br>id : ").append(myId1).append(" - ").append(msg.getDescription());
            } else {
                /**
                 * The service was able to perform the query and confirm the
                 * object exist, then we can delete it.
                 */
                BuildRevisionParameters brpData = (BuildRevisionParameters) resp.getItem();
                ans = brpService.delete(brpData);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Delete was successful. Adding Log entry.
                     */
                    logEventService.createForPrivateCalls("/DeleteBuildRevisionParameters", "DELETE", "Delete BuildRevisionParameters : ['" + brpid + "'|'" + brpData.getRelease() + "']", request);
                } else {
                    massErrorCounter++;
                    output_message.append("<br>id : ").append(myId1).append(" - ").append(ans.getResultMessage().getDescription());
                }
            }
        }
    }
    if (myId.length > 1) {
        if (massErrorCounter == myId.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 + " objects(s) out of " + myId.length + " failed to update 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 + " objects(s) out of " + myId.length + " failed to update 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 " + myId.length + " object(s) updated successfuly.");
            ans.setResultMessage(msg);
        }
        logEventService.createForPrivateCalls("/DeleteBuildRevisionParameters", "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.toString());
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) IBuildRevisionParametersService(org.cerberus.crud.service.IBuildRevisionParametersService) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) JSONException(org.json.JSONException) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) BuildRevisionParameters(org.cerberus.crud.entity.BuildRevisionParameters) ILogEventService(org.cerberus.crud.service.ILogEventService)

Example 79 with CerberusException

use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.

the class ReadBuildRevisionParameters method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.cerberus.exception.CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException {
    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%", ""));
    /**
     * Parsing and securing all required parameters.
     */
    Integer brpid = 0;
    boolean brpid_error = true;
    try {
        if (request.getParameter("id") != null && !request.getParameter("id").equals("")) {
            brpid = Integer.valueOf(policy.sanitize(request.getParameter("id")));
            brpid_error = false;
        }
    } catch (Exception ex) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME));
        msg.setDescription(msg.getDescription().replace("%OPERATION%", "Read"));
        msg.setDescription(msg.getDescription().replace("%REASON%", "id must be an integer value."));
        brpid_error = true;
    }
    String columnName = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
    // Global boolean on the servlet that define if the user has permition to edit and delete object.
    boolean userHasPermissions = request.isUserInRole("Integrator");
    // Init Answer with potencial error from Parsing parameter.
    AnswerItem answer = new AnswerItem(msg);
    try {
        JSONObject jsonResponse = new JSONObject();
        if ((request.getParameter("id") != null) && !(brpid_error)) {
            // ID parameter is specified so we return the unique record of object.
            answer = findBuildRevisionParametersByKey(brpid, appContext, userHasPermissions);
            jsonResponse = (JSONObject) answer.getItem();
        } else if ((request.getParameter("system") != null) && (request.getParameter("getlast") != null)) {
            // getlast parameter trigger the last release from the system..
            answer = findlastBuildRevisionParametersBySystem(request.getParameter("system"), appContext, userHasPermissions);
            jsonResponse = (JSONObject) answer.getItem();
        } else if ((request.getParameter("system") != null) && (request.getParameter("build") != null) && (request.getParameter("revision") != null) && (request.getParameter("getSVNRelease") != null)) {
            // getSVNRelease parameter trigger the list of SVN Release inside he build per Application.
            answer = findSVNBuildRevisionParametersBySystem(request.getParameter("system"), request.getParameter("country"), request.getParameter("environment"), request.getParameter("build"), request.getParameter("revision"), request.getParameter("lastbuild"), request.getParameter("lastrevision"), appContext, userHasPermissions);
            jsonResponse = (JSONObject) answer.getItem();
        } else if ((request.getParameter("system") != null) && (request.getParameter("build") != null) && (request.getParameter("revision") != null) && (request.getParameter("getNonSVNRelease") != null)) {
            // getNonSVNRelease parameter trigger the list of Manual Release with corresponding links.
            answer = findManualBuildRevisionParametersBySystem(request.getParameter("system"), request.getParameter("build"), request.getParameter("revision"), request.getParameter("lastbuild"), request.getParameter("lastrevision"), appContext, userHasPermissions);
            jsonResponse = (JSONObject) answer.getItem();
        } else if ((request.getParameter("system") != null) && !Strings.isNullOrEmpty(columnName)) {
            answer = findDistinctValuesOfColumn(request.getParameter("system"), appContext, request, columnName);
            jsonResponse = (JSONObject) answer.getItem();
        } else {
            // Default behaviour, we return the list of objects.
            answer = findBuildRevisionParametersList(request.getParameter("system"), request.getParameter("build"), request.getParameter("revision"), request.getParameter("application"), appContext, userHasPermissions, 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 80 with CerberusException

use of org.cerberus.exception.CerberusException in project cerberus-source by cerberustesting.

the class UpdateBuildRevisionParameters 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
    String build = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("build"), "", charset);
    String revision = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("revision"), "", charset);
    String release = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("release"), "", charset);
    // Parameter that we cannot secure as we need the html --> We DECODE them
    Integer brpid = 0;
    String[] myId = request.getParameterValues("id");
    StringBuilder output_message = new StringBuilder();
    int massErrorCounter = 0;
    for (String myId1 : myId) {
        brpid = 0;
        boolean brpid_error = true;
        try {
            if (myId1 != null && !myId1.equals("")) {
                brpid = Integer.valueOf(policy.sanitize(myId1));
                brpid_error = false;
            }
        } catch (Exception ex) {
            brpid_error = true;
        }
        /**
         * Checking all constrains before calling the services.
         */
        if (brpid_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 id to an integer value or id is missing."));
            ans.setResultMessage(msg);
            massErrorCounter++;
            output_message.append("<br>id : ").append(myId1).append(" - ").append(msg.getDescription());
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            IBuildRevisionParametersService brpService = appContext.getBean(IBuildRevisionParametersService.class);
            AnswerItem resp = brpService.readByKeyTech(brpid);
            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%", "Update").replace("%REASON%", "BuildRevisionParameters does not exist."));
                ans.setResultMessage(msg);
                massErrorCounter++;
                output_message.append("<br>id : ").append(myId1).append(" - ").append(msg.getDescription());
            } else {
                /**
                 * The service was able to perform the query and confirm the
                 * object exist, then we can update it.
                 */
                BuildRevisionParameters brpData = (BuildRevisionParameters) resp.getItem();
                /**
                 * Before updating, we check that the old entry can be
                 * modified. If old entry point to a build/revision that
                 * already been deployed, we cannot update it.
                 */
                if (brpService.check_buildRevisionAlreadyUsed(brpData.getApplication(), brpData.getBuild(), brpData.getRevision())) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Update").replace("%REASON%", "Could not update this release as its original build " + brpData.getBuild() + " revision " + brpData.getRevision() + " has already been deployed in an environment."));
                    ans.setResultMessage(msg);
                    massErrorCounter++;
                    output_message.append("<br>id : ").append(myId1).append(" - ").append(msg.getDescription());
                } else {
                    brpData.setBuild(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("build"), brpData.getBuild(), charset));
                    brpData.setRevision(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("revision"), brpData.getRevision(), charset));
                    brpData.setRelease(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("release"), brpData.getRelease(), charset));
                    brpData.setApplication(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), brpData.getApplication(), charset));
                    brpData.setProject(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("project"), brpData.getProject(), charset));
                    brpData.setTicketIdFixed(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("ticketidfixed"), brpData.getTicketIdFixed(), charset));
                    brpData.setBugIdFixed(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("bugidfixed"), brpData.getBugIdFixed(), charset));
                    brpData.setLink(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("link"), brpData.getLink(), charset));
                    brpData.setReleaseOwner(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("releaseowner"), brpData.getReleaseOwner(), charset));
                    brpData.setSubject(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("subject"), brpData.getSubject(), charset));
                    brpData.setJenkinsBuildId(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("jenkinsbuildid"), brpData.getJenkinsBuildId(), charset));
                    brpData.setMavenGroupId(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavengroupid"), brpData.getMavenGroupId(), charset));
                    brpData.setMavenArtifactId(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavenartifactid"), brpData.getMavenArtifactId(), charset));
                    brpData.setMavenVersion(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavenversion"), brpData.getMavenVersion(), charset));
                    brpData.setRepositoryUrl(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("repositoryurl"), brpData.getRepositoryUrl(), charset));
                    ans = brpService.update(brpData);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                        /**
                         * Update was successful. Adding Log entry.
                         */
                        logEventService.createForPrivateCalls("/UpdateBuildRevisionParameters", "UPDATE", "Updated BuildRevisionParameters : ['" + brpid + "'|'" + build + "'|'" + revision + "'|'" + release + "']", request);
                    } else {
                        massErrorCounter++;
                        output_message.append("<br>id : ").append(myId1).append(" - ").append(ans.getResultMessage().getDescription());
                    }
                }
            }
        }
    }
    if (myId.length > 1) {
        if (massErrorCounter == myId.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 + " objects(s) out of " + myId.length + " failed to update 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 + " objects(s) out of " + myId.length + " failed to update 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 " + myId.length + " object(s) updated successfuly.");
            ans.setResultMessage(msg);
        }
        logEventService.createForPrivateCalls("/UpdateBuildRevisionParameters", "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) IBuildRevisionParametersService(org.cerberus.crud.service.IBuildRevisionParametersService) 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) BuildRevisionParameters(org.cerberus.crud.entity.BuildRevisionParameters) ILogEventService(org.cerberus.crud.service.ILogEventService)

Aggregations

CerberusException (org.cerberus.exception.CerberusException)159 MessageEvent (org.cerberus.engine.entity.MessageEvent)64 MessageGeneral (org.cerberus.engine.entity.MessageGeneral)58 ApplicationContext (org.springframework.context.ApplicationContext)58 JSONObject (org.json.JSONObject)54 JSONException (org.json.JSONException)53 Connection (java.sql.Connection)48 SQLException (java.sql.SQLException)48 PreparedStatement (java.sql.PreparedStatement)47 AnswerItem (org.cerberus.util.answer.AnswerItem)41 ArrayList (java.util.ArrayList)37 IOException (java.io.IOException)35 PolicyFactory (org.owasp.html.PolicyFactory)35 ILogEventService (org.cerberus.crud.service.ILogEventService)34 Answer (org.cerberus.util.answer.Answer)34 ServletException (javax.servlet.ServletException)26 ResultSet (java.sql.ResultSet)18 TestCase (org.cerberus.crud.entity.TestCase)16 JSONArray (org.json.JSONArray)16 HashMap (java.util.HashMap)12