Search in sources :

Example 81 with AnswerList

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

the class FindInvariantByID 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 {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String idName = policy.sanitize(request.getParameter("idName"));
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    IInvariantService invariantService = appContext.getBean(InvariantService.class);
    JSONArray array = new JSONArray();
    // TODO: handle if the response does not turn ok
    AnswerList answer = invariantService.readByIdname(idName);
    for (Invariant myInvariant : (List<Invariant>) answer.getDataList()) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("value", myInvariant.getValue());
        jsonObject.put("description", myInvariant.getDescription());
        array.put(jsonObject);
    }
    response.getWriter().print(array.toString());
}
Also used : Invariant(org.cerberus.crud.entity.Invariant) ApplicationContext(org.springframework.context.ApplicationContext) AnswerList(org.cerberus.util.answer.AnswerList) PolicyFactory(org.owasp.html.PolicyFactory) JSONObject(org.json.JSONObject) IInvariantService(org.cerberus.crud.service.IInvariantService) JSONArray(org.json.JSONArray) AnswerList(org.cerberus.util.answer.AnswerList) List(java.util.List)

Example 82 with AnswerList

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

the class GetInvariantList method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String id = request.getParameter("idName");
    String idName = ParameterParserUtil.parseStringParam(id, "");
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    IInvariantService invariantService = appContext.getBean(InvariantService.class);
    JSONObject jsonResponse = new JSONObject();
    String action = request.getParameter("action");
    try {
        if (request.getParameter("action") != null) {
            // retrieve all the information in one client call
            if ("getNInvariant".equals(action)) {
                // gets a list of invariants
                JSONObject listOfInvariants = new JSONObject(idName);
                for (int i = 0; i < listOfInvariants.length(); i++) {
                    String invariantName = (String) listOfInvariants.get(String.valueOf(i));
                    JSONArray array = new JSONArray();
                    // TODO: handle if the response does not turn ok
                    AnswerList answer = invariantService.readByIdname(invariantName);
                    for (Invariant myInvariant : (List<Invariant>) answer.getDataList()) {
                        array.put(myInvariant.getValue());
                    }
                    jsonResponse.put(invariantName, array);
                }
            }
        } else {
            // gets one item
            // TODO: handle if the response does not turn ok
            AnswerList answer = invariantService.readByIdname(idName);
            for (Invariant myInvariant : (List<Invariant>) answer.getDataList()) {
                jsonResponse.put(myInvariant.getValue(), myInvariant.getValue());
            }
        }
        response.setContentType("application/json");
        response.getWriter().print(jsonResponse.toString());
    } catch (JSONException e) {
        LOG.warn(e);
        response.setContentType("text/html");
        response.getWriter().print(e.getMessage());
    }
}
Also used : Invariant(org.cerberus.crud.entity.Invariant) ApplicationContext(org.springframework.context.ApplicationContext) AnswerList(org.cerberus.util.answer.AnswerList) JSONObject(org.json.JSONObject) IInvariantService(org.cerberus.crud.service.IInvariantService) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) AnswerList(org.cerberus.util.answer.AnswerList) List(java.util.List)

Example 83 with AnswerList

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

the class ReadInvariant method findDistinctValuesOfColumn.

private AnswerItem findDistinctValuesOfColumn(ApplicationContext appContext, HttpServletRequest request, String columnName, String access) throws JSONException {
    AnswerItem answer = new AnswerItem();
    JSONObject object = new JSONObject();
    invariantService = appContext.getBean(IInvariantService.class);
    String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
    String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "idname,value,sort,description,VeryShortDesc, gp1,gp2,gp3");
    String[] columnToSort = sColumns.split(",");
    String column = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
    String sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_0"), "asc");
    List<String> individualLike = new ArrayList(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(",")));
    Map<String, List<String>> individualSearch = new HashMap<>();
    for (int a = 0; a < columnToSort.length; a++) {
        if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
            List<String> search = new ArrayList(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
            if (individualLike.contains(columnToSort[a])) {
                individualSearch.put(columnToSort[a] + ":like", search);
            } else {
                individualSearch.put(columnToSort[a], search);
            }
        }
    }
    AnswerList applicationList;
    if ("PUBLIC".equals(access)) {
        applicationList = invariantService.readDistinctValuesByPublicByCriteria(columnName, sort, searchParameter, individualSearch, column);
    } else {
        applicationList = invariantService.readDistinctValuesByPrivateByCriteria(columnName, sort, searchParameter, individualSearch, column);
    }
    object.put("distinctValues", applicationList.getDataList());
    answer.setItem(object);
    answer.setResultMessage(applicationList.getResultMessage());
    return answer;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) JSONObject(org.json.JSONObject) IInvariantService(org.cerberus.crud.service.IInvariantService) AnswerList(org.cerberus.util.answer.AnswerList) AnswerItem(org.cerberus.util.answer.AnswerItem)

Example 84 with AnswerList

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

the class AppServiceContentDAO method readDistinctValuesByCriteria.

@Override
public AnswerList<String> readDistinctValuesByCriteria(String system, String searchTerm, Map<String, List<String>> individualSearch, String columnName) {
    AnswerList answer = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    List<String> distinctValues = new ArrayList<>();
    StringBuilder searchSQL = new StringBuilder();
    List<String> individalColumnSearchValues = new ArrayList<String>();
    StringBuilder query = new StringBuilder();
    query.append("SELECT distinct ");
    query.append(columnName);
    query.append(" as distinctValues FROM appservicecontent ");
    searchSQL.append("WHERE 1=1");
    if (!StringUtil.isNullOrEmpty(system)) {
        searchSQL.append(" and (`System` = ? )");
    }
    if (!StringUtil.isNullOrEmpty(searchTerm)) {
        searchSQL.append(" and (src.`service` like ?");
        searchSQL.append(" or src.`key` like ?");
        searchSQL.append(" or src.`value` like ?");
        searchSQL.append(" or src.`sort` like ?");
        searchSQL.append(" or src.`active` like ?");
        searchSQL.append(" or src.`usrCreated` like ?");
        searchSQL.append(" or src.`usrModif` like ?");
        searchSQL.append(" or src.`dateCreated` like ?");
        searchSQL.append(" or src.`dateModif` like ?");
        searchSQL.append(" or src.`description` like ?)");
    }
    if (individualSearch != null && !individualSearch.isEmpty()) {
        searchSQL.append(" and ( 1=1 ");
        for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
            searchSQL.append(" and ");
            searchSQL.append(SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue()));
            individalColumnSearchValues.addAll(entry.getValue());
        }
        searchSQL.append(" )");
    }
    query.append(searchSQL);
    query.append(" order by ").append(columnName).append(" asc");
    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }
    try (Connection connection = databaseSpring.connect();
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        Statement stm = connection.createStatement()) {
        int i = 1;
        if (!StringUtil.isNullOrEmpty(system)) {
            preStat.setString(i++, system);
        }
        if (!StringUtil.isNullOrEmpty(searchTerm)) {
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
        }
        for (String individualColumnSearchValue : individalColumnSearchValues) {
            preStat.setString(i++, individualColumnSearchValue);
        }
        try (ResultSet resultSet = preStat.executeQuery();
            ResultSet rowSet = stm.executeQuery("SELECT FOUND_ROWS()")) {
            // gets the data
            while (resultSet.next()) {
                distinctValues.add(resultSet.getString("distinctValues") == null ? "" : resultSet.getString("distinctValues"));
            }
            int nrTotalRows = 0;
            if (rowSet != null && rowSet.next()) {
                nrTotalRows = rowSet.getInt(1);
            }
            if (distinctValues.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));
                answer = new AnswerList(distinctValues, nrTotalRows);
            } else if (distinctValues.size() <= 0) {
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND);
                answer = new AnswerList(distinctValues, nrTotalRows);
            } else {
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                answer = new AnswerList(distinctValues, nrTotalRows);
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    } catch (Exception e) {
        LOG.warn("Unable to execute query : " + e.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED).resolveDescription("DESCRIPTION", e.toString());
    } finally {
        // We always set the result message
        answer.setResultMessage(msg);
    }
    answer.setResultMessage(msg);
    answer.setDataList(distinctValues);
    return answer;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) AnswerList(org.cerberus.util.answer.AnswerList) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Example 85 with AnswerList

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

the class AppServiceDAO method findAppServiceByLikeName.

@Override
public AnswerList findAppServiceByLikeName(String service, int limit) {
    AnswerList response = new AnswerList();
    boolean throwEx = false;
    AppService result = null;
    final String query = "SELECT * FROM appservice srv WHERE `service` LIKE ? limit ?";
    List<AppService> objectList = new ArrayList<AppService>();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query);
        try {
            preStat.setString(1, "%" + service + "%");
            preStat.setInt(2, limit);
            ResultSet resultSet = preStat.executeQuery();
            try {
                while (resultSet.next()) {
                    objectList.add(this.loadFromResultSet(resultSet));
                }
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
                msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
                resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
                int nrTotalRows = 0;
                if (resultSet != null && resultSet.next()) {
                    nrTotalRows = resultSet.getInt(1);
                }
                response = new AnswerList(objectList, nrTotalRows);
            } catch (SQLException exception) {
                LOG.warn("Unable to execute query : " + exception.toString());
            } finally {
                resultSet.close();
            }
        } catch (SQLException exception) {
            LOG.warn("Unable to execute query : " + exception.toString());
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.warn("Unable to execute query : " + exception.toString());
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn("Exception closing connection : " + e.toString());
        }
    }
    response.setResultMessage(msg);
    response.setDataList(objectList);
    return response;
}
Also used : AnswerList(org.cerberus.util.answer.AnswerList) IFactoryAppService(org.cerberus.crud.factory.IFactoryAppService) AppService(org.cerberus.crud.entity.AppService) FactoryAppService(org.cerberus.crud.factory.impl.FactoryAppService) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

AnswerList (org.cerberus.util.answer.AnswerList)258 ArrayList (java.util.ArrayList)197 MessageEvent (org.cerberus.engine.entity.MessageEvent)152 List (java.util.List)146 Connection (java.sql.Connection)120 PreparedStatement (java.sql.PreparedStatement)120 ResultSet (java.sql.ResultSet)120 SQLException (java.sql.SQLException)120 JSONObject (org.json.JSONObject)90 AnswerItem (org.cerberus.util.answer.AnswerItem)89 Map (java.util.Map)69 HashMap (java.util.HashMap)65 JSONArray (org.json.JSONArray)62 Statement (java.sql.Statement)35 CerberusException (org.cerberus.exception.CerberusException)20 Invariant (org.cerberus.crud.entity.Invariant)18 IInvariantService (org.cerberus.crud.service.IInvariantService)15 TestCase (org.cerberus.crud.entity.TestCase)14 LinkedHashMap (java.util.LinkedHashMap)11 TestCaseExecution (org.cerberus.crud.entity.TestCaseExecution)11