List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext
@Nullable public static WebApplicationContext getWebApplicationContext(ServletContext sc)
From source file:org.openmeetings.servlet.outputhandler.CalendarServlet.java
public TimezoneUtil getTimezoneUtil() { try {/*from w w w. j a v a 2s.c om*/ if (ScopeApplicationAdapter.initComplete) { ApplicationContext context = WebApplicationContextUtils .getWebApplicationContext(getServletContext()); return (TimezoneUtil) context.getBean("timezoneUtil"); } } catch (Exception err) { log.error("[getTimezoneUtil]", err); } return null; }
From source file:com.ewcms.component.rss.web.RssServlet.java
private RssService getRssService() { ServletContext application = getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application); return (RssService) wac.getBean("rssService"); }
From source file:com.mothsoft.alexis.web.ChartServlet.java
private void doLineGraph(final HttpServletRequest request, final HttpServletResponse response, final String title, final String[] dataSetIds, final Integer width, final Integer height, final Integer numberOfSamples) throws ServletException, IOException { final DataSetService dataSetService = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()).getBean(DataSetService.class); final OutputStream out = response.getOutputStream(); response.setContentType("image/png"); response.setHeader("Cache-Control", "max-age: 5; must-revalidate"); final XYSeriesCollection seriesCollection = new XYSeriesCollection(); final DateAxis dateAxis = new DateAxis(title != null ? title : "Time"); final DateTickUnit unit = new DateTickUnit(DateTickUnit.HOUR, 1); final DateFormat chartFormatter = new SimpleDateFormat("ha"); dateAxis.setDateFormatOverride(chartFormatter); dateAxis.setTickUnit(unit);//ww w. j a va 2 s .c o m dateAxis.setLabelFont(DEFAULT_FONT); dateAxis.setTickLabelFont(DEFAULT_FONT); if (numberOfSamples > 12) { dateAxis.setTickLabelFont( new Font(DEFAULT_FONT.getFamily(), Font.PLAIN, (int) (DEFAULT_FONT.getSize() * .8))); } final NumberAxis yAxis = new NumberAxis("Activity"); final StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES); int colorCounter = 0; if (dataSetIds != null) { for (final String dataSetIdString : dataSetIds) { final Long dataSetId = Long.valueOf(dataSetIdString); final DataSet dataSet = dataSetService.get(dataSetId); // go back for numberOfSamples, but include current hour final Calendar calendar = new GregorianCalendar(); calendar.add(Calendar.HOUR_OF_DAY, -1 * (numberOfSamples - 1)); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); final Timestamp startDate = new Timestamp(calendar.getTimeInMillis()); calendar.add(Calendar.HOUR_OF_DAY, numberOfSamples); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); final Timestamp endDate = new Timestamp(calendar.getTimeInMillis()); logger.debug(String.format("Generating chart for period: %s to %s", startDate.toString(), endDate.toString())); final List<DataSetPoint> dataSetPoints = dataSetService .findAndAggregatePointsGroupedByUnit(dataSetId, startDate, endDate, TimeUnits.HOUR); final boolean hasData = addSeries(seriesCollection, dataSet.getName(), dataSetPoints, startDate, numberOfSamples, renderer); if (dataSet.isAggregate()) { renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, Color.BLACK); } else if (hasData) { renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, PAINTS[colorCounter++ % PAINTS.length]); } else { renderer.setSeriesPaint(seriesCollection.getSeriesCount() - 1, Color.LIGHT_GRAY); } } } final XYPlot plot = new XYPlot(seriesCollection, dateAxis, yAxis, renderer); // create the chart... final JFreeChart chart = new JFreeChart(plot); // set the background color for the chart... chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customisation... plot.setBackgroundPaint(new Color(253, 253, 253)); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); // set the range axis to display integers only... final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setLabelFont(DEFAULT_FONT); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setLowerBound(0.00d); ChartUtilities.writeChartAsPNG(out, chart, width, height); }
From source file:jp.terasoluna.fw.web.thin.AbstractControlFilter.java
/** * DIReiRg??[CX^X?B//from w w w . j a va 2 s . co m * * @return E Rg??[CX^X */ @SuppressWarnings("unchecked") protected E getController() { if (log.isDebugEnabled()) { log.debug("setController() called."); } // WebApplicationContext WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); // tB^?p??[^Bean`t@C // id?n String controllerId = config.getInitParameter("controller"); if (controllerId == null || "".equals(controllerId)) { if (log.isDebugEnabled()) { log.debug("init parameter 'controller' isn't defined or " + "empty"); } controllerId = getDefaultControllerBeanId(); } // Rg??[`bean id\ if (log.isDebugEnabled()) { log.debug("controller bean id = \"" + controllerId + "\""); } // DIReiRg??[CX^X E controller = null; try { controller = (E) wac.getBean(controllerId, getControllerClass()); } catch (NoSuchBeanDefinitionException e) { // Bean`t@CwBean`?? log.error("not found " + controllerId + ". " + "controller bean not defined in Beans definition file.", e); throw new SystemException(e, getErrorCode()); } catch (BeanNotOfRequiredTypeException e) { // Bean`t@CwBean?AwNX // qNX?? log.error("controller not implemented " + getControllerClass().toString() + ".", e); throw new SystemException(e, getErrorCode()); } catch (BeansException e) { // CX^X??s?? log.error("bean generation failed.", e); throw new SystemException(e, getErrorCode()); } return controller; }
From source file:com.ewcms.web.pubsub.MessageSender.java
private MessageFacable getMessageFac(ServletContext context) { ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context); Assert.notNull(applicationContext, "Can not get spring's context"); MessageFacable fac = applicationContext.getBean("messageFac", MessageFacable.class); Assert.notNull(fac, "Can not get messageFac"); return fac;//w w w .j av a 2 s. co m }
From source file:com.jaspersoft.jasperserver.war.themes.ThemeResolverServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); servletContext = config.getServletContext(); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); themeCache = (ThemeCache) ctx.getBean("themeCache"); String value = config.getInitParameter(EXPIRES_AFTER_ACCESS_IN_SECS); try {//from ww w.j a v a2 s. c o m expiresInSecs = Integer.parseInt(value); log.debug("Expires in seconds set : " + expiresInSecs); } catch (Exception ex) { log.error(EXPIRES_AFTER_ACCESS_IN_SECS + " should be a non-negative integer", ex); } }
From source file:net.naijatek.myalumni.modules.common.presentation.action.SecurityAction.java
public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(false); Integer counter = (Integer) session.getAttribute("loginCounter"); int loginCounter = 0; String currentIP = request.getRemoteAddr(); ActionMessages errors = new ActionMessages(); LoginForm loginForm = (LoginForm) form; String username = loginForm.getMemberUserName(); String password = loginForm.getMemberPassword(); MemberVO token = null;//from w w w . ja va 2s.c o m LoginHistoryVO accessHistory = null; ServletContext sCtx = request.getSession().getServletContext(); WebApplicationContext wCtx = WebApplicationContextUtils.getWebApplicationContext(sCtx); MyAlumniUserContainer container = (MyAlumniUserContainer) wCtx.getBean("userContainer"); logger.info("Login attempt --> , [ " + username + " ][ " + currentIP + "]"); if (counter == null) { session.setAttribute("loginCounter", new Integer(loginCounter)); session.setAttribute("loginUserCounter", username); } else { loginCounter = counter.intValue(); } // login and store it in the session accessHistory = createAccessHistory(request, username); try { token = securityService.login(username, password, currentIP); token.setLoginSuccessfull(true); accessHistory.setLoginStatus(BaseConstants.LOGIN_PASS); accessHistory.setReasonCode(ReasonCodes.SUCCESS); // Prompt user to change password if (token.getPromptChange().equals(BaseConstants.BOOLEAN_YES)) { loginForm.setMemberUserName(token.getMemberUserName()); loginForm.setMemberPassword(""); loginForm.setMemberTempPassword(""); loginForm.setMemberPasswordConfirm(""); session.invalidate(); errors.add(BaseConstants.INFO_KEY, new ActionMessage("errors.login.resetpassword")); saveMessages(request, errors); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.CHANGE_PASSWORD); securityService.addAccessTrail(accessHistory); return mapping.findForward(BaseConstants.FWD_EXPIRED_PASSWORD); } // Cant find roles if (token.getIsAdmin() == null || (!token.getIsAdmin().equals(BaseConstants.BOOLEAN_NO) & !token.getIsAdmin().equals(BaseConstants.BOOLEAN_YES))) { errors.add(BaseConstants.ERROR_KEY, new ActionMessage("errors.login.role")); saveMessages(request, errors); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.NO_ROLES_FOUND); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } } catch (UserAccountException e) { //token.setLoginSuccessfull(false); if (e.getExceptionReason() == NotLoginException.ACCOUNT_DEACTIVATED) { session.invalidate(); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.deactivated")); saveMessages(request, errors); logger.info("ACCOUNT DEACTIVATED : " + username); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_DEACTIVATED); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } if (e.getExceptionReason() == NotLoginException.ACCOUNT_DELETED) { session.invalidate(); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.deleted")); saveMessages(request, errors); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_DELETED); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } if (e.getExceptionReason() == NotLoginException.ACCOUNT_LOCKED) { session.invalidate(); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.locked")); saveMessages(request, errors); logger.info("ACCOUNT LOCKED : " + username); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_LOCKED); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } else if (e.getExceptionReason() == NotLoginException.WRONG_PASSWORD) { //session.invalidate(); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.password.mismatch", currentIP)); saveMessages(request, errors); logger.info("INVALID PASSWORD : " + username); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.INVALID_CREDENTIAL); // increment failed login counter // if the same user contineously try to login , counter increases // if a diff user from the prev user, but same session, counter resets if (username.equals(session.getAttribute("loginUserCounter"))) { loginCounter++; } else { loginCounter = 0; session.setAttribute("loginCounter", new Integer(loginCounter)); } // Maximum number of time a user can try to login unsuccessfully int userMaxLogin = Integer.parseInt(getSysProp().getValue("USER_MAX_LOGIN")); if (loginCounter >= userMaxLogin) { logger.warn(username + " : User has exceeded maximum number of login attempts"); logger.warn("User account has been disabled. Please contact System Administrator"); // deactivating user account if (securityService.lockMemberAccount(username)) { session.invalidate(); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.locked")); logger.info("ACCOUNT LOCKED : IP: (" + currentIP + ") " + username); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_LOCKED); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } } else { session.setAttribute("loginCounter", new Integer(loginCounter)); } securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } else if (e.getExceptionReason() == NotLoginException.WRONG_USERNAME) { logger.info("INVALID USERNAME: IP: (" + currentIP + ") " + username + " User login attempt has failed. Count = " + loginCounter); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_INVALID); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.password.mismatch")); saveMessages(request, errors); logger.info("UNSUCCESSFULL FWD_LOGIN - Invalid login IP: (" + currentIP + ") " + username); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.INVALID_CREDENTIAL); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } else if (e.getExceptionReason() == NotLoginException.ACCOUNT_UNAPPROVED) { errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.notapproved")); saveMessages(request, errors); logger.info("UNSUCCESSFULL FWD_LOGIN - Account not approved yet. : IP: (" + currentIP + ") " + username); accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_UNAPPROVED); securityService.addAccessTrail(accessHistory); return mapping.getInputForward(); } } if (token.isLoginSuccessfull()) { //clear out any old session info session = request.getSession(false); if (session != null) { session.invalidate(); } // Create a new session for this user session = request.getSession(true); // place users container in session container.setToken(token); setSessionUserContainer(request, container); setupOtherTasks(request, container, token); int sessionTimeout = setupSessionTimeout(session); // adding the user user the list of online users token.setLastRequestTime(new Date()); OnlineUserManager manager = OnlineUserManager.getInstance(); manager.addOnlineUser(token, sessionTimeout); //sCtx.setAttribute("onlineusers", manager.getOnlineUsers(sessionTimeout)); setServletContextObject(request, "onlineusers", manager.getOnlineUsers(sessionTimeout)); session.setAttribute(BaseConstants.IS_ONLINE, BaseConstants.BOOLEAN_YES); session.setAttribute(BaseConstants.IS_ADMIN, token.getIsAdmin()); // ADMIN String context = request.getPathInfo(); if (context.startsWith("/admin/") && token.getIsAdmin().equals(BaseConstants.BOOLEAN_YES)) { setupAdminDesktop(request, memService, classNewsService, privateMessageService); securityService.addAccessTrail(accessHistory); } else if (context.startsWith("/member/") && (token.getIsAdmin().equals(BaseConstants.BOOLEAN_YES) || token.getIsAdmin().equals(BaseConstants.BOOLEAN_NO))) { securityService.addAccessTrail(accessHistory); } else { accessHistory.setLoginStatus(BaseConstants.LOGIN_FAIL); accessHistory.setReasonCode(ReasonCodes.ACCOUNT_UNAUTHORIZED); securityService.addAccessTrail(accessHistory); errors.add(BaseConstants.WARN_KEY, new ActionMessage("errors.account.notenoughrights")); saveMessages(request, errors); logger.info("ACCOUNT UNAUTHORIZED : IP: (" + currentIP + ") " + username); return mapping.getInputForward(); } return mapping.findForward(BaseConstants.FWD_SUCCESS); } else { errors.add(BaseConstants.FATAL_KEY, new ActionMessage("errors.technical.difficulty")); saveMessages(request, errors); return mapping.getInputForward(); } }
From source file:com.redoute.datamap.servlet.picture.FindAllPicture.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j ava 2 s . com*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS); try { String page[] = null; String application[] = null; String picture[] = null; String implemented[] = null; String stream[] = null; if (request.getParameterValues("page") != null) { page = request.getParameterValues("page"); } if (request.getParameterValues("picture") != null) { picture = request.getParameterValues("picture"); } if (request.getParameterValues("application") != null) { application = request.getParameterValues("application"); } if (request.getParameterValues("impl") != null) { implemented = request.getParameterValues("impl"); } if (request.getParameterValues("stream") != null) { stream = request.getParameterValues("stream"); } List<String> sArray = new ArrayList<String>(); List<String> sArrayJ = new ArrayList<String>(); if (page != null) { String spage = " ("; for (int a = 0; a < page.length - 1; a++) { spage += " p.`page` like '%" + page[a] + "%' or"; } spage += " p.`page` like '%" + page[page.length - 1] + "%') "; sArray.add(spage); } if (application != null) { String sapplication = " ("; for (int a = 0; a < application.length - 1; a++) { sapplication += " p.`application` like '%" + application[a] + "%' or"; } sapplication += " p.`application` like '%" + application[application.length - 1] + "%') "; sArray.add(sapplication); } if (picture != null) { String spicture = " ("; for (int a = 0; a < picture.length - 1; a++) { spicture += " p.`picture` like '%" + picture[a] + "%' or"; } spicture += " p.`picture` like '%" + picture[picture.length - 1] + "%') "; sArray.add(spicture); } if (implemented != null) { String simplemented = " ("; for (int a = 0; a < implemented.length - 1; a++) { simplemented += " d.`implemented` like '%" + implemented[a] + "%' or"; } simplemented += " d.`implemented` like '%" + implemented[implemented.length - 1] + "%') "; sArrayJ.add(simplemented); } if (stream != null) { String sstream = " ("; for (int a = 0; a < stream.length - 1; a++) { sstream += " d.`stream` like '%" + stream[a] + "%' or"; } sstream += " d.`stream` like '%" + stream[stream.length - 1] + "%') "; sArrayJ.add(sstream); } StringBuilder individualSearch = new StringBuilder(); if (sArray.size() >= 1) { for (int i = 0; i < sArray.size(); i++) { individualSearch.append(" and "); individualSearch.append(sArray.get(i)); } } StringBuilder joinedSearch = new StringBuilder(); if (sArrayJ.size() >= 1) { for (int i = 0; i < sArrayJ.size(); i++) { joinedSearch.append(" and "); joinedSearch.append(sArrayJ.get(i)); } } String inds = String.valueOf(individualSearch); String joined = String.valueOf(joinedSearch); JSONArray data = new JSONArray(); //data that will be shown in the table ApplicationContext appContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); IPictureService pictureService = appContext.getBean(IPictureService.class); IDatamapService datamapService = appContext.getBean(IDatamapService.class); List<Picture> datamapList = pictureService.findPictureListByCriteria(inds, joined); JSONObject jsonResponse = new JSONObject(); for (Picture datamap : datamapList) { boolean isImpl = datamapService.allImplementedByCriteria("picture", datamap.getPicture()); JSONArray row = new JSONArray(); row.put(datamap.getId()).put(datamap.getApplication()).put(datamap.getPage()) .put(datamap.getPicture()) .put(isImpl == true ? "Y" : "N"); data.put(row); } jsonResponse.put("aaData", data); response.setContentType("application/json"); response.getWriter().print(jsonResponse.toString()); } catch (JSONException ex) { Logger.log(FindAllPicture.class.getName(), Level.FATAL, ex.toString()); } finally { out.close(); } }
From source file:de.appsolve.padelcampus.listener.SessionEventListener.java
private void initDependencies(ServletContext servletContext) { if (sessionUtil == null) { WebApplicationContextUtils.getWebApplicationContext(servletContext).getAutowireCapableBeanFactory() .autowireBean(this); }// w w w. java2 s.co m }