Search in sources :

Example 41 with CerberusException

use of org.cerberus.exception.CerberusException 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 42 with CerberusException

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

the class UpdateInvariant 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();
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    String id = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("idName"), "", charset);
    String value = request.getParameter("value");
    String oriId = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("originalIdName"), "", charset);
    String oriValue = request.getParameter("originalValue");
    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;
    }
    boolean userHasPermissions = request.isUserInRole("Administrator");
    // 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(id)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Update").replace("%REASON%", "Invariant name is missing!"));
        finalAnswer.setResultMessage(msg);
    } else if (sort_error) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert sort to an integer value!"));
        finalAnswer.setResultMessage(msg);
    } else if (!userHasPermissions) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Update").replace("%REASON%", "You don't have the right to do that"));
        finalAnswer.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);
        AnswerItem resp = invariantService.readByKey(oriId, oriValue);
        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 {
            Invariant invariantData = (Invariant) 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.
                 */
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
            } else {
                if (invariantService.hasPermissionsUpdate(invariantData, request)) {
                    invariantData.setIdName(id);
                    invariantData.setValue(value);
                    invariantData.setSort(sort);
                    invariantData.setDescription(description);
                    invariantData.setVeryShortDesc(veryShortDescField);
                    invariantData.setGp1(gp1);
                    invariantData.setGp2(gp2);
                    invariantData.setGp3(gp3);
                    invariantData.setGp4(gp4);
                    invariantData.setGp5(gp5);
                    invariantData.setGp6(gp6);
                    invariantData.setGp7(gp7);
                    invariantData.setGp8(gp8);
                    invariantData.setGp9(gp9);
                    ans = invariantService.update(oriId, oriValue, invariantData);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                        /**
                         * Object updated. Adding Log entry.
                         */
                        ILogEventService logEventService = appContext.getBean(LogEventService.class);
                        logEventService.createForPrivateCalls("/UpdateInvariant2", "UPDATE", "Update Invariant : ['" + id + "']", request);
                    }
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant").replace("%OPERATION%", "Update").replace("%REASON%", "The Invariant is not Public!"));
                    ans.setResultMessage(msg);
                    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 : Invariant(org.cerberus.crud.entity.Invariant) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) IInvariantService(org.cerberus.crud.service.IInvariantService) 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) ILogEventService(org.cerberus.crud.service.ILogEventService)

Example 43 with CerberusException

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

the class ChangeUserPassword method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String login = request.getParameter("login");
    String currentPassword = request.getParameter("currentPassword");
    String newPassword = request.getParameter("newPassword");
    String confirmPassword = request.getParameter("confirmPassword");
    String resetPasswordToken = request.getParameter("resetPasswordToken");
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);
    User myUser;
    try {
        JSONObject jsonResponse = new JSONObject();
        try {
            myUser = userService.findUserByKey(login);
            AnswerItem ansPassword = userService.updateUserPassword(myUser, currentPassword, newPassword, confirmPassword, resetPasswordToken);
            jsonResponse.put("messageType", ansPassword.getResultMessage().getMessage().getCodeString());
            jsonResponse.put("message", ansPassword.getResultMessage().getDescription());
        } catch (CerberusException ex1) {
            // TODO:FN this need to be refactored //findUserByKey should return answer
            jsonResponse.put("messageType", "KO");
            jsonResponse.put("message", ex1.toString());
        }
        response.setContentType("application/json");
        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.setContentType("application/json");
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) CerberusException(org.cerberus.exception.CerberusException) User(org.cerberus.crud.entity.User) JSONObject(org.json.JSONObject) IUserService(org.cerberus.crud.service.IUserService) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem)

Example 44 with CerberusException

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

the class ChangeUserPasswordAdmin method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String login = request.getParameter("login");
    String newPassword = request.getParameter("newPassword");
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);
    User myUser;
    try {
        JSONObject jsonResponse = new JSONObject();
        try {
            myUser = userService.findUserByKey(login);
            AnswerItem ansPassword = userService.updateUserPasswordAdmin(myUser, newPassword);
            jsonResponse.put("messageType", ansPassword.getResultMessage().getMessage().getCodeString());
            jsonResponse.put("message", ansPassword.getResultMessage().getDescription());
        } catch (CerberusException ex1) {
            // TODO:FN this need to be refactored //findUserByKey should return answer
            jsonResponse.put("messageType", "KO");
            jsonResponse.put("message", ex1.toString());
        }
        response.setContentType("application/json");
        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.setContentType("application/json");
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) CerberusException(org.cerberus.exception.CerberusException) User(org.cerberus.crud.entity.User) JSONObject(org.json.JSONObject) IUserService(org.cerberus.crud.service.IUserService) JSONException(org.json.JSONException) AnswerItem(org.cerberus.util.answer.AnswerItem)

Example 45 with CerberusException

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

the class ForgotPassword 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 {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IUserService userService = appContext.getBean(UserService.class);
        IEmailService emailService = appContext.getBean(IEmailService.class);
        IParameterService parameterService = appContext.getBean(ParameterService.class);
        String system = "";
        JSONObject jsonResponse = new JSONObject();
        String login = ParameterParserUtil.parseStringParam(request.getParameter("login"), "");
        /**
         * Check if notification parameter is set to Y. If not, return an
         * error
         */
        String sendNotification = parameterService.findParameterByKey("cerberus_notification_accountcreation_activatenotification", system).getValue();
        if (!sendNotification.equalsIgnoreCase("Y")) {
            jsonResponse.put("messageType", "Error");
            jsonResponse.put("message", "This functionality is not activated. Please contact your Cerberus Administrator.");
            response.getWriter().print(jsonResponse);
            response.getWriter().flush();
            return;
        }
        /**
         * If email not found in database, send error message
         */
        AnswerItem ai = userService.readByKey(login);
        User user = (User) ai.getItem();
        if (user == null) {
            jsonResponse.put("messageType", "Error");
            jsonResponse.put("message", "Login submitted is unknown !");
            response.getWriter().print(jsonResponse);
            response.getWriter().flush();
            return;
        }
        /**
         * Update user setting a new value in requestresetpassword
         */
        userService.requestResetPassword(user);
        /**
         * Send an email with the hash as a parameter
         */
        Answer mailSent = new Answer(emailService.generateAndSendForgotPasswordEmail(user));
        if (!mailSent.isCodeStringEquals("OK")) {
            jsonResponse.put("messageType", "Error");
            jsonResponse.put("message", "An error occured sending the notification. Detail : " + mailSent.getMessageDescription());
            response.getWriter().print(jsonResponse);
            response.getWriter().flush();
            return;
        }
        /**
         * Adding Log entry.
         */
        ILogEventService logEventService = appContext.getBean(ILogEventService.class);
        logEventService.createForPrivateCalls("/ForgotPassword", "CREATE", "User : " + login + " asked for password recovery", request);
        /**
         * Build Response Message
         */
        jsonResponse.put("messageType", "OK");
        jsonResponse.put("message", "An e-mail has been sent to the mailbox " + user.getEmail() + ".");
        response.getWriter().print(jsonResponse);
        response.getWriter().flush();
    } catch (CerberusException myexception) {
        response.getWriter().print(myexception.getMessageError().getDescription());
    } catch (JSONException ex) {
        LOG.warn(ex);
        response.setContentType("application/json");
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}
Also used : CerberusException(org.cerberus.exception.CerberusException) User(org.cerberus.crud.entity.User) JSONException(org.json.JSONException) IParameterService(org.cerberus.crud.service.IParameterService) AnswerItem(org.cerberus.util.answer.AnswerItem) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) IUserService(org.cerberus.crud.service.IUserService) ILogEventService(org.cerberus.crud.service.ILogEventService) IEmailService(org.cerberus.service.email.IEmailService) PrintWriter(java.io.PrintWriter)

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