Example usage for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext

List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext.

Prototype

@Nullable
public static WebApplicationContext getWebApplicationContext(ServletContext sc) 

Source Link

Document

Find the root WebApplicationContext for this web app, typically loaded via org.springframework.web.context.ContextLoaderListener .

Usage

From source file:org.cerberus.servlet.crud.test.ImportTestCaseFromJson.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w.  jav  a  2s .c om
 *
 * @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 {
    String test = "";
    String testcase = "";
    JSONObject jo = null;
    FileItem item = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();

                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equals("test")) {
                        test = item.getString("UTF-8");
                    }
                    if (name.equals("testcase")) {
                        testcase = item.getString("UTF-8");
                    }
                } else {
                    InputStream inputStream = item.getInputStream();

                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(inputStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;
                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }
                    inputStream.close();
                    streamReader.close();
                    jo = new JSONObject(responseStrBuilder.toString());

                }

            }

            ApplicationContext appContext = WebApplicationContextUtils
                    .getWebApplicationContext(this.getServletContext());
            ITestCaseService tcService = appContext.getBean(ITestCaseService.class);
            TestCase tcInfo = new TestCase();
            tcInfo.setTest(test);
            tcInfo.setTestCase(testcase);
            tcInfo.setOrigine(jo.getString("origin") == null ? "" : jo.getString("origin"));
            tcInfo.setImplementer(jo.getString("implementer") == null ? "123TOTO" : "1234TOTO");
            tcInfo.setBehaviorOrValueExpected(jo.getString("description") == null ? "1293TOTO" : "12394TOTO");

            tcService.updateTestCaseInformation(tcInfo);

            response.sendRedirect("TestCase.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException ex) {
            Logger.getLogger(ImportTestCaseFromJson.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.cerberus.servlet.crud.testcampaign.UpdateCampaign2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w . ja  va2  s  . co  m*/
 *
 * @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("text/html;charset=UTF-8");
    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 desc = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("Description"),
            null, charset);

    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);

        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();
            if (!desc.equals(camp.getDescription())) {
                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.createPrivateCalls("/UpdateCampaign", "UPDATE", "Update Campaign : " + c,
                            request);
                }
            }

            if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && battery != null) {
                JSONArray batteries = new JSONArray(battery);
                ICampaignContentService campaignContentService = appContext
                        .getBean(ICampaignContentService.class);
                IFactoryCampaignContent factoryCampaignContent = appContext
                        .getBean(IFactoryCampaignContent.class);
                ArrayList<CampaignContent> arr = new ArrayList<>();
                for (int i = 0; i < batteries.length(); i++) {
                    JSONArray bat = batteries.getJSONArray(i);
                    CampaignContent co = factoryCampaignContent.create(0, bat.getString(0), bat.getString(1));
                    arr.add(co);
                }

                finalAnswer = campaignContentService.compareListAndUpdateInsertDeleteElements(c, arr);
                if (finalAnswer.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createPrivateCalls("/UpdateCampaign", "UPDATE",
                            "Update Campaign Content : " + camp.getCampaign(), 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(2),
                            bat.getString(1), 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.createPrivateCalls("/UpdateCampaign", "UPDATE",
                            "Update Campaign Parameter : " + 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();
}

From source file:org.cerberus.servlet.crud.testdata.ReadTestDataLib.java

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    // Default message to unexpected error.
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    AnswerItem answer = new AnswerItem(msg);

    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");

    /**/* w w w  . j  a va 2  s. c  o m*/
     * Parsing and securing all required parameters.
     */
    String name = policy.sanitize(request.getParameter("name"));
    String country = policy.sanitize(request.getParameter("country"));
    String columnName = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
    Integer testDataLibId = 0;

    Integer limit = -1;
    boolean hasError = true;
    try {
        if (request.getParameter("testdatalibid") != null && !request.getParameter("testdatalibid").isEmpty()) {
            testDataLibId = Integer.parseInt(request.getParameter("testdatalibid"));
            hasError = false;
        }
    } catch (NumberFormatException ex) {
        org.apache.log4j.Logger.getLogger(ReadTestDataLib.class.getName()).log(org.apache.log4j.Level.ERROR,
                null, ex);
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Data Library"));
        msg.setDescription(msg.getDescription().replace("%OPERATION%", "Read"));
        msg.setDescription(
                msg.getDescription().replace("%REASON%", "Test data library id must be an integer value."));
        answer.setResultMessage(msg);
        hasError = true;
    }
    try {
        //if the limit fails to be converted there is no problem because in the database we use the default value
        if (request.getParameter("limit") != null && !request.getParameter("limit").isEmpty()) {
            limit = Integer.parseInt(request.getParameter("limit"));
        }
    } catch (NumberFormatException ex) {
        org.apache.log4j.Logger.getLogger(ReadTestDataLib.class.getName()).log(org.apache.log4j.Level.WARN,
                null, ex);
    }

    // Global boolean on the servlet that define if the user has permition to edit and delete object.
    boolean userHasPermissions = request.isUserInRole("TestDataManager");

    try {
        JSONObject jsonResponse;

        if (request.getParameter("testdatalibid") != null && !hasError) {
            if (request.getParameter("name") != null && request.getParameter("country") != null) {
                //gets all test cases that use a library
                answer = getTestCasesUsingTestDataLib(testDataLibId, name, country, appContext,
                        userHasPermissions);
            } else {
                //gets a lib by id
                answer = findTestDataLibByID(testDataLibId, appContext, userHasPermissions);
            }
        } else if (request.getParameter("name") != null && request.getParameter("limit") != null) {
            answer = findTestDataLibNameList(name, limit, appContext);
        } else if (request.getParameter("groups") != null) {
            //gets the list of distinct groups
            answer = findDistinctGroups(appContext);
        } else if (!Strings.isNullOrEmpty(columnName)) {
            answer = findDistinctValuesOfColumn(appContext, request, columnName);
            jsonResponse = (JSONObject) answer.getItem();
        } else {
            //no parameters, then retrieves the full list
            answer = findTestDataLibList(appContext, request);
        }

        jsonResponse = (JSONObject) answer.getItem();

        jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", answer.getResultMessage().getDescription());

        response.getWriter().print(jsonResponse.toString());

    } catch (JSONException e) {
        org.apache.log4j.Logger.getLogger(ReadTestDataLib.class.getName()).log(org.apache.log4j.Level.ERROR,
                null, e);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}

From source file:org.cerberus.servlet.crud.testexecution.ReadTestCaseExecution.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w.  ja  v  a  2 s . co  m
 *
 * @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, ParseException {
    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());

    response.setContentType("application/json");
    response.setCharacterEncoding("utf8");

    testCaseExecutionService = appContext.getBean(ITestCaseExecutionService.class);

    try {
        JSONObject jsonResponse = new JSONObject();
        AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
        // Data/Filter Parameters.
        String Tag = ParameterParserUtil.parseStringParam(request.getParameter("Tag"), "");
        String test = ParameterParserUtil.parseStringParam(request.getParameter("test"), "");
        String testCase = ParameterParserUtil.parseStringParam(request.getParameter("testCase"), "");
        String system = ParameterParserUtil.parseStringParam(request.getParameter("system"), "");
        long executionId = ParameterParserUtil.parseLongParam(request.getParameter("executionId"), 0);
        // Switch Parameters.
        boolean executionWithDependency = ParameterParserUtil.parseBooleanParam("executionWithDependency",
                false);
        String columnName = ParameterParserUtil.parseStringParam(request.getParameter("columnName"), "");
        boolean byColumns = ParameterParserUtil.parseBooleanParam(request.getParameter("byColumns"), false);

        if (!Strings.isNullOrEmpty(columnName)) {
            //If columnName is present, then return the distinct value of this column.
            //In this specific case, do nothing as distinct will be done client side
        } else if (!Tag.equals("") && byColumns) {
            //Return the columns to display in the execution table
            answer = findExecutionColumns(appContext, request, Tag);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (!Tag.equals("") && !byColumns) {
            //Return the list of execution for the execution table
            answer = findExecutionListByTag(appContext, request, Tag);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (!system.isEmpty()) {
            //find execution by system, the remaining parameters are parsed after avoiding the extra processing
            answer = findExecutionListBySystem(system, appContext, request);
            jsonResponse = (JSONObject) answer.getItem();
        } else if (!test.equals("") && !testCase.equals("")) {
            TestCaseExecution lastExec = testCaseExecutionService.findLastTestCaseExecutionNotPE(test,
                    testCase);
            JSONObject result = new JSONObject();
            if (lastExec != null) {
                result.put("id", lastExec.getId());
                result.put("controlStatus", lastExec.getControlStatus());
                result.put("env", lastExec.getEnvironment());
                result.put("country", lastExec.getCountry());
                result.put("end", new Date(lastExec.getEnd())).toString();
            }
            jsonResponse.put("contentTable", result);
        } else if (executionId != 0 && !executionWithDependency) {
            answer = testCaseExecutionService.readByKeyWithDependency(executionId);
            TestCaseExecution tce = (TestCaseExecution) answer.getItem();
            jsonResponse.put("testCaseExecution", tce.toJson());
        } else if (executionId != 0 && executionWithDependency) {

        } else {
            answer = findTestCaseExecutionList(appContext, true, request);
            jsonResponse = (JSONObject) answer.getItem();
        }

        jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
        jsonResponse.put("message", answer.getResultMessage().getDescription());

        response.getWriter().print(jsonResponse.toString());
    } catch (JSONException ex) {
        org.apache.log4j.Logger.getLogger(ReadTestCaseExecution.class.getName())
                .log(org.apache.log4j.Level.ERROR, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }
}

From source file:org.cerberus.servlet.crud.testexecution.ReadTestCaseExecutionMedia.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww .j a  v  a  2 s. c om
 *
 * @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 CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException {
    String charset = request.getCharacterEncoding();

    String type = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("type"), "",
            charset);
    String test = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), "",
            charset);
    String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testcase"),
            "", charset);
    String fileName = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("filename"),
            "", charset);
    String fileType = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("filetype"),
            "", charset);
    String fileDesc = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("filedesc"),
            "", charset);
    int step = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("step"), 0, charset);
    int index = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("index"), 1, charset);
    int sequence = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("sequence"), 0, charset);
    int sequenceControl = ParameterParserUtil
            .parseIntegerParamAndDecode(request.getParameter("sequenceControl"), 0, charset);
    int iterator = ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("iterator"), 0, charset);
    boolean autoContentType = ParameterParserUtil.parseBooleanParam(request.getParameter("autoContentType"),
            true);
    long id = ParameterParserUtil.parseLongParamAndDecode(request.getParameter("id"), 0, charset);

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IParameterService parameterService = appContext.getBean(IParameterService.class);

    BufferedImage b = null;

    AnswerList al = new AnswerList<>(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED));

    TestCaseExecutionFile tceFile = null;
    if (!(fileName.equals(""))) {

        IFactoryTestCaseExecutionFile factoryTestCaseExecutionFile = appContext
                .getBean(IFactoryTestCaseExecutionFile.class);
        tceFile = factoryTestCaseExecutionFile.create(0, 0, "", fileDesc, fileName, fileType, "", null, "",
                null);

    } else {

        ITestCaseExecutionFileService testCaseExecutionFileService = appContext
                .getBean(ITestCaseExecutionFileService.class);

        String levelFile = "";
        if (type.equals("action")) {
            levelFile = test + "-" + testcase + "-" + step + "-" + index + "-" + sequence;
        } else if (type.equals("control")) {
            levelFile = test + "-" + testcase + "-" + step + "-" + index + "-" + sequence + "-"
                    + sequenceControl;
        }
        al = testCaseExecutionFileService.readByVarious(id, levelFile);

        if (al.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && !al.getDataList().isEmpty()) {
            Iterator i = al.getDataList().iterator();
            int indexIterator = -1;
            while (i.hasNext() && indexIterator != iterator) {
                indexIterator++;
                TestCaseExecutionFile tctemp = (TestCaseExecutionFile) i.next();
                if (indexIterator == iterator) {
                    tceFile = tctemp;
                }
            }
        } else {
            // If previous read failed we try without index. (that can be removed few moths after step index has been introduced in Jan 2017)
            if (type.equals("action")) {
                levelFile = test + "-" + testcase + "-" + step + "-" + sequence;
            } else if (type.equals("control")) {
                levelFile = test + "-" + testcase + "-" + step + "-" + sequence + "-" + sequenceControl;
            }
            al = testCaseExecutionFileService.readByVarious(id, levelFile);
            if (al.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && !al.getDataList().isEmpty()) {
                Iterator i = al.getDataList().iterator();
                int indexIterator = -1;
                while (i.hasNext() && indexIterator != iterator) {
                    indexIterator++;
                    TestCaseExecutionFile tctemp = (TestCaseExecutionFile) i.next();
                    if (indexIterator == iterator) {
                        tceFile = tctemp;
                    }
                }
            }
        }
    }

    if (tceFile != null) {
        String pathString = parameterService.getParameterStringByKey("cerberus_mediastorage_path", "", "");
        switch (tceFile.getFileType()) {
        case "JPG":
        case "PNG":
        case "GIF":
        case "JPEG":
            returnImage(request, response, tceFile, pathString);
            break;
        case "HTML":
            if (autoContentType) {
                response.setContentType("text/html");
            }
            returnFile(request, response, tceFile, pathString);
            break;
        case "XML":
            if (autoContentType) {
                response.setContentType("application/xml");
            }
            returnFile(request, response, tceFile, pathString);
            break;
        case "JSON":
            if (autoContentType) {
                response.setContentType("application/json");
            }
            returnFile(request, response, tceFile, pathString);
            break;
        case "TXT":
            returnFile(request, response, tceFile, pathString);
            break;
        default:
            returnNotSupported(request, response, tceFile, pathString);
        }

    }
}

From source file:org.cerberus.servlet.crud.usermanagement.UpdateMyUserReporting1.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JSONObject jsonResponse = new JSONObject();

    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);

    String login = request.getUserPrincipal().getName();
    String charset = request.getCharacterEncoding();
    /**/*from  ww w. java 2 s. co  m*/
     * Parse parameters - list of values
     */
    List<String> tcstatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcstatus"), null, charset);
    List<String> groupList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("group"),
            null, charset);
    List<String> tcactiveList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcactive"), null, charset);
    List<String> priorityList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("priority"), null, charset);

    List<String> countryList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("country"), null, charset);
    List<String> browserList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("browser"), null, charset);
    List<String> tcestatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcestatus"), null, charset);

    //environment
    List<String> environmentList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("environment"), null, charset);
    List<String> projectList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("project"), null, charset);
    /**
     * Parse parameters - free text
     */
    String ip = StringEscapeUtils.escapeHtml4(request.getParameter("ip"));
    String port = StringEscapeUtils.escapeHtml4(request.getParameter("port"));
    String tag = StringEscapeUtils.escapeHtml4(request.getParameter("tag"));
    String browserversion = StringEscapeUtils.escapeHtml4(request.getParameter("browserversion"));
    String comment = StringEscapeUtils.escapeHtml4(request.getParameter("comment"));

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IUserService userService = appContext.getBean(UserService.class);

    try {
        User user = userService.findUserByKey(login);
        if (user != null) {
            JSONObject preferences = new JSONObject();

            if (tcstatusList != null) {
                preferences.put("s", tcstatusList);
            }
            if (groupList != null) {
                preferences.put("g", groupList);
            }
            if (tcactiveList != null) {
                preferences.put("a", tcactiveList);
            }
            if (priorityList != null) {
                preferences.put("pr", priorityList);
            }
            if (countryList != null) {
                preferences.put("co", countryList);
            }
            if (browserList != null) {
                preferences.put("b", browserList);
            }
            if (tcestatusList != null) {
                preferences.put("es", tcestatusList);
            }
            if (environmentList != null) {
                preferences.put("e", environmentList);
            }
            if (projectList != null) {
                preferences.put("prj", projectList);
            }

            if (!StringUtil.isNullOrEmpty(ip)) {
                preferences.put("ip", ip);
            }
            if (!StringUtil.isNullOrEmpty(port)) {
                preferences.put("p", port);
            }
            if (!StringUtil.isNullOrEmpty(tag)) {
                preferences.put("t", tag);
            }
            if (!StringUtil.isNullOrEmpty(browserversion)) {
                preferences.put("br", browserversion);
            }
            if (!StringUtil.isNullOrEmpty(comment)) {
                preferences.put("cm", comment);
            }

            user.setReportingFavorite(preferences.toString());
            userService.updateUser(user); //TODO: when converting to the new standard this should return an answer
            //re-send the updated preferences 

            jsonResponse.put("preferences", preferences);

            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Execution reporting filters ")
                    .replace("%OPERATION%", "Update"));

            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createPrivateCalls("/UpdateMyUserReporting1", "UPDATE",
                    "Update user reporting preference for user: " + login, request);
        } else {
            msg.setDescription(
                    msg.getDescription().replace("%DESCRIPTION%", "Unable to update User was not found!"));
        }

        jsonResponse.put("messageType", msg.getMessage().getCodeString());
        jsonResponse.put("message", msg.getDescription());
    } catch (JSONException ex) {
        Logger.getLogger(UpdateMyUserReporting1.class.getName()).log(Level.SEVERE, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    } catch (CerberusException ex) {
        Logger.getLogger(UpdateMyUserReporting1.class.getName()).log(Level.SEVERE, null, ex);
        //returns a default error message with the json format that is able to be parsed by the client-side
        response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
    }

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}

From source file:org.cerberus.servlet.publi.ResultCI.java

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());

    /**//from   w w  w  .j av a2  s. co  m
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    logEventService.insertLogEventPublicCalls("/ResultCI", "CALL",
            "ResultCIV0 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 CI_OK_prio1 to CI_OK_prio4.\n"
            + "Formula used is the following :\n"
            + "Nb Exe Prio 1 testcases * CI_OK_prio1 + Nb Exe Prio 2 testcases * CI_OK_prio2 +\n"
            + "  Nb Exe Prio 3 testcases * CI_OK_prio3 + Nb Exe Prio 4 testcases * CI_OK_prio4\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(ParameterService.class);

            float pond1 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio1", "").getValue());
            float pond2 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio2", "").getValue());
            float pond3 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio3", "").getValue());
            float pond4 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio4", "").getValue());

            String result;
            float resultCal = (nbkop1 * pond1) + (nbkop2 * pond2) + (nbkop3 * pond3) + (nbkop4 * pond4);
            if ((resultCal < 1) && (nbkop1 + nbkop2 + nbkop3 + nbkop4 > 0)) {
                result = "OK";
            } else {
                result = "KO";
            }
            out.print(result);

            // Log the result with calculation detail.
            logEventService.insertLogEventPublicCalls("/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) {
            MyLogger.log(ResultCI.class.getName(), org.apache.log4j.Level.WARN, e.toString());
        }
    }

}

From source file:org.cerberus.servlet.publi.RunTestCase.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());

    /**/*from ww  w .  j a  v a2 s .  co m*/
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    logEventService.insertLogEventPublicCalls("/RunTestCase", "CALL",
            "RunTestCaseV0 called : " + request.getRequestURL(), request);

    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    //Tool
    String robotHost = "";
    String robotPort = "";
    String browser = "";
    String version = "";
    String platform = "";
    String robot = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("robot")), "");
    String active = "";

    if (robot.equals("")) {
        robotHost = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("ss_ip")), "");
        robotPort = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("ss_p")), "");
        browser = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("browser")),
                "firefox");
        version = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("version")), "");
        platform = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("platform")), "");
    } else {
        IRobotService robotService = appContext.getBean(IRobotService.class);
        try {
            Robot robObj = robotService.findRobotByName(robot);
            robotHost = robObj.getHost();
            robotPort = String.valueOf(robObj.getPort());
            browser = robObj.getBrowser();
            version = robObj.getVersion();
            platform = robObj.getPlatform();
            active = robObj.getActive();
        } catch (CerberusException ex) {
            Logger.getLogger(RunTestCase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }

    //Test
    String test = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("Test")), "");
    String testCase = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("TestCase")),
            "");
    String country = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("Country")), "");
    String environment = ParameterParserUtil
            .parseStringParam(policy.sanitize(request.getParameter("Environment")), "");

    //Test Dev Environment
    boolean manualURL = ParameterParserUtil
            .parseBooleanParam(policy.sanitize(request.getParameter("manualURL")), false);
    String myHost = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("myhost")), "");
    String myContextRoot = ParameterParserUtil
            .parseStringParam(policy.sanitize(request.getParameter("mycontextroot")), "");
    String myLoginRelativeURL = ParameterParserUtil
            .parseStringParam(policy.sanitize(request.getParameter("myloginrelativeurl")), "");
    //TODO find another solution
    myLoginRelativeURL = myLoginRelativeURL.replace("&#61;", "=");
    String myEnvData = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("myenvdata")),
            "");

    //Execution
    String tag = ParameterParserUtil.parseStringParam(policy.sanitize(request.getParameter("Tag")), "");
    String outputFormat = ParameterParserUtil
            .parseStringParam(policy.sanitize(request.getParameter("outputformat")), "compact");
    int screenshot = ParameterParserUtil.parseIntegerParam(policy.sanitize(request.getParameter("screenshot")),
            1);
    int verbose = ParameterParserUtil.parseIntegerParam(policy.sanitize(request.getParameter("verbose")), 0);

    String helpMessage = "\nThis servlet is used to start the execution of a test case.\n"
            + "Parameter list :\n" + "- Test [mandatory] : Test to execute. [" + test + "]\n"
            + "- TestCase [mandatory] : Test Case reference to execute. [" + testCase + "]\n"
            + "- Country [mandatory] : Country where the test case will execute. [" + country + "]\n"
            + "- Environment [mandatory] : Environment where the test case will execute. [" + environment
            + "]\n" + "- robot : robot name on which the test will be executed. [" + robot + "]\n"
            + "- ss_ip : Host of the Robot where the test will be executed. [" + robotHost + "]\n"
            + "- ss_p : Port of the Robot. [" + robotPort + "]\n"
            + "- browser : Browser to use for the execution. [" + browser + "]\n"
            + "- version : Version to use for the execution. [" + version + "]\n"
            + "- platform : Platform to use for the execution. [" + platform + "]\n"
            + "- manualURL : Activate or not the Manual URL of the application to execute. If activated the 4 parameters after (myhost, mycontextroot, myloginrelativeurl, myenvdata) are necessary. ["
            + manualURL + "]\n" + "- myhost : Host of the application to test. [" + myHost + "]\n"
            + "- mycontextroot : Context root of the application to test. [" + myContextRoot + "]\n"
            + "- myloginrelativeurl : Relative login URL of the application. [" + myLoginRelativeURL + "]\n"
            + "- myenvdata : Environment where to get the test data when a manualURL is defined. [" + myEnvData
            + "]\n" + "- Tag : Tag that will be stored on the execution. [" + tag + "]\n"
            + "- outputformat : Format of the output of the execution. [" + outputFormat + "]\n"
            + "- screenshot : Activate or not the screenshots. [" + screenshot + "]\n"
            + "- verbose : Verbose level of the execution. [" + verbose + "]\n";

    boolean error = false;

    // Checking the parameter validity. Tag is a mandatory parameter
    if (StringUtils.isBlank(test)) {
        out.println("Error - Parameter test is mandatory.");
        error = true;
    }
    if (StringUtils.isBlank(testCase)) {
        out.println("Error - Parameter testCase is mandatory.");
        error = true;
    }
    if (StringUtils.isBlank(country)) {
        out.println("Error - Parameter country is mandatory.");
        error = true;
    }
    if (StringUtils.isBlank(environment) && !manualURL) {
        out.println("Error - Parameter environment is mandatory.");
        error = true;
    }
    if (active.equals("N") && !manualURL) {
        out.println("Error - Robot is not Active.");
        error = true;
    }

    if (!error) {

        IRunTestCaseService runTestCaseService = appContext.getBean(RunTestCaseService.class);
        IFactoryTCase factoryTCase = appContext.getBean(IFactoryTCase.class);
        IFactoryTestCaseExecution factoryTCExecution = appContext.getBean(IFactoryTestCaseExecution.class);

        TCase tCase = factoryTCase.create(test, testCase);

        TestCaseExecution tCExecution = factoryTCExecution.create(0, test, testCase, null, null, environment,
                country, browser, version, platform, "", 0, 0, "", "", null, robotHost, null, robotPort, tag,
                "N", verbose, screenshot, outputFormat, null, Version.PROJECT_NAME_VERSION, tCase, null, null,
                manualURL, myHost, myContextRoot, myLoginRelativeURL, myEnvData, robotHost, robotPort, null,
                new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTSTARTED));

        /**
         * Set UUID
         */
        ExecutionUUID executionUUIDObject = appContext.getBean(ExecutionUUID.class);
        UUID executionUUID = UUID.randomUUID();
        executionUUIDObject.setExecutionUUID(executionUUID.toString(), 0);
        tCExecution.setExecutionUUID(executionUUID.toString());
        MyLogger.log(RunTestCase.class.getName(), Level.DEBUG, "Execution Key : " + executionUUID);

        try {
            tCExecution = runTestCaseService.runTestCase(tCExecution);
        } catch (Exception ex) {
            MyLogger.log(RunTestCase.class.getName(), Level.FATAL, "Exception on testcase: "
                    + tCExecution.getId() + "\nDetail: " + ex.getMessage() + "\n\n" + ex.toString());
        }

        long runID = tCExecution.getId();
        if (outputFormat.equalsIgnoreCase("gui")) {
            if (runID > 0) {
                response.sendRedirect("./ExecutionDetail.jsp?id_tc=" + runID);
            } else {
                out.println(
                        "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>Test Execution Result</title></head>");
                out.println("<body>");
                out.println("<table>");
                out.println("<tr><td>RunID</td><td><span id='RunID'>" + runID + "</span></td></tr>");
                out.println("<tr><td>Test</td><td><span id='Test'>" + test + "</span></td></tr>");
                out.println("<tr><td>TestCase</td><td><span id='TestCase'>" + testCase + "</span></td></tr>");
                out.println("<tr><td>Country</td><td><span id='Country'>" + country + "</span></td></tr>");
                out.println("<tr><td>Environment</td><td><span id='Environment'>" + environment
                        + "</span></td></tr>");
                out.println("<tr><td>TimestampStart</td><td><span id='TimestampStart'>"
                        + new Timestamp(tCExecution.getStart()) + "</span></td></tr>");
                out.println("<tr><td>TimestampEnd</td><td><span id='TimestampEnd'>"
                        + new Timestamp(tCExecution.getEnd()) + "</span></td></tr>");
                out.println("<tr><td>OutputFormat</td><td><span id='OutputFormat'>" + outputFormat
                        + "</span></td></tr>");
                out.println("<tr><td>Verbose</td><td><span id='Verbose'>" + verbose + "</span></td></tr>");
                out.println(
                        "<tr><td>Screenshot</td><td><span id='Screenshot'>" + screenshot + "</span></td></tr>");
                out.println("<tr><td>Robot</td><td><span id='Browser'>" + robot + "</span></td></tr>");
                out.println("<tr><td>Browser</td><td><span id='Browser'>" + browser + "</span></td></tr>");
                out.println("<tr><td>Version</td><td><span id='Browser'>" + version + "</span></td></tr>");
                out.println("<tr><td>Platform</td><td><span id='Browser'>" + platform + "</span></td></tr>");
                out.println("<tr><td>ManualURL</td><td><span id='ManualURL'>" + tCExecution.isManualURL()
                        + "</span></td></tr>");
                out.println("<tr><td>MyHost</td><td><span id='MyHost'>" + tCExecution.getMyHost()
                        + "</span></td></tr>");
                out.println("<tr><td>MyContextRoot</td><td><span id='MyContextRoot'>"
                        + tCExecution.getMyContextRoot() + "</span></td></tr>");
                out.println("<tr><td>MyLoginRelativeURL</td><td><span id='MyLoginRelativeURL'>"
                        + tCExecution.getMyLoginRelativeURL() + "</span></td></tr>");
                out.println("<tr><td>myEnvironmentData</td><td><span id='myEnvironmentData'>"
                        + tCExecution.getEnvironmentData() + "</span></td></tr>");
                out.println("<tr><td>ReturnCode</td><td><b><span id='ReturnCodeDescription'>"
                        + tCExecution.getResultMessage().getCode() + "</span></b></td></tr>");
                out.println("<tr><td>ReturnCodeDescription</td><td><b><span id='ReturnCodeDescription'>"
                        + tCExecution.getResultMessage().getDescription() + "</span></b></td></tr>");
                out.println("<tr><td>ControlStatus</td><td><b><span id='ReturnCodeMessage'>"
                        + tCExecution.getResultMessage().getCodeString() + "</span></b></td></tr>");
                out.println("<tr><td></td><td></td></tr>");
                out.println("</table><br><br>");
                out.println("<table border>");
                out.println("<tr>"
                        + "<td><input id=\"ButtonRetry\" type=\"button\" value=\"Retry\" onClick=\"window.location.reload()\"></td>"
                        + "<td><input id=\"ButtonBack\" type=\"button\" value=\"Go Back\" onClick=\"window.history.back()\"></td>"
                        + "<td><input id=\"ButtonOpenTC\" type=\"button\" value=\"Open Test Case\" onClick=\"window.open('TestCase.jsp?Test="
                        + test + "&TestCase=" + testCase + "&Load=Load')\"></td>" + "</tr>");
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
            }
        } else if (outputFormat.equalsIgnoreCase("verbose-txt")) {
            String separator = " = ";
            out.println("RunID" + separator + runID);
            out.println("Test" + separator + test);
            out.println("TestCase" + separator + testCase);
            out.println("Country" + separator + country);
            out.println("Environment" + separator + environment);
            out.println("Time Start" + separator + new Timestamp(tCExecution.getStart()));
            out.println("Time End" + separator + new Timestamp(tCExecution.getEnd()));
            out.println("OutputFormat" + separator + outputFormat);
            out.println("Verbose" + separator + verbose);
            out.println("Screenshot" + separator + screenshot);
            out.println("Robot" + separator + robot);
            out.println("Browser" + separator + browser);
            out.println("Version" + separator + version);
            out.println("Platform" + separator + platform);
            out.println("ManualURL" + separator + tCExecution.isManualURL());
            out.println("MyHost" + separator + tCExecution.getMyHost());
            out.println("MyContextRoot" + separator + tCExecution.getMyContextRoot());
            out.println("MyLoginRelativeURL" + separator + tCExecution.getMyLoginRelativeURL());
            out.println("myEnvironmentData" + separator + tCExecution.getEnvironmentData());
            out.println("ReturnCode" + separator + tCExecution.getResultMessage().getCode());
            out.println("ReturnCodeDescription" + separator + tCExecution.getResultMessage().getDescription());
            out.println("ControlStatus" + separator + tCExecution.getResultMessage().getCodeString());
        } else {
            DateFormat df = new SimpleDateFormat(DateUtil.DATE_FORMAT_DISPLAY);
            out.println(df.format(tCExecution.getStart()) + " - " + runID + " [" + test + "|" + testCase + "|"
                    + country + "|" + environment + "] : '" + tCExecution.getResultMessage().getCodeString()
                    + "' - " + tCExecution.getResultMessage().getCode() + " "
                    + tCExecution.getResultMessage().getDescription());
        }
    } else {
        // In case of errors, we display the help message.
        out.println(helpMessage);
    }

}

From source file:org.cerberus.servlet.testCase.ImportTestCaseFromJson.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w  w  .  ja v a 2  s  .  co m
 *
 * @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 {
    String test = "";
    String testcase = "";
    JSONObject jo = null;
    FileItem item = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();

                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equals("test")) {
                        test = item.getString("UTF-8");
                        System.out.println(test);
                    }
                    if (name.equals("testcase")) {
                        testcase = item.getString("UTF-8");
                        System.out.println(testcase);
                    }
                } else {
                    InputStream inputStream = item.getInputStream();

                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(inputStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;
                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }
                    inputStream.close();
                    streamReader.close();
                    jo = new JSONObject(responseStrBuilder.toString());

                }

            }

            ApplicationContext appContext = WebApplicationContextUtils
                    .getWebApplicationContext(this.getServletContext());
            ITestCaseService tcService = appContext.getBean(ITestCaseService.class);
            TestCase tcInfo = new TestCase();
            tcInfo.setTest(test);
            tcInfo.setTestCase(testcase);
            tcInfo.setOrigin(jo.getString("origin") == null ? "" : jo.getString("origin"));
            tcInfo.setImplementer(jo.getString("implementer") == null ? "123TOTO" : "1234TOTO");
            tcInfo.setDescription(jo.getString("description") == null ? "1293TOTO" : "12394TOTO");

            tcService.updateTestCaseInformation(tcInfo);

            response.sendRedirect("TestCase.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException ex) {
            Logger.getLogger(ImportTestCaseFromJson.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.cerberus.servlet.zzpublic.ResultCI.java

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());

    /**/*from  w  w  w  .j  a  va 2  s. c  o m*/
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createPublicCalls("/ResultCI", "CALL", "ResultCIV0 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 CI_OK_prio1 to CI_OK_prio4.\n"
            + "Formula used is the following :\n"
            + "Nb Exe Prio 1 testcases * CI_OK_prio1 + Nb Exe Prio 2 testcases * CI_OK_prio2 +\n"
            + "  Nb Exe Prio 3 testcases * CI_OK_prio3 + Nb Exe Prio 4 testcases * CI_OK_prio4\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("CI_OK_prio1", "").getValue());
            float pond2 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio2", "").getValue());
            float pond3 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio3", "").getValue());
            float pond4 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio4", "").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.createPublicCalls("/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) {
            MyLogger.log(ResultCI.class.getName(), org.apache.log4j.Level.WARN, e.toString());
        }
    }

}