Search in sources :

Example 1 with DatabaseSpring

use of org.cerberus.database.DatabaseSpring in project cerberus-source by cerberustesting.

the class NewRelease 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 {
    PrintWriter out = response.getWriter();
    String charset = request.getCharacterEncoding();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    logEventService.createForPublicCalls("/NewRelease", "CALL", "NewRelease called : " + request.getRequestURL(), request);
    IApplicationService MyApplicationService = appContext.getBean(ApplicationService.class);
    IUserService MyUserService = appContext.getBean(UserService.class);
    IProjectService MyProjectService = appContext.getBean(ProjectService.class);
    IBuildRevisionParametersService buildRevisionParametersService = appContext.getBean(IBuildRevisionParametersService.class);
    IFactoryBuildRevisionParameters factoryBuildRevisionParameters = appContext.getBean(IFactoryBuildRevisionParameters.class);
    // Parsing all parameters.
    String application = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), "", charset);
    String release = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("release"), "", charset);
    String project = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("project"), "", charset);
    String ticket = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("ticket"), "", charset);
    String bug = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("bug"), "", charset);
    String subject = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("subject"), "", charset);
    String owner = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("owner"), "", charset);
    String link = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("link"), "", charset);
    // Those Parameters could be used later when Cerberus send the deploy request to Jenkins.
    String jenkinsbuildid = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("jenkinsbuildid"), "", charset);
    String mavengroupid = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavengroupid"), "", charset);
    String mavenartifactid = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavenartifactid"), "", charset);
    String mavenversion = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("mavenversion"), "", charset);
    String repositoryurl = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("repositoryurl"), "", charset);
    String helpMessage = "\nThis servlet is used to create or update a release entry in a 'NONE' build and 'NONE' revision.\n\nParameter list :\n" + "- application [mandatory] : the application that produced the release. This parameter must match the application list in Cerberus. [" + application + "]\n" + "- release : release number or svn number. This should be unique at the application level. 2 calls on the same application and release will update the other parameters on the same entry. [" + release + "]\n" + "- project : Project reference. [" + project + "]\n" + "- ticket : Ticket Reference. [" + ticket + "]\n" + "- bug : Bug reference. [" + bug + "]\n" + "- subject : A short description of the change. [" + subject + "]\n" + "- owner : User name of the developper/ person who did the commit. [" + owner + "]\n" + "- link : URL Link on detail documentation on the release. [" + link + "]\n\n" + "The following optional parameters could be used later when Cerberus send the deploy request to Jenkins.\n" + "- jenkinsbuildid : Jenkins Build ID. [" + jenkinsbuildid + "]\n" + "- mavengroupid : Maven Group ID. [" + mavengroupid + "]\n" + "- mavenartifactid : Maven Artifact ID. [" + mavenartifactid + "]\n" + "- repositoryurl : Repository URL. [" + repositoryurl + "]\n" + "- mavenversion : Maven Version. [" + mavenversion + "]\n";
    DatabaseSpring database = appContext.getBean(DatabaseSpring.class);
    Connection connection = database.connect();
    try {
        boolean error = false;
        // Checking the parameter validity. If application has been entered, does it exist ?
        if (!application.equalsIgnoreCase("") && !MyApplicationService.exist(application)) {
            out.println("Error - Application does not exist  : " + application);
            error = true;
        }
        if (application.equalsIgnoreCase("")) {
            out.println("Error - Parameter application is mandatory.");
            error = true;
        }
        // Checking the parameter validity. If owner has been entered, does it exist ?
        if (!owner.equalsIgnoreCase("")) {
            if (MyUserService.isUserExist(owner)) {
                // We get the exact name from Cerberus.
                owner = MyUserService.findUserByKey(owner).getLogin();
            } else {
                out.println("Warning - User does not exist : " + owner);
            }
        }
        // Checking the parameter validity. If project has been entered, does it exist ?
        if (!project.equalsIgnoreCase("") && !MyProjectService.exist(project)) {
            out.println("Warning - Project does not exist : " + project);
        }
        // Starting the database update only when no blocking error has been detected.
        if (error == false) {
            // In case the bugID is not defined, we try to guess it from the subject. should be between # and a space or CR.
            if (StringUtil.isNullOrEmpty(bug)) {
                String[] columns = subject.split("#");
                if (columns.length >= 2) {
                    for (int i = 1; i < columns.length; i++) {
                        String[] columnsbis = columns[i].split(" ");
                        if (columnsbis.length >= 1) {
                            if (!columnsbis[0].contains(";")) {
                                // Bug number should not include ;
                                bug = columnsbis[0];
                            }
                        }
                    }
                }
            }
            // Transaction and database update.
            // Duplicate entry Verification. On the build/relivion not yet assigned (NONE/NONE),
            // we verify that the application + release has not been submitted yet.
            // if it exist, we update it in stead of inserting a new row.
            // That correspond in the cases where the Jenkins pipe is executed several times
            // on a single svn commit.
            /**
             * Verify if the entry already exists if already exists, update
             * it else create it
             */
            AnswerItem answer = buildRevisionParametersService.readByVarious2("NONE", "NONE", release, application);
            BuildRevisionParameters buildRevisionParameters = (BuildRevisionParameters) answer.getItem();
            if (answer.getResultMessage().getCode() == new MessageEvent(MessageEventEnum.DATA_OPERATION_OK).getCode() && buildRevisionParameters != null) {
                out.println("Warning - Release entry already exist. Updating the existing entry : " + buildRevisionParameters.getId());
                if (!project.isEmpty()) {
                    buildRevisionParameters.setProject(project);
                }
                if (!ticket.isEmpty()) {
                    buildRevisionParameters.setTicketIdFixed(ticket);
                }
                if (!bug.isEmpty()) {
                    buildRevisionParameters.setBugIdFixed(bug);
                }
                if (!subject.isEmpty()) {
                    buildRevisionParameters.setSubject(subject);
                }
                if (!owner.isEmpty()) {
                    buildRevisionParameters.setReleaseOwner(owner);
                }
                if (!link.isEmpty()) {
                    buildRevisionParameters.setLink(link);
                }
                if (!jenkinsbuildid.isEmpty()) {
                    buildRevisionParameters.setJenkinsBuildId(jenkinsbuildid);
                }
                if (!mavengroupid.isEmpty()) {
                    buildRevisionParameters.setMavenGroupId(mavengroupid);
                }
                if (!mavenartifactid.isEmpty()) {
                    buildRevisionParameters.setMavenArtifactId(mavenartifactid);
                }
                if (!mavenversion.isEmpty()) {
                    buildRevisionParameters.setMavenVersion(mavenversion);
                }
                if (!repositoryurl.isEmpty()) {
                    buildRevisionParameters.setRepositoryUrl(repositoryurl);
                }
                buildRevisionParametersService.update(buildRevisionParameters);
            } else if (answer.getResultMessage().getCode() == new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND).getCode()) {
                buildRevisionParametersService.create(factoryBuildRevisionParameters.create(0, "NONE", "NONE", release, application, project, ticket, bug, link, owner, subject, null, jenkinsbuildid, mavengroupid, mavenartifactid, mavenversion, repositoryurl));
                out.println("Release Inserted : '" + release + "' on '" + application + "' for user '" + owner + "'");
            } else {
                out.println("A problem occured : '" + answer.getResultMessage().getDescription());
            }
        } else {
            // In case of errors, we display the help message.
            out.println(helpMessage);
        }
    } catch (Exception e) {
        LOG.warn(Infos.getInstance().getProjectNameAndVersion() + " - Exception catched.", e);
        out.print("Error while inserting the release : ");
        out.println(e.toString());
    } finally {
        out.close();
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
}
Also used : IProjectService(org.cerberus.crud.service.IProjectService) IFactoryBuildRevisionParameters(org.cerberus.crud.factory.IFactoryBuildRevisionParameters) SQLException(java.sql.SQLException) MessageEvent(org.cerberus.engine.entity.MessageEvent) Connection(java.sql.Connection) IBuildRevisionParametersService(org.cerberus.crud.service.IBuildRevisionParametersService) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ApplicationContext(org.springframework.context.ApplicationContext) BuildRevisionParameters(org.cerberus.crud.entity.BuildRevisionParameters) IFactoryBuildRevisionParameters(org.cerberus.crud.factory.IFactoryBuildRevisionParameters) IUserService(org.cerberus.crud.service.IUserService) DatabaseSpring(org.cerberus.database.DatabaseSpring) ILogEventService(org.cerberus.crud.service.ILogEventService) IApplicationService(org.cerberus.crud.service.IApplicationService) PrintWriter(java.io.PrintWriter)

Example 2 with DatabaseSpring

use of org.cerberus.database.DatabaseSpring in project cerberus-source by cerberustesting.

the class ResultCI method processRequest.

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    /**
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createForPublicCalls("/ResultCI", "CALL", "ResultCI called : " + request.getRequestURL(), request);
    String tag = policy.sanitize(request.getParameter("tag"));
    String helpMessage = "\nThis servlet is used to profide a global OK or KO based on the number and status of the execution done on a specific tag.\n" + "The number of executions are ponderated by parameters by priority from cerberus_ci_okcoefprio1 to cerberus_ci_okcoefprio4.\n" + "Formula used is the following :\n" + "Nb Exe Prio 1 testcases * cerberus_ci_okcoefprio1 + Nb Exe Prio 2 testcases * cerberus_ci_okcoefprio2 +\n" + "  Nb Exe Prio 3 testcases * cerberus_ci_okcoefprio3 + Nb Exe Prio 4 testcases * cerberus_ci_okcoefprio4\n\n" + "If not executions are found, the result is KO.\n" + "With at least 1 execution, if result is < 1 then global servlet result is OK. If not, it is KO.\n" + "All execution needs to have a status equal to KO, FA, NA or PE.\n\n" + "Parameter list :\n" + "- tag [mandatory] : Execution Tag to filter the test cases execution. [" + tag + "]\n";
    DatabaseSpring database = appContext.getBean(DatabaseSpring.class);
    Connection connection = database.connect();
    try {
        boolean error = false;
        // Checking the parameter validity. Tag is a mandatory parameter
        if (StringUtils.isBlank(tag)) {
            out.println("Error - Parameter tag is mandatory.");
            error = true;
        }
        if (!error) {
            PreparedStatement prepStmt = connection.prepareStatement("SELECT count(*) AS NBKOP1 " + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b " + "ON b.test= t.test AND b.testcase=t.testcase " + "WHERE controlStatus not in ('OK') AND priority = '1' " + "AND tag = ?");
            int nbkop1 = 0;
            try {
                prepStmt.setString(1, tag);
                ResultSet rs_resultp1 = prepStmt.executeQuery();
                try {
                    if (rs_resultp1.first()) {
                        nbkop1 = Integer.valueOf(rs_resultp1.getString("NBKOP1"));
                    }
                } finally {
                    rs_resultp1.close();
                }
            } finally {
                prepStmt.close();
            }
            PreparedStatement prepStmt2 = connection.prepareStatement("SELECT count(*) AS NBKOP2 " + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b " + "ON b.test= t.test AND b.testcase=t.testcase " + "WHERE controlStatus not in ('OK') AND priority = '2' " + "AND tag = ?");
            int nbkop2 = 0;
            try {
                prepStmt2.setString(1, tag);
                ResultSet rs_resultp2 = prepStmt2.executeQuery();
                try {
                    if (rs_resultp2.first()) {
                        nbkop2 = Integer.valueOf(rs_resultp2.getString("NBKOP2"));
                    }
                } finally {
                    rs_resultp2.close();
                }
            } finally {
                prepStmt2.close();
            }
            PreparedStatement prepStmt3 = connection.prepareStatement("SELECT count(*) AS NBKOP3 " + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b " + "ON b.test= t.test AND b.testcase=t.testcase " + "WHERE controlStatus not in ('OK') AND priority = '3' " + "AND tag = ?");
            int nbkop3 = 0;
            try {
                prepStmt3.setString(1, tag);
                ResultSet rs_resultp3 = prepStmt3.executeQuery();
                try {
                    if (rs_resultp3.first()) {
                        nbkop3 = Integer.valueOf(rs_resultp3.getString("NBKOP3"));
                    }
                } finally {
                    rs_resultp3.close();
                }
            } finally {
                prepStmt3.close();
            }
            PreparedStatement prepStmt4 = connection.prepareStatement("SELECT count(*) AS NBKOP4 " + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b " + "ON b.test= t.test AND b.testcase=t.testcase " + "WHERE controlStatus not in ('OK') AND priority = '4' " + "AND tag = ?");
            int nbkop4 = 0;
            try {
                prepStmt4.setString(1, tag);
                ResultSet rs_resultp4 = prepStmt4.executeQuery();
                try {
                    if (rs_resultp4.first()) {
                        nbkop4 = Integer.valueOf(rs_resultp4.getString("NBKOP4"));
                    }
                } finally {
                    rs_resultp4.close();
                }
            } finally {
                prepStmt4.close();
            }
            IParameterService parameterService = appContext.getBean(IParameterService.class);
            float pond1 = Float.valueOf(parameterService.findParameterByKey("cerberus_ci_okcoefprio1", "").getValue());
            float pond2 = Float.valueOf(parameterService.findParameterByKey("cerberus_ci_okcoefprio2", "").getValue());
            float pond3 = Float.valueOf(parameterService.findParameterByKey("cerberus_ci_okcoefprio3", "").getValue());
            float pond4 = Float.valueOf(parameterService.findParameterByKey("cerberus_ci_okcoefprio4", "").getValue());
            String result;
            float resultCal = (nbkop1 * pond1) + (nbkop2 * pond2) + (nbkop3 * pond3) + (nbkop4 * pond4);
            if (resultCal < 1) {
                result = "OK";
            } else {
                result = "KO";
            }
            out.print(result);
            // Log the result with calculation detail.
            logEventService.createForPublicCalls("/ResultCI", "CALLRESULT", "ResultCI calculated with result [" + result + "] : " + nbkop1 + "*" + pond1 + " + " + nbkop2 + "*" + pond2 + " + " + nbkop3 + "*" + pond3 + " + " + nbkop4 + "*" + pond4 + " = " + resultCal, request);
        } else {
            // In case of errors, we display the help message.
            out.println(helpMessage);
        }
    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        out.close();
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IParameterService(org.cerberus.crud.service.IParameterService) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) SQLException(java.sql.SQLException) ApplicationContext(org.springframework.context.ApplicationContext) DatabaseSpring(org.cerberus.database.DatabaseSpring) ResultSet(java.sql.ResultSet) ILogEventService(org.cerberus.crud.service.ILogEventService) PrintWriter(java.io.PrintWriter)

Example 3 with DatabaseSpring

use of org.cerberus.database.DatabaseSpring in project cerberus-source by cerberustesting.

the class FindTestImplementationStatusPerApplication method processRequest.

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String echo = policy.sanitize(request.getParameter("sEcho"));
    String mySystem = policy.sanitize(request.getParameter("MySystem"));
    String application = policy.sanitize(request.getParameter("Application"));
    Connection connection = null;
    JSONObject jsonResponse = new JSONObject();
    try {
        List<String> sArray = new ArrayList<String>();
        if (!mySystem.equals("")) {
            String smySystem = " `system` like '%" + mySystem + "%'";
            sArray.add(smySystem);
        }
        JSONArray data = new JSONArray();
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IInvariantService invariantService = appContext.getBean(InvariantService.class);
        DatabaseSpring database = appContext.getBean(DatabaseSpring.class);
        connection = database.connect();
        AnswerList answer = invariantService.readByIdnameGp1("TCSTATUS", "Y");
        List<Invariant> myInvariants = answer.getDataList();
        StringBuilder SQL = new StringBuilder();
        StringBuilder SQLa = new StringBuilder();
        StringBuilder SQLb = new StringBuilder();
        SQLa.append("SELECT t.test, count(*) as TOTAL ");
        SQLb.append(" FROM testcase t ");
        for (Invariant i : myInvariants) {
            i.getSort();
            SQLa.append(", Col");
            SQLa.append(String.valueOf(i.getSort()));
            SQLb.append(" LEFT JOIN (SELECT g.test, count(*) as Col");
            SQLb.append(String.valueOf(i.getSort()));
            SQLb.append(" FROM testcase g WHERE Status = '");
            SQLb.append(i.getValue());
            SQLb.append("' and application ='");
            SQLb.append(application);
            SQLb.append("' GROUP BY g.test) Tab");
            SQLb.append(String.valueOf(i.getSort()));
            SQLb.append(" ON Tab");
            SQLb.append(String.valueOf(i.getSort()));
            SQLb.append(".test=t.test ");
        }
        SQLb.append(" where t.application ='");
        SQLb.append(application);
        SQLb.append("'");
        SQLb.append(" group by t.test");
        SQL.append(SQLa);
        SQL.append(SQLb);
        LOG.debug(" SQL1 : " + SQL.toString());
        PreparedStatement stmt_teststatus = connection.prepareStatement(SQL.toString());
        try (ResultSet rs_teststatus = stmt_teststatus.executeQuery()) {
            // Integer tot = 0;
            List<Integer> totLine;
            totLine = new ArrayList<Integer>();
            for (Invariant i : myInvariants) {
                totLine.add(0);
            }
            try {
                while (rs_teststatus.next()) {
                    JSONArray row = new JSONArray();
                    StringBuilder testLink = new StringBuilder();
                    testLink.append("<a href=\"TestCaseList.jsp?test=");
                    testLink.append(rs_teststatus.getString("t.test"));
                    testLink.append("\">");
                    testLink.append(rs_teststatus.getString("t.test"));
                    testLink.append("</a>");
                    row.put(testLink.toString());
                    row.put(rs_teststatus.getString("TOTAL"));
                    for (Invariant i : myInvariants) {
                        i.getSort();
                        row.put(rs_teststatus.getString("Col" + String.valueOf(i.getSort())));
                    }
                    data.put(row);
                }
                // data that will be shown in the table
                jsonResponse.put("aaData", data);
                jsonResponse.put("sEcho", echo);
                jsonResponse.put("iTotalRecords", data.length());
                jsonResponse.put("iTotalDisplayRecords", data.length());
                response.setContentType("application/json");
                response.getWriter().print(jsonResponse.toString());
            } catch (JSONException ex) {
                LOG.warn(ex.toString());
            } finally {
                out.close();
            }
        } catch (SQLException ex) {
            LOG.warn(" Exception trying to query '" + SQL.toString() + "' : " + ex);
        } finally {
            stmt_teststatus.close();
        }
    } catch (Exception ex) {
        LOG.warn(" Exception catched : " + ex);
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
}
Also used : Invariant(org.cerberus.crud.entity.Invariant) AnswerList(org.cerberus.util.answer.AnswerList) PolicyFactory(org.owasp.html.PolicyFactory) SQLException(java.sql.SQLException) IInvariantService(org.cerberus.crud.service.IInvariantService) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) PreparedStatement(java.sql.PreparedStatement) ServletException(javax.servlet.ServletException) SQLException(java.sql.SQLException) JSONException(org.json.JSONException) IOException(java.io.IOException) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) DatabaseSpring(org.cerberus.database.DatabaseSpring) ResultSet(java.sql.ResultSet) PrintWriter(java.io.PrintWriter)

Example 4 with DatabaseSpring

use of org.cerberus.database.DatabaseSpring in project cerberus-source by cerberustesting.

the class TestcaseList 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");
    PrintWriter out = response.getWriter();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    DatabaseSpring db = appContext.getBean(DatabaseSpring.class);
    PreparedStatement stmt_testlist = null;
    try (Connection conn = db.connect()) {
        String application = request.getParameter("application");
        String app = "";
        String test = request.getParameter("test");
        String tes = "";
        String url = request.getParameter("url");
        if ((StringUtils.isNotBlank(application)) && !(application.equals("all"))) {
            app = " and application = '" + application + "'";
        } else {
            app = "";
        }
        if ((StringUtils.isNotBlank(test)) && !(test.equals("all"))) {
            tes = " and test = '" + test + "'";
        } else {
            tes = "";
        }
        if (StringUtils.isNotBlank(url)) {
            stmt_testlist = conn.prepareStatement("SELECT concat(?) AS list FROM testcase " + " WHERE TcActive = 'Y'  AND `Group` = 'AUTOMATED' ? ? ORDER BY test,testcase");
            stmt_testlist.setString(1, url);
            stmt_testlist.setString(2, app);
            stmt_testlist.setString(3, tes);
            try (ResultSet rs_testlist = stmt_testlist.executeQuery()) {
                int id = 0;
                if (rs_testlist.first()) {
                    do {
                        out.println(rs_testlist.getString("list"));
                    } while (rs_testlist.next());
                }
            } catch (SQLException ex) {
                LOG.warn(ex.toString());
            }
            stmt_testlist.close();
        }
    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        out.close();
        try {
            if (stmt_testlist != null) {
                stmt_testlist.close();
            }
        } catch (SQLException ex) {
            LOG.warn("Exception closing PreparedStatement: " + ex.toString());
        }
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) SQLException(java.sql.SQLException) DatabaseSpring(org.cerberus.database.DatabaseSpring) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) SQLException(java.sql.SQLException) PrintWriter(java.io.PrintWriter)

Example 5 with DatabaseSpring

use of org.cerberus.database.DatabaseSpring in project cerberus-source by cerberustesting.

the class TestcaseListGrid 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");
    PrintWriter out = response.getWriter();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    DatabaseSpring db = appContext.getBean(DatabaseSpring.class);
    Connection conn = db.connect();
    try {
        StringBuilder whereclauses = new StringBuilder();
        String application = "";
        if (request.getParameter("application") != null && !(request.getParameter("application").equals("all"))) {
            application = request.getParameter("application");
            whereclauses.append(" and a.application = '");
            whereclauses.append(application);
            whereclauses.append("'");
        }
        String test = "";
        if (request.getParameter("test") != null && !(request.getParameter("test").equals("all"))) {
            test = request.getParameter("test");
            whereclauses.append(" and a.test = '");
            whereclauses.append(test);
            whereclauses.append("'");
        }
        String testcase = "";
        if (request.getParameter("testcase") != null && !(request.getParameter("testcase").equals("all"))) {
            testcase = request.getParameter("testcase");
            whereclauses.append(" and a.testcase = '");
            whereclauses.append(testcase);
            whereclauses.append("'");
        }
        int repeat = 0;
        if (request.getParameter("repeat") != null && !(request.getParameter("repeat").equals("0"))) {
            repeat = Integer.valueOf(request.getParameter("repeat"));
        }
        if (request.getParameter("country") != null) {
            String[] countries = request.getParameterValues("country");
            StringBuilder strb = new StringBuilder(whereclauses);
            for (int x = 0; x < countries.length; x++) {
                strb.append(" and b.country = '");
                strb.append(countries[x]);
                strb.append("'");
            }
            whereclauses = new StringBuilder();
            whereclauses.append(strb.toString());
        }
        if (request.getParameter("status") != null) {
            String[] status = request.getParameterValues("status");
            StringBuilder strb = new StringBuilder(whereclauses);
            strb.append(" AND ( ");
            for (int x = 0; x < status.length; x++) {
                if (x > 0) {
                    strb.append(" OR ");
                }
                strb.append(" a.status = '");
                strb.append(status[x]);
                strb.append("'");
            }
            strb.append(" ) ");
            whereclauses = new StringBuilder();
            whereclauses.append(strb.toString());
        }
        if (request.getParameter("project") != null) {
            String[] projects = request.getParameterValues("project");
            StringBuilder strb = new StringBuilder(whereclauses);
            strb.append(" AND ( ");
            for (int x = 0; x < projects.length; x++) {
                if (x > 0) {
                    strb.append(" OR ");
                }
                strb.append(" a.project = '");
                strb.append(projects[x]);
                strb.append("'");
            }
            strb.append(" ) ");
            whereclauses = new StringBuilder();
            whereclauses.append(strb.toString());
        }
        int number = 1;
        if (request.getParameter("number") != null) {
            number = Integer.valueOf(request.getParameter("number"));
        }
        int totalnumber = 1;
        if (request.getParameter("totalnumber") != null) {
            totalnumber = Integer.valueOf(request.getParameter("totalnumber"));
        }
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT count(*) FROM testcase a JOIN testcasecountry b ON a.test=b.test ");
        sb.append(" AND a.testcase=b.testcase WHERE a.TcActive = 'Y'  AND a.`Group` = 'AUTOMATED'");
        sb.append(whereclauses);
        sb.append(" ORDER BY a.test,a.testcase");
        PreparedStatement stmt_count = conn.prepareStatement(sb.toString());
        int count;
        try {
            // stmt_count.setString(1, whereclauses);
            ResultSet rs_count = stmt_count.executeQuery();
            try {
                count = 1;
                if (rs_count.first()) {
                    count = rs_count.getInt(1) / totalnumber;
                }
                number = (number - 1) * count;
            } finally {
                rs_count.close();
            }
        } finally {
            stmt_count.close();
        }
        String url = "";
        if (request.getParameter("url") != null) {
            url = request.getParameter("url");
            StringBuilder sb2 = new StringBuilder();
            sb2.append("SELECT replace(concat( ");
            sb2.append(url);
            sb2.append("), \"%COUNTRY%\", country) AS list  FROM testcase a JOIN testcasecountry b ON a.test=b.test");
            sb2.append(" AND a.testcase=b.testcase WHERE a.TcActive = 'Y'  AND a.`Group` = 'AUTOMATED' ");
            sb2.append(whereclauses);
            sb2.append(" ORDER BY a.test,a.testcase LIMIT ");
            sb2.append(number);
            sb2.append(",");
            sb2.append(count);
            LOG.info("SQL query: " + sb2.toString());
            PreparedStatement stmt_testlist = conn.prepareStatement(sb2.toString());
            try {
                // stmt_testlist.setString(1, url);
                // stmt_testlist.setString(2, whereclauses);
                // stmt_testlist.setInt(3, number);
                // stmt_testlist.setInt(4, count);
                ResultSet rs_testlist = stmt_testlist.executeQuery();
                try {
                    int id = 0;
                    if (rs_testlist.first()) {
                        for (int a = 0; a < repeat; a++) {
                            rs_testlist.first();
                            do {
                                out.println(rs_testlist.getString("list"));
                            } while (rs_testlist.next());
                        }
                    }
                } finally {
                    rs_testlist.close();
                }
            } finally {
                stmt_testlist.close();
            }
        }
    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        out.close();
        try {
            conn.close();
        } catch (Exception ex) {
            LOG.warn("Exception closing Connection: " + ex.toString());
        }
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) DatabaseSpring(org.cerberus.database.DatabaseSpring) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Aggregations

Connection (java.sql.Connection)6 DatabaseSpring (org.cerberus.database.DatabaseSpring)6 IOException (java.io.IOException)5 PrintWriter (java.io.PrintWriter)5 PreparedStatement (java.sql.PreparedStatement)5 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 ServletException (javax.servlet.ServletException)5 ApplicationContext (org.springframework.context.ApplicationContext)5 ArrayList (java.util.ArrayList)2 ILogEventService (org.cerberus.crud.service.ILogEventService)2 MessageEvent (org.cerberus.engine.entity.MessageEvent)2 AnswerItem (org.cerberus.util.answer.AnswerItem)2 AnswerList (org.cerberus.util.answer.AnswerList)2 PolicyFactory (org.owasp.html.PolicyFactory)2 Strings (com.google.common.base.Strings)1 Statement (java.sql.Statement)1 List (java.util.List)1 Map (java.util.Map)1 LogManager (org.apache.logging.log4j.LogManager)1