List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext
@Nullable public static WebApplicationContext getWebApplicationContext(ServletContext sc)
From source file:org.cerberus.servlet.zzpublic.ResultCIV001.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS); response.setContentType("application/json"); response.setCharacterEncoding("utf8"); // Calling Servlet Transversal Util. ServletUtil.servletStart(request);/*from ww w . jav a 2s . c om*/ /** * Adding Log entry. */ ILogEventService logEventService = appContext.getBean(ILogEventService.class); logEventService.createPublicCalls("/ResultCIV001", "CALL", "ResultCIV001 called : " + request.getRequestURL(), request); try { JSONObject jsonResponse = new JSONObject(); String tag = policy.sanitize(request.getParameter("tag")); String helpMessage = "This servlet is used to provide a json object with various execution counters as well as a global OK or KO status based on the number and status of the execution done on a specific tag. " + "The number of executions are ponderated by parameters by priority from CI_OK_prio1 to CI_OK_prio4. " + "Formula used is the following : " + "Nb Exe Prio 1 testcases * CI_OK_prio1 + Nb Exe Prio 2 testcases * CI_OK_prio2 + " + "Nb Exe Prio 3 testcases * CI_OK_prio3 + Nb Exe Prio 4 testcases * CI_OK_prio4." + "If no executions are found, the result is KO." + "With at least 1 execution, if result is < 1 then global servlet result is OK. If not, it is KO." + "All execution needs to have a status equal to KO, FA, NA or PE." + "Parameter list :" + "- tag [mandatory] : Execution Tag to filter the test cases execution. [" + tag + "]"; boolean error = false; String error_message = ""; // Checking the parameter validity. Tag is a mandatory parameter if (StringUtils.isBlank(tag)) { error_message = "Error - Parameter tag is mandatory."; error = true; } if (!error) { ITestCaseExecutionService MyTestExecutionService = appContext .getBean(TestCaseExecutionService.class); List<TestCaseExecution> myList; int nbok = 0; int nbko = 0; int nbfa = 0; int nbpe = 0; int nbna = 0; int nbca = 0; int nbtotal = 0; int nbkop1 = 0; int nbkop2 = 0; int nbkop3 = 0; int nbkop4 = 0; String exeStart = ""; long longStart = 0; String exeEnd = ""; long longEnd = 0; try { myList = MyTestExecutionService.convert(MyTestExecutionService.readByTag(tag)); for (TestCaseExecution curExe : myList) { if (longStart == 0) { longStart = curExe.getStart(); } if (curExe.getStart() < longStart) { longStart = curExe.getStart(); } if (longEnd == 0) { longEnd = curExe.getEnd(); } if (curExe.getEnd() > longEnd) { longEnd = curExe.getEnd(); } nbtotal++; switch (curExe.getControlStatus()) { case TestCaseExecution.CONTROLSTATUS_KO: nbko++; break; case TestCaseExecution.CONTROLSTATUS_OK: nbok++; break; case TestCaseExecution.CONTROLSTATUS_FA: nbfa++; break; case TestCaseExecution.CONTROLSTATUS_NA: nbna++; break; case TestCaseExecution.CONTROLSTATUS_CA: nbca++; break; case TestCaseExecution.CONTROLSTATUS_PE: nbpe++; break; } if (!(curExe.getControlStatus().equals("OK"))) { switch (curExe.getTestCaseObj().getPriority()) { case 1: nbkop1++; break; case 2: nbkop2++; break; case 3: nbkop3++; break; case 4: nbkop4++; break; } } } } catch (CerberusException ex) { Logger.getLogger(ResultCIV001.class.getName()).log(Level.SEVERE, null, ex); } IParameterService parameterService = appContext.getBean(IParameterService.class); float pond1 = parameterService.getParameterFloatByKey("CI_OK_prio1", "", 0); float pond2 = parameterService.getParameterFloatByKey("CI_OK_prio2", "", 0); float pond3 = parameterService.getParameterFloatByKey("CI_OK_prio3", "", 0); float pond4 = parameterService.getParameterFloatByKey("CI_OK_prio4", "", 0); String result; float resultCal = (nbkop1 * pond1) + (nbkop2 * pond2) + (nbkop3 * pond3) + (nbkop4 * pond4); if ((resultCal < 1) && (nbtotal > 0)) { result = "OK"; } else { result = "KO"; } jsonResponse.put("messageType", "OK"); jsonResponse.put("message", "CI result calculated with success."); jsonResponse.put("CI_OK_prio1", pond1); jsonResponse.put("CI_OK_prio2", pond2); jsonResponse.put("CI_OK_prio3", pond3); jsonResponse.put("CI_OK_prio4", pond4); jsonResponse.put("CI_finalResult", resultCal); jsonResponse.put("NonOK_prio1_nbOfExecution", nbkop1); jsonResponse.put("NonOK_prio2_nbOfExecution", nbkop2); jsonResponse.put("NonOK_prio3_nbOfExecution", nbkop3); jsonResponse.put("NonOK_prio4_nbOfExecution", nbkop4); jsonResponse.put("status_OK_nbOfExecution", nbok); jsonResponse.put("status_KO_nbOfExecution", nbko); jsonResponse.put("status_FA_nbOfExecution", nbfa); jsonResponse.put("status_PE_nbOfExecution", nbpe); jsonResponse.put("status_NA_nbOfExecution", nbna); jsonResponse.put("status_CA_nbOfExecution", nbca); jsonResponse.put("TOTAL_nbOfExecution", nbtotal); jsonResponse.put("result", result); jsonResponse.put("ExecutionStart", String.valueOf(new Timestamp(longStart))); jsonResponse.put("ExecutionEnd", String.valueOf(new Timestamp(longEnd))); response.getWriter().print(jsonResponse.toString()); // Log the result with calculation detail. logEventService.createPublicCalls("/ResultCIV001", "CALLRESULT", "ResultCIV001 calculated with result [" + result + "] : " + nbkop1 + "*" + pond1 + " + " + nbkop2 + "*" + pond2 + " + " + nbkop3 + "*" + pond3 + " + " + nbkop4 + "*" + pond4 + " = " + resultCal, request); } else { jsonResponse.put("messageType", "KO"); jsonResponse.put("message", error_message); jsonResponse.put("helpMessage", helpMessage); response.getWriter().print(jsonResponse.toString()); } } catch (JSONException e) { org.apache.log4j.Logger.getLogger(ReadLogEvent.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.zzpublic.RunTestCase.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); /**// www . j av a 2 s. c o m * Adding Log entry. */ ILogEventService logEventService = appContext.getBean(ILogEventService.class); logEventService.createPublicCalls("/RunTestCase", "CALL", "RunTestCaseV0 called : " + request.getRequestURL(), request); //Tool String ss_ip = ""; // Selenium IP String ss_p = ""; // Selenium Port String browser = ""; String version = ""; String platform = ""; String robot = ""; String active = ""; String timeout = ""; String userAgent = ""; String screenSize = ""; boolean synchroneous = true; int getPageSource = 0; int getSeleniumLog = 0; boolean manualExecution = false; List<RobotCapability> capabilities = null; //Test String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Test"), ""); String testCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("TestCase"), ""); String country = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Country"), ""); String environment = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Environment"), ""); //Test Dev Environment boolean manualURL = ParameterParserUtil.parseBooleanParam(request.getParameter("manualURL"), false); String myHost = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("myhost"), ""); String myContextRoot = ParameterParserUtil .parseStringParamAndSanitize(request.getParameter("mycontextroot"), ""); String myLoginRelativeURL = ParameterParserUtil .parseStringParamAndSanitize(request.getParameter("myloginrelativeurl"), ""); //TODO find another solution myLoginRelativeURL = myLoginRelativeURL.replace("=", "="); String myEnvData = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("myenvdata"), ""); //Execution String tag = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Tag"), ""); String outputFormat = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("outputformat"), "compact"); int screenshot = ParameterParserUtil.parseIntegerParam(request.getParameter("screenshot"), 1); int verbose = ParameterParserUtil.parseIntegerParam(request.getParameter("verbose"), 0); timeout = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("timeout"), ""); synchroneous = ParameterParserUtil.parseBooleanParam(request.getParameter("synchroneous"), true); getPageSource = ParameterParserUtil.parseIntegerParam(request.getParameter("pageSource"), 1); getSeleniumLog = ParameterParserUtil.parseIntegerParam(request.getParameter("seleniumLog"), 1); manualExecution = ParameterParserUtil.parseBooleanParam(request.getParameter("manualExecution"), false); long idFromQueue = ParameterParserUtil.parseIntegerParam(request.getParameter("IdFromQueue"), 0); int numberOfRetries = ParameterParserUtil.parseIntegerParam(request.getParameter("retries"), 0); screenSize = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("screenSize"), ""); robot = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("robot"), ""); ss_ip = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("ss_ip"), ""); ss_p = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("ss_p"), ""); if (request.getParameter("Browser") != null && !"".equals(request.getParameter("Browser"))) { browser = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("Browser"), "firefox"); } else { browser = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("browser"), "firefox"); } version = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("version"), ""); platform = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("platform"), ""); 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 : Environment where the test case will execute. This parameter is mandatory only if manualURL is not set to Y. [" + 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. (Can be overwriten if robot is defined) [" + ss_ip + "]\n" + "- ss_p : Port of the Robot. (Can be overwriten if robot is defined) [" + ss_p + "]\n" + "- browser : Browser to use for the execution. (Can be overwriten if robot is defined) [" + browser + "]\n" + "- version : Version to use for the execution. (Can be overwriten if robot is defined) [" + version + "]\n" + "- platform : Platform to use for the execution. (Can be overwriten if robot is defined) [" + platform + "]\n" + "- screenSize : Size of the screen to set for the execution. [" + screenSize + "]\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 (only used when manualURL is feed). [" + myHost + "]\n" + "- mycontextroot : Context root of the application to test (only used when manualURL is feed). [" + myContextRoot + "]\n" + "- myloginrelativeurl : Relative login URL of the application (only used when manualURL is feed). [" + myLoginRelativeURL + "]\n" + "- myenvdata : Environment where to get the test data when a manualURL is defined. (only used when manualURL is feed) [" + myEnvData + "]\n" + "- Tag : Tag that will be stored on the execution. [" + StringEscapeUtils.escapeHtml4(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" + "- timeout : Timeout used for the action. If empty, the default value will be the one configured in parameter table. [" + timeout + "]\n" + "- synchroneous : Synchroneous define if the servlet wait for the end of the execution to report its execution. [" + synchroneous + "\n" + "- pageSource : Record Page Source during the execution. [" + getPageSource + "]\n" + "- seleniumLog : Get the SeleniumLog at the end of the execution. [" + getSeleniumLog + "]\n" + "- manualExecution : Execute testcase in manual mode. [" + manualExecution + "]\n" + "- retries : Number of tries if the result is not OK. [" + numberOfRetries + "]\n"; boolean error = false; // -- Checking the parameter validity. -- // test, testcase and country parameters are mandatory 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; } // environment is mandatory when manualURL is not activated. if (StringUtils.isBlank(environment) && !manualURL) { out.println("Error - Parameter environment is mandatory (or use the manualURL parameter)."); error = true; } // We check that execution is not desactivated by cerberus_automaticexecution_enable parameter. IParameterService parameterService = appContext.getBean(IParameterService.class); try { if (!("Y".equals( parameterService.findParameterByKey("cerberus_automaticexecution_enable", "").getValue()))) { out.println( "Error - Execution disable by configuration (cerberus_automaticexecution_enable <> Y)."); error = true; LOG.info("Execution request ignored by cerberus_automaticexecution_enable parameter. " + test + " / " + testCase); } } catch (CerberusException ex) { LOG.error( "Parameter cerberus_automaticexecution_enable not found on Cerberus database. Please make sure database is up to date."); } // If Robot is feeded, we check it exist. If it exist, we overwrite the associated parameters. if (!"".equals(robot)) { IRobotService robotService = appContext.getBean(IRobotService.class); try { Robot robObj = robotService.convert(robotService.readByKey(robot)); // If Robot parameter is defined and we can find the robot, we overwrite the corresponding parameters. ss_ip = ParameterParserUtil.parseStringParam(robObj.getHost(), ss_ip); ss_p = ParameterParserUtil.parseStringParam(String.valueOf(robObj.getPort()), ss_p); browser = ParameterParserUtil.parseStringParam(robObj.getBrowser(), browser); version = ParameterParserUtil.parseStringParam(robObj.getVersion(), version); platform = ParameterParserUtil.parseStringParam(robObj.getPlatform(), platform); active = robObj.getActive(); userAgent = robObj.getUserAgent(); capabilities = robObj.getCapabilities(); screenSize = robObj.getScreenSize(); } catch (CerberusException ex) { out.println("Error - Robot [" + robot + "] does not exist."); error = true; } } // We cannot execute a testcase on a desactivated Robot. if (active.equals("N")) { out.println("Error - Robot is not Active."); error = true; } //verify the format of the ScreenSize. It must be 2 integer separated by a *. For example : 1024*768 if (!"".equals(screenSize)) { if (!screenSize.contains("*")) { out.println("Error - ScreenSize format is not Correct. It must be 2 Integer separated by a *."); error = true; } else { try { String screenWidth = screenSize.split("\\*")[0]; String screenLength = screenSize.split("\\*")[1]; Integer.parseInt(screenWidth); Integer.parseInt(screenLength); } catch (Exception e) { out.println("Error - ScreenSize format is not Correct. It must be 2 Integer separated by a *."); error = true; } } } if (!error) { //check if the test case is to be executed in the specific parameters boolean exists = false; try { ITestCaseCountryService tccService = appContext.getBean(ITestCaseCountryService.class); TestCaseCountry tcc = tccService.findTestCaseCountryByKey(test, testCase, country); if (tcc != null) { exists = true; } } catch (CerberusException ex) { response.setContentType("text/plain"); DateFormat df = new SimpleDateFormat(DateUtil.DATE_FORMAT_DISPLAY); String errorMessage = df.format(new Date()) + " - " + 0 + " [" + test + "|" + testCase + "|" + country + "|" + environment + "] : Test Case is not selected for country!' "; out.println(errorMessage); } //there is no need to lauch the execution if the test case does not exist for the country if (exists) { //TODO:FN debug messages to be removed LOG.debug("STARTED: Test " + test + "-" + testCase); IRunTestCaseService runTestCaseService = appContext.getBean(IRunTestCaseService.class); IFactoryTestCase factoryTCase = appContext.getBean(IFactoryTestCase.class); IFactoryTestCaseExecution factoryTCExecution = appContext.getBean(IFactoryTestCaseExecution.class); ITestCaseExecutionService tces = appContext.getBean(ITestCaseExecutionService.class); TestCase tCase = factoryTCase.create(test, testCase); TestCaseExecution tCExecution = factoryTCExecution.create(0, test, testCase, null, null, environment, myEnvData, country, browser, version, platform, "", 0, 0, "", "", null, ss_ip, null, ss_p, tag, "N", verbose, screenshot, getPageSource, getSeleniumLog, synchroneous, timeout, outputFormat, null, Infos.getInstance().getProjectNameAndVersion(), tCase, null, null, manualURL, myHost, myContextRoot, myLoginRelativeURL, myEnvData, ss_ip, ss_p, null, new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_TESTSTARTED), "Selenium", numberOfRetries, screenSize, capabilities, "", "", "", "", "", manualExecution); /** * Set UserAgent */ tCExecution.setUserAgent(userAgent); /** * Set UUID */ ExecutionUUID executionUUIDObject = appContext.getBean(ExecutionUUID.class); UUID executionUUID = UUID.randomUUID(); executionUUIDObject.setExecutionUUID(executionUUID.toString(), tCExecution); tCExecution.setExecutionUUID(executionUUID.toString()); LOG.info("Execution Requested : UUID=" + executionUUID); /** * Set IdFromQueue */ tCExecution.setIdFromQueue(idFromQueue); /** * Loop on the execution of the testcase until we get an OK or * reached the number of retries. */ //while (tCExecution.getNumberOfRetries() >= 0 && !tCExecution.getResultMessage().getCodeString().equals("OK")) { try { LOG.debug("Start execution " + tCExecution.getId()); tCExecution = runTestCaseService.runTestCase(tCExecution); // tCExecution.decreaseNumberOfRetries(); } catch (Exception ex) { LOG.error("Error while executing RunTestCase ", ex); // break; } // } /** * If execution happened, we Log the Execution. */ if (tCExecution.getId() != 0) { TestCaseExecution t = (TestCaseExecution) tces.readByKeyWithDependency(tCExecution.getId()) .getItem(); LOG.info("CerberusExecution " + t.toJson()); } /** * Clean memory in case testcase has not been launched(Remove * all object put in memory) */ try { if (tCExecution.getId() == 0) { executionUUIDObject.removeExecutionUUID(tCExecution.getExecutionUUID()); LOG.debug("Clean ExecutionUUID"); } } catch (Exception ex) { LOG.error("Exception cleaning Memory: ", ex); } /** * Execution is finished we report the result. */ long runID = tCExecution.getId(); if (outputFormat.equalsIgnoreCase("gui")) { // HTML GUI output. either the detailed execution page or an error page when the execution is not created. if (runID > 0) { // Execution has been created. AnswerItem a = parameterService.readByKey("", "cerberus_executiondetail_use"); if (a.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && a.getItem() != null) { Parameter p = (Parameter) a.getItem(); if (!p.getValue().equals("N")) { response.sendRedirect("ExecutionDetail2.jsp?executionId=" + runID); } else { response.sendRedirect("ExecutionDetail.jsp?id_tc=" + runID); } } else { response.sendRedirect("ExecutionDetail.jsp?id_tc=" + runID); } } else { // Execution was not even created. response.setContentType("text/html"); 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>IdFromQueue</td><td><b><span id='IdFromQueue'>" + tCExecution.getIdFromQueue() + "</span></b></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>PageSource</td><td><span id='PageSource'>" + getPageSource + "</span></td></tr>"); out.println("<tr><td>SeleniumLog</td><td><span id='SeleniumLog'>" + getSeleniumLog + "</span></td></tr>"); out.println("<tr><td>Robot</td><td><span id='Robot'>" + robot + "</span></td></tr>"); out.println("<tr><td>Selenium Server IP</td><td><span id='SeleniumIP'>" + ss_ip + "</span></td></tr>"); out.println("<tr><td>Selenium Server Port</td><td><span id='SeleniumPort'>" + ss_p + "</span></td></tr>"); out.println("<tr><td>Timeout</td><td><span id='Timeout'>" + timeout + "</span></td></tr>"); out.println("<tr><td>Synchroneous</td><td><span id='Synchroneous'>" + synchroneous + "</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='Version'>" + version + "</span></td></tr>"); out.println( "<tr><td>Platform</td><td><span id='Platform'>" + platform + "</span></td></tr>"); out.println("<tr><td>Screen Size</td><td><span id='screenSize'>" + screenSize + "</span></td></tr>"); out.println("<tr><td>Number of Retry</td><td><span id='nbretry'>" + numberOfRetries + "</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('TestCaseScript.jsp?test=" + test + "&testcase=" + testCase + "')\"></td>" + "</tr>"); out.println("</table>"); out.println("</body>"); out.println("</html>"); } } else if (outputFormat.equalsIgnoreCase("redirectToReport")) { // Redirect to the reporting page by tag. response.sendRedirect( "./ReportingExecutionByTag.jsp?Tag=" + StringUtil.encodeAsJavaScriptURIComponent(tag)); } else if (outputFormat.equalsIgnoreCase("verbose-txt")) { // Text verbose output. response.setContentType("text/plain"); 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("PageSource" + separator + getPageSource); out.println("SeleniumLog" + separator + getSeleniumLog); out.println("Robot" + separator + robot); out.println("Selenium Server IP" + separator + ss_ip); out.println("Selenium Server Port" + separator + ss_p); out.println("Timeout" + separator + timeout); out.println("Synchroneous" + separator + synchroneous); out.println("Browser" + separator + browser); out.println("Version" + separator + version); out.println("Platform" + separator + platform); out.println("ScreenSize" + separator + screenSize); out.println("Nb Of Retry" + separator + numberOfRetries); 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 { // Default behaviour when not outputformat is defined : compact mode. response.setContentType("text/plain"); 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.codehaus.groovy.grails.web.binding.GrailsDataBinder.java
/** * Collects all PropertyEditorRegistrars in the application context and * calls them to register their custom editors * * @param servletContext/* w ww . j av a2 s . c o m*/ * @param registry The PropertyEditorRegistry instance */ private static void registerCustomEditors(ServletContext servletContext, PropertyEditorRegistry registry) { if (servletContext == null) { return; } WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); if (context == null) { return; } @SuppressWarnings("unchecked") Map<String, PropertyEditorRegistrar> editors = (Map<String, PropertyEditorRegistrar>) servletContext .getAttribute(PROPERTY_EDITOR_REGISTRARS); if (editors == null) { editors = context.getBeansOfType(PropertyEditorRegistrar.class); if (!Environment.isDevelopmentMode()) { servletContext.setAttribute(PROPERTY_EDITOR_REGISTRARS, editors); } } for (PropertyEditorRegistrar editorRegistrar : editors.values()) { editorRegistrar.registerCustomEditors(registry); } }
From source file:org.codehaus.groovy.grails.web.context.GrailsContextLoader.java
@Override public void closeWebApplicationContext(ServletContext servletContext) { // clean up in war mode, in run-app these references may be needed again if (application == null || !application.isWarDeployed()) { return;/*from w w w . j av a2 s. c om*/ } WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); ConfigurableApplicationContext parent = ctx != null ? (ConfigurableApplicationContext) ctx.getParent() : null; try { super.closeWebApplicationContext(servletContext); } finally { ShutdownOperations.runOperations(); } if (parent != null) { LOG.info("Destroying Spring parent WebApplicationContext " + parent.getDisplayName()); parent.close(); } try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } catch (AccessControlException e) { // container doesn't allow, probably related to WAR deployment on AppEngine. proceed. } application = null; }
From source file:org.codehaus.groovy.grails.web.util.WebUtils.java
/** * Locates the ApplicationContext, returns null if not found * @param servletContext The servlet context * @return The ApplicationContext//from www. ja v a2 s .com */ public static ApplicationContext findApplicationContext(ServletContext servletContext) { return WebApplicationContextUtils.getWebApplicationContext(servletContext); }
From source file:org.codemine.smartgarden.controller.SmartGardenServlet.java
private DataSource getDataSource() { try {/*from w w w . j av a2 s.co m*/ ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); DataSource dataSource = (DataSource) appContext.getBean("dataSource"); return dataSource; } catch (Throwable ex) { Logger.getLogger(SmartGardenServlet.class.getName()).log(Level.ERROR, null, ex); } return null; }
From source file:org.easyrec.servlet.PluginStarter.java
private void initialize() { ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); this.tenantService = context.getBean("tenantService", TenantService.class); this.remoteTenantDAO = context.getBean("remoteTenantDAO", RemoteTenantDAO.class); this.remoteTenantService = context.getBean("remoteTenantService", RemoteTenantService.class); this.shopRecommenderService = context.getBean("shopRecommenderService", ShopRecommenderService.class); this.easyrecSettings = context.getBean("easyrecSettings", EasyRecSettings.class); this.pluginRegistry = context.getBean("pluginRegistry", PluginRegistry.class); this.generatorContainer = context.getBean("generatorContainer", GeneratorContainer.class); this.logEntryDAO = context.getBean("logEntryDAO", LogEntryDAO.class); initialized = true;//from w w w .j a v a 2 s . c o m }
From source file:org.egov.collection.web.actions.receipts.AjaxReceiptCreateAction.java
/** * This method is accessed from challan.js and MiscReceipts.js * * @return/* w w w . ja v a 2 s . c o m*/ * @throws Exception */ @Action(value = "/receipts/ajaxReceiptCreate-ajaxValidateDetailCodeNew") public String ajaxValidateDetailCodeNew() throws Exception { final String code = parameters.get("code")[0]; final String index = parameters.get(INDEX)[0]; final String codeorname = parameters.get("codeorname")[0]; final Accountdetailtype adt = (Accountdetailtype) getPersistenceService().find(accountDetailTypeQuery, Integer.valueOf(parameters.get(DETAILTYPEID)[0])); if (adt == null) { value = index + "~" + ERROR + "#"; return RESULT; } final String table = adt.getFullQualifiedName(); final Class<?> service = Class.forName(table); String simpleName = service.getSimpleName(); simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1) + "Service"; final WebApplicationContext wac = WebApplicationContextUtils .getWebApplicationContext(ServletActionContext.getServletContext()); final EntityTypeService entityService = (EntityTypeService) wac.getBean(simpleName); entityList = (List<EntityType>) entityService.filterActiveEntities(code, 10, adt.getId()); if (entityList == null || entityList.isEmpty()) value = index + "~" + ERROR + "#"; else { if (entityList.size() > 1) {// To Check with same code/name if more than one entity is returned value = index + "~" + ERROR + "#"; return RESULT; } for (final EntityType entity : entityList) if (entity == null) { value = index + "~" + ERROR + "#"; break; } else if (codeorname.equalsIgnoreCase("both")) {// To Check if // both name // and code has // to be // compared if (entity.getName().equals(code) || entity.getCode().equals(code)) { value = index + "~" + entity.getEntityId() + "~" + entity.getName() + "~" + entity.getCode(); break; } else value = index + "~" + ERROR + "#"; } else if (entity.getCode().equals(code)) {// In case of view // mode, to get the // details from the // code value = index + "~" + entity.getEntityId() + "~" + entity.getName() + "~" + entity.getCode(); break; } else value = index + "~" + ERROR + "#"; } return RESULT; }
From source file:org.egov.collection.web.actions.receipts.AjaxReceiptCreateAction.java
@Action(value = "/receipts/ajaxReceiptCreate-getCodeNew") public String getCodeNew() throws Exception { value = "";/* www . jav a2s . c om*/ final String detailTypeId = parameters.get("detailTypeId")[0]; final String filterKey = parameters.get("filterKey")[0]; final Integer accountDetailTypeId = Integer.valueOf(detailTypeId); final Accountdetailtype adt = (Accountdetailtype) getPersistenceService().find(accountDetailTypeQuery, accountDetailTypeId); if (adt == null) return RESULT; final String table = adt.getFullQualifiedName(); final Class<?> service = Class.forName(table); String simpleName = service.getSimpleName(); simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1) + "Service"; final WebApplicationContext wac = WebApplicationContextUtils .getWebApplicationContext(ServletActionContext.getServletContext()); final EntityTypeService entityService = (EntityTypeService) wac.getBean(simpleName); final List<EntityType> tempEntityList = (List<EntityType>) entityService.filterActiveEntities(filterKey, -1, adt.getId()); entityList = new ArrayList<EntityType>(); for (final EntityType e : tempEntityList) { if (e.getName().contains("@") || e.getName().contains("#") || e.getName().contains("$") || e.getName().contains("%") || e.getName().contains("^") || e.getName().contains("&") || e.getName().contains("*")) e.getName().replace("@", " ").replace("#", " ").replace("$", " ").replace("%", " ") .replace("^", " ").replace("&", " ").replace("*", " "); entityList.add(e); } return "entities"; }
From source file:org.egov.egf.web.actions.payment.DirectBankPaymentAction.java
@ValidationErrorPage(value = NEW) @SkipValidation//from w w w .j a va 2 s. com public String nonBillPayment() { voucherHeader = persistenceService.getSession().load(CVoucherHeader.class, voucherHeader.getId()); final String vName = voucherHeader.getName(); String appconfigKey = ""; if (vName.equalsIgnoreCase(FinancialConstants.JOURNALVOUCHER_NAME_CONTRACTORJOURNAL)) appconfigKey = "worksBillPurposeIds"; else if (vName.equalsIgnoreCase(FinancialConstants.JOURNALVOUCHER_NAME_SUPPLIERJOURNAL)) appconfigKey = "purchaseBillPurposeIds"; else if (vName.equalsIgnoreCase(FinancialConstants.JOURNALVOUCHER_NAME_SALARYJOURNAL)) appconfigKey = "salaryBillPurposeIds"; final AppConfigValues appConfigValues = appConfigValuesService .getConfigValuesByModuleAndKey(FinancialConstants.MODULE_NAME_APPCONFIG, appconfigKey).get(0); final String purposeValue = appConfigValues.getValue(); final CGeneralLedger netPay = (CGeneralLedger) persistenceService.find( "from CGeneralLedger where voucherHeaderId.id=? and glcodeId.purposeId=?", voucherHeader.getId(), purposeValue); if (netPay == null) throw new ValidationException(Arrays.asList(new ValidationError( "net.payable.not.selected.or.selected.wrongly", "Either Net payable code is not selected or wrongly selected in voucher .Payment creation Failed"))); billDetailslist = new ArrayList<VoucherDetails>(); subLedgerlist = new ArrayList<VoucherDetails>(); final VoucherDetails vd = new VoucherDetails(); vd.setGlcodeDetail(netPay.getGlcode()); vd.setGlcodeIdDetail(netPay.getGlcodeId().getId()); vd.setAccounthead(netPay.getGlcodeId().getName()); vd.setDebitAmountDetail(BigDecimal.valueOf(netPay.getCreditAmount())); if (netPay.getFunctionId() != null) { vd.setFunctionIdDetail(Long.valueOf(netPay.getFunctionId())); final CFunction function = persistenceService.getSession().load(CFunction.class, Long.valueOf(netPay.getFunctionId())); vd.setFunctionDetail(function.getId().toString()); } commonBean.setAmount(BigDecimal.valueOf(netPay.getCreditAmount())); billDetailslist.add(vd); final Set<CGeneralLedgerDetail> generalLedgerDetails = netPay.getGeneralLedgerDetails(); final int i = 0; for (final CGeneralLedgerDetail gldetail : generalLedgerDetails) { final VoucherDetails vdetails = new VoucherDetails(); vdetails.setSubledgerCode(netPay.getGlcode()); vdetails.setAmount(gldetail.getAmount()); // vdetails.setDebitAmountDetail(vdetails.getAmount()); vdetails.setGlcodeDetail(netPay.getGlcode()); vdetails.setGlcode(netPay.getGlcodeId()); vdetails.setSubledgerCode(netPay.getGlcode()); vdetails.setAccounthead(netPay.getGlcodeId().getName()); final Accountdetailtype detailType = persistenceService.getSession().load(Accountdetailtype.class, gldetail.getDetailTypeId()); vdetails.setDetailTypeName(detailType.getName()); vdetails.setDetailType(detailType); vdetails.setDetailKey(gldetail.getDetailKeyId().toString()); vdetails.setDetailKeyId(gldetail.getDetailKeyId()); final String table = detailType.getFullQualifiedName(); Class<?> service; try { service = Class.forName(table); } catch (final ClassNotFoundException e1) { LOGGER.error(e1.getMessage(), e1); throw new ValidationException( Arrays.asList(new ValidationError("application.error", "application.error"))); } String simpleName = service.getSimpleName(); // simpleName=simpleName.toLowerCase()+"Service"; simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1) + "Service"; final WebApplicationContext wac = WebApplicationContextUtils .getWebApplicationContext(ServletActionContext.getServletContext()); final PersistenceService entityPersistenceService = (PersistenceService) wac.getBean(simpleName); String dataType = ""; try { final Class aClass = Class.forName(table); final java.lang.reflect.Method method = aClass.getMethod("getId"); dataType = method.getReturnType().getSimpleName(); } catch (final Exception e) { throw new ApplicationRuntimeException(e.getMessage()); } EntityType entity = null; if (dataType.equals("Long")) entity = (EntityType) entityPersistenceService .findById(Long.valueOf(gldetail.getDetailKeyId().toString()), false); else entity = (EntityType) entityPersistenceService.findById(gldetail.getDetailKeyId(), false); vdetails.setDetailCode(entity.getCode()); vdetails.setDetailName(entity.getName()); vdetails.setDetailKey(entity.getName()); if (i == 0) commonBean.setPaidTo(entity.getName()); subLedgerlist.add(vdetails); } if (subLedgerlist.size() == 0) subLedgerlist.add(new VoucherDetails()); loadAjaxedDropDowns(); return NEW; }