Search in sources :

Example 61 with Answer

use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.

the class ExecuteNextInQueue method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONObject jsonResponse = new JSONObject();
    Answer answer = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    answer.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    boolean forceExecution = ParameterParserUtil.parseBooleanParamAndDecode(request.getParameter("forceExecution"), false, charset);
    if (forceExecution) {
        try {
            threadPoolService.executeNextInQueueAsynchroneously(true);
            response.setStatus(HttpStatus.OK.value());
        } catch (CerberusException e) {
            LOG.warn("Unable to execute next in queue", e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
    try {
        String jobRunning = myVersionService.getMyVersionStringByKey("queueprocessingjobrunning", "");
        jsonResponse.put("jobRunning", jobRunning);
        String jobStart = myVersionService.getMyVersionStringByKey("queueprocessingjobstart", "");
        jsonResponse.put("jobStart", jobStart);
        String jobActive = parameterService.getParameterStringByKey("cerberus_queueexecution_enable", "", "Y");
        jsonResponse.put("jobActive", jobActive);
        jsonResponse.put("jobActiveHasPermissionsUpdate", parameterService.hasPermissionsUpdate("cerberus_queueexecution_enable", request));
        jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", answer.getResultMessage().getDescription());
        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 : Answer(org.cerberus.util.answer.Answer) CerberusException(org.cerberus.exception.CerberusException) JSONObject(org.json.JSONObject) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) JSONException(org.json.JSONException)

Example 62 with Answer

use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.

the class UpdateUser method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IndexOutOfBoundsException {
    // TODO create class Validator to validate all parameter from page
    JSONObject jsonResponse = new JSONObject();
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer ans = new Answer();
    Answer finalAnswer = new Answer(msg1);
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    String id = request.getParameter("id");
    String login = request.getParameter("login");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String team = request.getParameter("team");
    String systems = request.getParameter("systems");
    String requests = request.getParameter("request");
    String groups = request.getParameter("groups");
    String defaultSystem = request.getParameter("defaultSystem");
    if (StringUtil.isNullOrEmpty(login) || StringUtil.isNullOrEmpty(id)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "User").replace("%OPERATION%", "Update").replace("%REASON%", "User login is missing."));
        ans.setResultMessage(msg);
    } else {
        LOG.info("Updating user " + login);
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IUserService userService = appContext.getBean(UserService.class);
        IUserGroupService userGroupService = appContext.getBean(UserGroupService.class);
        IFactoryUserSystem userSystemFactory = appContext.getBean(IFactoryUserSystem.class);
        IUserSystemService userSystemService = appContext.getBean(IUserSystemService.class);
        IFactoryUserGroup factoryGroup = new FactoryUserGroup();
        User myUser;
        List<UserGroup> newGroups = null;
        List<UserSystem> newSystems = null;
        try {
            myUser = userService.findUserByKey(id);
            List<String> listGroup = new ArrayList<String>();
            JSONArray GroupArray = new JSONArray(request.getParameter("groups"));
            for (int i = 0; i < GroupArray.length(); i++) {
                listGroup.add(GroupArray.getString(i));
            }
            newGroups = new ArrayList<UserGroup>();
            for (String group : listGroup) {
                newGroups.add(factoryGroup.create(group));
            }
            myUser.setLogin(login);
            myUser.setName(name);
            myUser.setTeam(team);
            newSystems = new ArrayList<UserSystem>();
            JSONArray SystemArray = new JSONArray(request.getParameter("systems"));
            List<String> listSystem = new ArrayList<String>();
            for (int i = 0; i < SystemArray.length(); i++) {
                listSystem.add(SystemArray.getString(i));
            }
            for (String system : listSystem) {
                newSystems.add(userSystemFactory.create(login, system));
            }
            myUser.setDefaultSystem(defaultSystem);
            myUser.setRequest(requests);
            myUser.setEmail(email);
            try {
                ans = userService.update(myUser);
                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("/UpdateUser", "UPDATE", "Updated user : " + login, request);
                    if (!newGroups.isEmpty()) {
                        userGroupService.updateUserGroups(myUser, newGroups);
                        /**
                         * Adding Log entry.
                         */
                        logEventService = appContext.getBean(LogEventService.class);
                        logEventService.createForPrivateCalls("/UpdateUser", "UPDATE", "Updated user groups : " + login, request);
                    }
                    if (!newSystems.isEmpty()) {
                        request.getSession().setAttribute("MySystem", newSystems.get(0).getSystem());
                        userSystemService.updateUserSystems(myUser, newSystems);
                        /**
                         * Adding Log entry.
                         */
                        logEventService = appContext.getBean(LogEventService.class);
                        logEventService.createForPrivateCalls("/UpdateUser", "UPDATE", "Updated user system : " + login, request);
                    }
                }
                /**
                 * Adding Log entry.
                 */
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
                jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
                response.getWriter().print(jsonResponse);
            } catch (CerberusException ex) {
                response.getWriter().print(ex.getMessageError().getDescription());
            }
        } catch (CerberusException ex) {
            response.getWriter().print(ex.getMessageError().getDescription());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Also used : User(org.cerberus.crud.entity.User) UserSystem(org.cerberus.crud.entity.UserSystem) IFactoryUserSystem(org.cerberus.crud.factory.IFactoryUserSystem) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) IUserGroupService(org.cerberus.crud.service.IUserGroupService) FactoryUserGroup(org.cerberus.crud.factory.impl.FactoryUserGroup) IFactoryUserGroup(org.cerberus.crud.factory.IFactoryUserGroup) UserGroup(org.cerberus.crud.entity.UserGroup) ApplicationContext(org.springframework.context.ApplicationContext) IFactoryUserSystem(org.cerberus.crud.factory.IFactoryUserSystem) ILogEventService(org.cerberus.crud.service.ILogEventService) IUserSystemService(org.cerberus.crud.service.IUserSystemService) CerberusException(org.cerberus.exception.CerberusException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) FactoryUserGroup(org.cerberus.crud.factory.impl.FactoryUserGroup) IFactoryUserGroup(org.cerberus.crud.factory.IFactoryUserGroup) Answer(org.cerberus.util.answer.Answer) JSONObject(org.json.JSONObject) IUserService(org.cerberus.crud.service.IUserService) IFactoryUserGroup(org.cerberus.crud.factory.IFactoryUserGroup)

Example 63 with Answer

use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.

the class DisableEnvironment 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();
    AnswerItem answerItem = new AnswerItem();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    answerItem.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    /**
     * Parsing and securing all required parameters.
     */
    String system = policy.sanitize(request.getParameter("system"));
    String country = policy.sanitize(request.getParameter("country"));
    String env = policy.sanitize(request.getParameter("environment"));
    // Init Answer with potencial error from Parsing parameter.
    // AnswerItem answer = new AnswerItem(msg);
    String eMailContent = "";
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IEmailService emailService = appContext.getBean(IEmailService.class);
    ICountryEnvParamService countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
    ICountryEnvParam_logService countryEnvParam_logService = appContext.getBean(ICountryEnvParam_logService.class);
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    if (request.getParameter("system") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "System name is missing!"));
        answerItem.setResultMessage(msg);
    } else if (request.getParameter("country") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Country is missing!"));
        answerItem.setResultMessage(msg);
    } else if (request.getParameter("environment") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Environment is missing!"));
        answerItem.setResultMessage(msg);
    } else {
        // All parameters are OK we can start performing the operation.
        // Getting the contryEnvParam based on the parameters.
        answerItem = countryEnvParamService.readByKey(system, country, env);
        if (!(answerItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && answerItem.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%", OPERATION).replace("%REASON%", OBJECT_NAME + " ['" + system + "','" + country + "','" + env + "'] does not exist. Cannot disable it!"));
            answerItem.setResultMessage(msg);
        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can update it.
             */
            CountryEnvParam cepData = (CountryEnvParam) answerItem.getItem();
            cepData.setActive(false);
            Answer answer = countryEnvParamService.update(cepData);
            if (!(answer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()))) {
                /**
                 * Object could not be updated. We stop here and report the
                 * error.
                 */
                answerItem.setResultMessage(answer.getResultMessage());
            } else {
                /**
                 * Update was successful.
                 */
                // Adding Log entry.
                logEventService.createForPrivateCalls("/DisableEnvironment", "UPDATE", "Updated CountryEnvParam : ['" + system + "','" + country + "','" + env + "']", request);
                // Adding CountryEnvParam Log entry.
                countryEnvParam_logService.createLogEntry(system, country, env, "", "", "Disabled.", request.getUserPrincipal().getName());
                /**
                 * Email notification.
                 */
                String OutputMessage = "";
                MessageEvent me = emailService.generateAndSendDisableEnvEmail(system, country, env);
                if (!"OK".equals(me.getMessage().getCodeString())) {
                    LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched." + me.getMessage().getDescription());
                    logEventService.createForPrivateCalls("/DisableEnvironment", "DISABLE", "Warning on Disable environment : ['" + system + "','" + country + "','" + env + "'] " + me.getMessage().getDescription(), request);
                    OutputMessage = me.getMessage().getDescription();
                }
                if (OutputMessage.equals("")) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", "Environment").replace("%OPERATION%", OPERATION));
                    answerItem.setResultMessage(msg);
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", "Environment").replace("%OPERATION%", OPERATION).concat(" Just one warning : ").concat(OutputMessage));
                    answerItem.setResultMessage(msg);
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", answerItem.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", answerItem.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : ICountryEnvParam_logService(org.cerberus.crud.service.ICountryEnvParam_logService) 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) ICountryEnvParamService(org.cerberus.crud.service.ICountryEnvParamService) AnswerItem(org.cerberus.util.answer.AnswerItem) IEmailService(org.cerberus.service.email.IEmailService) CountryEnvParam(org.cerberus.crud.entity.CountryEnvParam)

Example 64 with Answer

use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.

the class GetNotification 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, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer answer = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    answer.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    /**
     * Parsing and securing all required parameters.
     */
    String system = policy.sanitize(request.getParameter("system"));
    String country = policy.sanitize(request.getParameter("country"));
    String env = policy.sanitize(request.getParameter("environment"));
    String build = policy.sanitize(request.getParameter("build"));
    String revision = policy.sanitize(request.getParameter("revision"));
    String chain = policy.sanitize(request.getParameter("chain"));
    // Init Answer with potencial error from Parsing parameter.
    // AnswerItem answer = new AnswerItem(msg);
    String eMailContent = "";
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IEmailGenerationService emailService = appContext.getBean(IEmailGenerationService.class);
    if (request.getParameter("system") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get").replace("%REASON%", "System name is missing!"));
        answer.setResultMessage(msg);
    } else if (request.getParameter("event") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get").replace("%REASON%", "event is missing!"));
        answer.setResultMessage(msg);
    } else if (request.getParameter("event").equals("newbuildrevision")) {
        try {
            // ID parameter is specified so we return the unique record of object.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get"));
            answer.setResultMessage(msg);
            Email email = emailService.generateRevisionChangeEmail(system, country, env, build, revision);
            jsonResponse.put("notificationTo", email.getTo());
            jsonResponse.put("notificationCC", email.getCc());
            jsonResponse.put("notificationSubject", email.getSubject());
            jsonResponse.put("notificationBody", email.getBody());
        } catch (Exception ex) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get").replace("%REASON%", ex.toString()));
            answer.setResultMessage(msg);
        }
    } else if (request.getParameter("event").equals("disableenvironment")) {
        try {
            // ID parameter is specified so we return the unique record of object.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get"));
            answer.setResultMessage(msg);
            Email email = emailService.generateDisableEnvEmail(system, country, env);
            jsonResponse.put("notificationTo", email.getTo());
            jsonResponse.put("notificationCC", email.getCc());
            jsonResponse.put("notificationSubject", email.getSubject());
            jsonResponse.put("notificationBody", email.getBody());
        } catch (Exception ex) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get").replace("%REASON%", ex.toString()));
            answer.setResultMessage(msg);
        }
    } else if (request.getParameter("event").equals("newchain")) {
        try {
            // ID parameter is specified so we return the unique record of object.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get"));
            answer.setResultMessage(msg);
            Email email = emailService.generateNewChainEmail(system, country, env, chain);
            jsonResponse.put("notificationTo", email.getTo());
            jsonResponse.put("notificationCC", email.getCc());
            jsonResponse.put("notificationSubject", email.getSubject());
            jsonResponse.put("notificationBody", email.getBody());
        } catch (Exception ex) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get").replace("%REASON%", ex.toString()));
            answer.setResultMessage(msg);
        }
    } else {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "GetNotification").replace("%OPERATION%", "Get").replace("%REASON%", "Unknown invalidityReason!"));
        answer.setResultMessage(msg);
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", answer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) Email(org.cerberus.service.email.entity.Email) JSONObject(org.json.JSONObject) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) IEmailGenerationService(org.cerberus.service.email.IEmailGenerationService) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) JSONException(org.json.JSONException)

Example 65 with Answer

use of org.cerberus.util.answer.Answer in project cerberus-source by cerberustesting.

the class NewBuildRev 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();
    AnswerItem answerItem = new AnswerItem();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    answerItem.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    /**
     * Parsing and securing all required parameters.
     */
    String system = policy.sanitize(request.getParameter("system"));
    String country = policy.sanitize(request.getParameter("country"));
    String env = policy.sanitize(request.getParameter("environment"));
    String build = policy.sanitize(request.getParameter("build"));
    String revision = policy.sanitize(request.getParameter("revision"));
    // Init Answer with potencial error from Parsing parameter.
    // AnswerItem answer = new AnswerItem(msg);
    String eMailContent;
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IEmailService emailService = appContext.getBean(IEmailService.class);
    IEmailGenerationService emailGenerationService = appContext.getBean(IEmailGenerationService.class);
    IParameterService parameterService = appContext.getBean(IParameterService.class);
    ICountryEnvParamService countryEnvParamService = appContext.getBean(ICountryEnvParamService.class);
    ICountryEnvParam_logService countryEnvParam_logService = appContext.getBean(ICountryEnvParam_logService.class);
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    if (request.getParameter("system") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "System name is missing!"));
        answerItem.setResultMessage(msg);
    } else if (request.getParameter("country") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Country is missing!"));
        answerItem.setResultMessage(msg);
    } else if (request.getParameter("environment") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Environment is missing!"));
        answerItem.setResultMessage(msg);
    } else if (request.getParameter("build") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Build is missing!"));
        answerItem.setResultMessage(msg);
    } else if (request.getParameter("revision") == null) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", ITEM).replace("%OPERATION%", OPERATION).replace("%REASON%", "Revision is missing!"));
        answerItem.setResultMessage(msg);
    } else {
        // All parameters are OK we can start performing the operation.
        // Getting the contryEnvParam based on the parameters.
        answerItem = countryEnvParamService.readByKey(system, country, env);
        if (!(answerItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && answerItem.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%", OPERATION).replace("%REASON%", OBJECT_NAME + " ['" + system + "','" + country + "','" + env + "'] does not exist. Cannot activate it!"));
            answerItem.setResultMessage(msg);
        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can update it.
             */
            // Email Calculation. Email must be calcuated before we update the Build and revision in order to have the old build revision still available in the mail.
            String OutputMessage = "";
            Email email = null;
            try {
                email = emailGenerationService.generateRevisionChangeEmail(system, country, env, build, revision);
            } catch (Exception ex) {
                LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched.", ex);
                logEventService.createForPrivateCalls("/NewBuildRev", "NEWBUILDREV", "Warning on New Build/Revision environment : ['" + system + "','" + country + "','" + env + "'] " + ex.getMessage(), request);
                OutputMessage = ex.getMessage();
            }
            // We update the object.
            CountryEnvParam cepData = (CountryEnvParam) answerItem.getItem();
            cepData.setBuild(build);
            cepData.setRevision(revision);
            cepData.setActive(true);
            Answer answer = countryEnvParamService.update(cepData);
            if (!(answer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()))) {
                /**
                 * Object could not be updated. We stop here and report the
                 * error.
                 */
                answerItem.setResultMessage(answer.getResultMessage());
            } else {
                /**
                 * Update was successful.
                 */
                // Adding Log entry.
                logEventService.createForPrivateCalls("/NewBuildRev", "UPDATE", "Updated CountryEnvParam : ['" + system + "','" + country + "','" + env + "']", request);
                // Adding CountryEnvParam Log entry.
                countryEnvParam_logService.createLogEntry(system, country, env, build, revision, "New Build Revision.", request.getUserPrincipal().getName());
                /**
                 * Email notification.
                 */
                try {
                    emailService.sendHtmlMail(email);
                } catch (Exception e) {
                    LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched.", e);
                    logEventService.createForPrivateCalls("/NewBuildRev", "NEWBUILDREV", "Warning on New Build/Revision environment : ['" + system + "','" + country + "','" + env + "'] " + e.getMessage(), request);
                    OutputMessage = e.getMessage();
                }
                if (OutputMessage.equals("")) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", "Environment").replace("%OPERATION%", OPERATION));
                    answerItem.setResultMessage(msg);
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", "Environment").replace("%OPERATION%", OPERATION).concat(" Just one warning : ").concat(OutputMessage));
                    answerItem.setResultMessage(msg);
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", answerItem.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", answerItem.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : Email(org.cerberus.service.email.entity.Email) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) IParameterService(org.cerberus.crud.service.IParameterService) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) ICountryEnvParam_logService(org.cerberus.crud.service.ICountryEnvParam_logService) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) ILogEventService(org.cerberus.crud.service.ILogEventService) ICountryEnvParamService(org.cerberus.crud.service.ICountryEnvParamService) IEmailService(org.cerberus.service.email.IEmailService) CountryEnvParam(org.cerberus.crud.entity.CountryEnvParam) IEmailGenerationService(org.cerberus.service.email.IEmailGenerationService)

Aggregations

Answer (org.cerberus.util.answer.Answer)241 MessageEvent (org.cerberus.engine.entity.MessageEvent)227 Connection (java.sql.Connection)127 PreparedStatement (java.sql.PreparedStatement)127 SQLException (java.sql.SQLException)127 ApplicationContext (org.springframework.context.ApplicationContext)77 JSONObject (org.json.JSONObject)75 ILogEventService (org.cerberus.crud.service.ILogEventService)74 PolicyFactory (org.owasp.html.PolicyFactory)60 AnswerItem (org.cerberus.util.answer.AnswerItem)53 CerberusException (org.cerberus.exception.CerberusException)45 ArrayList (java.util.ArrayList)35 JSONException (org.json.JSONException)26 IOException (java.io.IOException)23 ServletException (javax.servlet.ServletException)19 JSONArray (org.json.JSONArray)15 LogEventService (org.cerberus.crud.service.impl.LogEventService)13 TestCase (org.cerberus.crud.entity.TestCase)10 ITestCaseService (org.cerberus.crud.service.ITestCaseService)10 CountryEnvParam (org.cerberus.crud.entity.CountryEnvParam)8