Search in sources :

Example 6 with Campaign

use of org.cerberus.crud.entity.Campaign in project cerberus-source by cerberustesting.

the class UpdateCampaign method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    Answer finalAnswer = new Answer(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");
    PrintWriter out = response.getWriter();
    String charset = request.getCharacterEncoding();
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    int cID = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("CampaignID"), 0, charset);
    String c = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("Campaign"), null, charset);
    String notifystart = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("NotifyStart"), null, charset);
    String notifyend = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("NotifyEnd"), null, charset);
    String desc = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("Description"), null, charset);
    // Parameter that we cannot secure as we need the html --> We DECODE them
    String distriblist = ParameterParserUtil.parseStringParam(request.getParameter("DistribList"), "");
    if (StringUtil.isNullOrEmpty(c)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Campaign").replace("%OPERATION%", "Update").replace("%REASON%", "Campaign name is missing!"));
        finalAnswer.setResultMessage(msg);
    } else {
        // Parameter that we cannot secure as we need the html --> We DECODE them
        // String battery = ParameterParserUtil.parseStringParam(request.getParameter("Batteries"), null);
        String parameter = ParameterParserUtil.parseStringParam(request.getParameter("Parameters"), null);
        String label = ParameterParserUtil.parseStringParam(request.getParameter("Labels"), null);
        ICampaignService campaignService = appContext.getBean(ICampaignService.class);
        AnswerItem resp = campaignService.readByKey(c);
        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 {
            Campaign camp = (Campaign) resp.getItem();
            camp.setDistribList(distriblist);
            camp.setNotifyStartTagExecution(notifystart);
            camp.setNotifyEndTagExecution(notifyend);
            camp.setDescription(desc);
            finalAnswer = campaignService.update(camp);
            if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/UpdateCampaign", "UPDATE", "Update Campaign : " + c, request);
            }
            if (parameter != null) {
                JSONArray parameters = new JSONArray(parameter);
                ICampaignParameterService campaignParameterService = appContext.getBean(ICampaignParameterService.class);
                IFactoryCampaignParameter factoryCampaignParameter = appContext.getBean(IFactoryCampaignParameter.class);
                ArrayList<CampaignParameter> arr = new ArrayList<>();
                for (int i = 0; i < parameters.length(); i++) {
                    JSONArray bat = parameters.getJSONArray(i);
                    CampaignParameter co = factoryCampaignParameter.create(0, bat.getString(0), bat.getString(2), bat.getString(3));
                    arr.add(co);
                }
                finalAnswer = campaignParameterService.compareListAndUpdateInsertDeleteElements(c, arr);
                if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/UpdateCampaign", "UPDATE", "Update Campaign Parameter : " + camp.getCampaign(), request);
                }
            }
            if (label != null) {
                JSONArray labels = new JSONArray(label);
                ICampaignLabelService campaignLabelService = appContext.getBean(ICampaignLabelService.class);
                IFactoryCampaignLabel factoryCampaignLabel = appContext.getBean(IFactoryCampaignLabel.class);
                ArrayList<CampaignLabel> arr = new ArrayList<>();
                for (int i = 0; i < labels.length(); i++) {
                    JSONArray bat = labels.getJSONArray(i);
                    CampaignLabel co = factoryCampaignLabel.create(0, bat.getString(0), Integer.valueOf(bat.getString(2)), request.getRemoteUser(), null, request.getRemoteUser(), null);
                    arr.add(co);
                }
                finalAnswer = campaignLabelService.compareListAndUpdateInsertDeleteElements(c, arr);
                if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/UpdateCampaign", "UPDATE", "Update Campaign Label : " + camp.getCampaign(), request);
                }
            }
        }
    }
    /**
     * 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 : IFactoryCampaignParameter(org.cerberus.crud.factory.IFactoryCampaignParameter) ICampaignService(org.cerberus.crud.service.ICampaignService) MessageEvent(org.cerberus.engine.entity.MessageEvent) ICampaignParameterService(org.cerberus.crud.service.ICampaignParameterService) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) AnswerItem(org.cerberus.util.answer.AnswerItem) IFactoryCampaignParameter(org.cerberus.crud.factory.IFactoryCampaignParameter) CampaignParameter(org.cerberus.crud.entity.CampaignParameter) Answer(org.cerberus.util.answer.Answer) IFactoryCampaignLabel(org.cerberus.crud.factory.IFactoryCampaignLabel) ApplicationContext(org.springframework.context.ApplicationContext) Campaign(org.cerberus.crud.entity.Campaign) JSONObject(org.json.JSONObject) ILogEventService(org.cerberus.crud.service.ILogEventService) ICampaignLabelService(org.cerberus.crud.service.ICampaignLabelService) IFactoryCampaignLabel(org.cerberus.crud.factory.IFactoryCampaignLabel) CampaignLabel(org.cerberus.crud.entity.CampaignLabel) PrintWriter(java.io.PrintWriter)

Example 7 with Campaign

use of org.cerberus.crud.entity.Campaign in project cerberus-source by cerberustesting.

the class DeleteCampaign 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
 */
final void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    Answer finalAnswer = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");
    String charset = request.getCharacterEncoding();
    // 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 key = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("key"), "", charset);
    if (StringUtil.isNullOrEmpty(key)) {
        /**
         * Missing key
         */
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Campaign").replace("%OPERATION%", "Delete").replace("%REASON%", "Campaign name is missing!"));
        finalAnswer.setResultMessage(msg);
    } else {
        ICampaignService campaignService = appContext.getBean(ICampaignService.class);
        AnswerItem resp = campaignService.readByKey(key);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) && resp.getItem() != null) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Campaign").replace("%OPERATION%", "Delete").replace("%REASON%", "Campaign can not be found"));
            finalAnswer.setResultMessage(msg);
        } else {
            Campaign camp = (Campaign) resp.getItem();
            finalAnswer = campaignService.delete(camp);
            if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteCampaign", "DELETE", "Delete Campaign : " + key, request);
            }
        }
    }
    /**
     * 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 : Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) ICampaignService(org.cerberus.crud.service.ICampaignService) Campaign(org.cerberus.crud.entity.Campaign) JSONObject(org.json.JSONObject) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) AnswerItem(org.cerberus.util.answer.AnswerItem)

Example 8 with Campaign

use of org.cerberus.crud.entity.Campaign in project cerberus-source by cerberustesting.

the class EmailService method generateAndSendNotifyStartTagExecution.

@Override
public MessageEvent generateAndSendNotifyStartTagExecution(String tag, String campaign) {
    try {
        Campaign myCampaign = campaignService.convert(campaignService.readByKey(campaign));
        if (!StringUtil.isNullOrEmpty(myCampaign.getDistribList()) && myCampaign.getNotifyStartTagExecution().equalsIgnoreCase("Y")) {
            Email email = null;
            email = emailGenerationService.generateNotifyStartTagExecution(tag, campaign, myCampaign.getDistribList());
            try {
            } catch (Exception ex) {
                LOG.warn("Exception generating email for Start Tag Execution :" + ex);
                return new MessageEvent(MessageEventEnum.GENERIC_ERROR).resolveDescription("REASON", ex.toString());
            }
            try {
                this.sendHtmlMail(email);
            } catch (Exception ex) {
                LOG.warn("Exception sending email for Start Tag Execution :" + ex);
                return new MessageEvent(MessageEventEnum.GENERIC_ERROR).resolveDescription("REASON", ex.toString());
            }
        }
    } catch (Exception ex) {
        LOG.warn("Exception generating email for Start Tag Execution :" + ex);
        return new MessageEvent(MessageEventEnum.GENERIC_ERROR).resolveDescription("REASON", ex.toString());
    }
    return new MessageEvent(MessageEventEnum.GENERIC_OK);
}
Also used : Campaign(org.cerberus.crud.entity.Campaign) HtmlEmail(org.apache.commons.mail.HtmlEmail) Email(org.cerberus.service.email.entity.Email) MessageEvent(org.cerberus.engine.entity.MessageEvent)

Example 9 with Campaign

use of org.cerberus.crud.entity.Campaign in project cerberus-source by cerberustesting.

the class ReadCampaign method findCampaignByKey.

private AnswerItem findCampaignByKey(String key, Boolean userHasPermissions, ApplicationContext appContext, HttpServletRequest request) throws JSONException {
    AnswerItem item = new AnswerItem();
    JSONObject object = new JSONObject();
    campaignService = appContext.getBean(ICampaignService.class);
    AnswerItem answer = campaignService.readByKey(key);
    Campaign p;
    if (answer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
        // the service was able to perform the query, then we should get all values
        p = (Campaign) answer.getItem();
        JSONObject response = convertCampaigntoJSONObject(p);
        if (request.getParameter("parameter") != null) {
            ICampaignParameterService campaignParameterService = appContext.getBean(ICampaignParameterService.class);
            AnswerList resp = campaignParameterService.readByCampaign(key);
            if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                // the service was able to perform the query, then we should get all values
                JSONArray a = new JSONArray();
                for (Object c : resp.getDataList()) {
                    CampaignParameter cc = (CampaignParameter) c;
                    a.put(convertCampaignParametertoJSONObject(cc));
                }
                response.put("parameter", a);
            }
        }
        if (request.getParameter("label") != null) {
            ICampaignLabelService campaignLabelService = appContext.getBean(ICampaignLabelService.class);
            AnswerList resp = campaignLabelService.readByVarious(key);
            if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                // the service was able to perform the query, then we should get all values
                JSONArray a = new JSONArray();
                for (Object c : resp.getDataList()) {
                    CampaignLabel cc = (CampaignLabel) c;
                    a.put(convertCampaignLabeltoJSONObject(cc));
                }
                response.put("label", a);
            }
        }
        if (request.getParameter("testcase") != null) {
            ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
            String[] campaignList = new String[1];
            campaignList[0] = key;
            AnswerItem<List<TestCase>> resp = testCaseService.findTestCaseByCampaignNameAndCountries(key, null);
            if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                // the service was able to perform the query, then we should get all values
                JSONArray a = new JSONArray();
                for (Object c : resp.getItem()) {
                    TestCase cc = (TestCase) c;
                    a.put(convertTestCasetoJSONObject(cc));
                }
                response.put("testcase", a);
            }
        }
        object.put("contentTable", response);
    }
    object.put("hasPermissions", userHasPermissions);
    item.setItem(object);
    item.setResultMessage(answer.getResultMessage());
    return item;
}
Also used : ICampaignService(org.cerberus.crud.service.ICampaignService) AnswerList(org.cerberus.util.answer.AnswerList) ICampaignParameterService(org.cerberus.crud.service.ICampaignParameterService) JSONArray(org.json.JSONArray) AnswerItem(org.cerberus.util.answer.AnswerItem) CampaignParameter(org.cerberus.crud.entity.CampaignParameter) Campaign(org.cerberus.crud.entity.Campaign) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) JSONObject(org.json.JSONObject) ICampaignLabelService(org.cerberus.crud.service.ICampaignLabelService) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) CampaignLabel(org.cerberus.crud.entity.CampaignLabel)

Example 10 with Campaign

use of org.cerberus.crud.entity.Campaign in project cerberus-source by cerberustesting.

the class CampaignDAO method readByCriteria.

@Override
public AnswerList readByCriteria(int start, int amount, String column, String dir, String searchTerm, Map<String, List<String>> individualSearch) {
    AnswerList response = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    List<Campaign> objectList = new ArrayList<Campaign>();
    StringBuilder searchSQL = new StringBuilder();
    List<String> individalColumnSearchValues = new ArrayList<String>();
    StringBuilder query = new StringBuilder();
    // SQL_CALC_FOUND_ROWS allows to retrieve the total number of columns by disrearding the limit clauses that
    // were applied -- used for pagination p
    query.append("SELECT SQL_CALC_FOUND_ROWS * FROM campaign cpg ");
    query.append(" WHERE 1=1");
    if (!StringUtil.isNullOrEmpty(searchTerm)) {
        searchSQL.append(" and (cpg.campaign like ?");
        searchSQL.append(" or cpg.distriblist like ?");
        searchSQL.append(" or cpg.description like ?)");
    }
    if (individualSearch != null && !individualSearch.isEmpty()) {
        searchSQL.append(" and ( 1=1 ");
        for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
            searchSQL.append(" and ");
            String q = SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue());
            if (q == null || "".equals(q)) {
                q = "(" + entry.getKey() + " IS NULL OR " + entry.getKey() + " = '')";
            }
            searchSQL.append(q);
            individalColumnSearchValues.addAll(entry.getValue());
        }
        searchSQL.append(" )");
    }
    query.append(searchSQL);
    if (!StringUtil.isNullOrEmpty(column)) {
        query.append(" order by ").append(column).append(" ").append(dir);
    }
    if ((amount <= 0) || (amount >= MAX_ROW_SELECTED)) {
        query.append(" limit ").append(start).append(" , ").append(MAX_ROW_SELECTED);
    } else {
        query.append(" limit ").append(start).append(" , ").append(amount);
    }
    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            int i = 1;
            if (!StringUtil.isNullOrEmpty(searchTerm)) {
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
                preStat.setString(i++, "%" + searchTerm + "%");
            }
            for (String individualColumnSearchValue : individalColumnSearchValues) {
                preStat.setString(i++, individualColumnSearchValue);
            }
            ResultSet resultSet = preStat.executeQuery();
            try {
                // gets the data
                while (resultSet.next()) {
                    objectList.add(this.loadFromResultSet(resultSet));
                }
                // get the total number of rows
                resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
                int nrTotalRows = 0;
                if (resultSet != null && resultSet.next()) {
                    nrTotalRows = resultSet.getInt(1);
                }
                if (objectList.size() >= MAX_ROW_SELECTED) {
                    // Result of SQl was limited by MAX_ROW_SELECTED constrain. That means that we may miss some lines in the resultList.
                    LOG.error("Partial Result in the query.");
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT);
                    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Maximum row reached : " + MAX_ROW_SELECTED));
                    response = new AnswerList(objectList, nrTotalRows);
                } else if (objectList.size() <= 0) {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND);
                    response = new AnswerList(objectList, nrTotalRows);
                } else {
                    msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                    msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                    response = new AnswerList(objectList, nrTotalRows);
                }
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
            } finally {
                if (resultSet != null) {
                    resultSet.close();
                }
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
        } finally {
            if (preStat != null) {
                preStat.close();
            }
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
    } finally {
        try {
            if (!this.databaseSpring.isOnTransaction()) {
                if (connection != null) {
                    connection.close();
                }
            }
        } catch (SQLException exception) {
            LOG.warn("Unable to close connection : " + exception.toString());
        }
    }
    response.setResultMessage(msg);
    response.setDataList(objectList);
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IFactoryCampaign(org.cerberus.crud.factory.IFactoryCampaign) Campaign(org.cerberus.crud.entity.Campaign) ResultSet(java.sql.ResultSet) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Aggregations

Campaign (org.cerberus.crud.entity.Campaign)11 MessageEvent (org.cerberus.engine.entity.MessageEvent)8 AnswerItem (org.cerberus.util.answer.AnswerItem)6 JSONObject (org.json.JSONObject)6 ArrayList (java.util.ArrayList)5 IFactoryCampaign (org.cerberus.crud.factory.IFactoryCampaign)5 ICampaignService (org.cerberus.crud.service.ICampaignService)5 JSONArray (org.json.JSONArray)4 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 SQLException (java.sql.SQLException)3 List (java.util.List)3 CampaignLabel (org.cerberus.crud.entity.CampaignLabel)3 CampaignParameter (org.cerberus.crud.entity.CampaignParameter)3 ICampaignLabelService (org.cerberus.crud.service.ICampaignLabelService)3 ICampaignParameterService (org.cerberus.crud.service.ICampaignParameterService)3 ILogEventService (org.cerberus.crud.service.ILogEventService)3 Answer (org.cerberus.util.answer.Answer)3 AnswerList (org.cerberus.util.answer.AnswerList)3