Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:net.mojodna.sprout.support.SpringBodyTagSupport.java

/**
 * Fetch ContextLoaderPlugIn's WebApplicationContext from the ServletContext,
 * falling back to the root WebApplicationContext (the usual case).
 * @return the WebApplicationContext//from w  w w  .j  a v a 2  s .  com
 * @throws IllegalStateException if no WebApplicationContext could be found
 * @see ContextLoaderPlugIn#SERVLET_CONTEXT_PREFIX
 * @see WebApplicationContextUtils#getWebApplicationContext
 */
protected WebApplicationContext initWebApplicationContext(final PageContext pageContext)
        throws IllegalStateException {
    final ServletContext sc = pageContext.getServletContext();
    WebApplicationContext wac = (WebApplicationContext) sc
            .getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX);
    if (null == wac) {
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    }
    return wac;
}

From source file:com.toedter.chatty.server.boot.message.web.ChatMessageRepositoryListener.java

private void notifySubscribers(ChatMessage chatMessage) {
    shouldBroadcast.set(true);/*w ww .j  a  va 2s.c om*/
    if (!isBroadcasterInitialized.getAndSet(true)) {
        logger.info("Broadcasting initialized");
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        Runnable broadcasterRunnable = new Runnable() {
            public void run() {
                // logger.info("Broadcasting REFRESH: " + shouldBroadcast.get());
                if (shouldBroadcast.getAndSet(false)) {
                    if (broadcaster == null) {
                        ServletContext servletContext = ServletContextFactory.getDefault().getServletContext();
                        BroadcasterFactory factory = (BroadcasterFactory) servletContext
                                .getAttribute("org.atmosphere.cpr.BroadcasterFactory");
                        broadcaster = factory.lookup("/chatty/atmos/messages");
                    }
                    broadcaster.broadcast("{\"command\":\"reloadChatMessages\"}");
                }
            }
        };
        scheduledExecutorService.scheduleAtFixedRate(broadcasterRunnable, 0, 300, TimeUnit.MILLISECONDS);
    }
}

From source file:com.krawler.common.listeners.LocaleResolverListener.java

@Override
public void requestInitialized(ServletRequestEvent sre) {
    ServletRequest request = sre.getServletRequest();
    ServletContext context = sre.getServletContext();

    if (request != null && context != null) {
        request.setAttribute(LocaleUtils.LOCALE_RESOLVER_ATTRIBUTE,
                context.getAttribute(LocaleUtils.LOCALE_RESOLVER_NAME));
    } else {//from   www.j ava2s .com
        log.debug("Locale resolver cannot be associated with request [request:" + request + ",context:"
                + context + "]");
    }
}

From source file:com.manydesigns.portofino.stripes.ForbiddenAccessResolution.java

public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    //TODO ElementsActionBeanContext
    ElementsActionBeanContext context = new ElementsActionBeanContext();
    context.setRequest(request);/*from   w ww. j  a va  2 s .  c o  m*/
    String originalPath = context.getActionPath();
    UrlBuilder urlBuilder = new UrlBuilder(Locale.getDefault(), originalPath, false);
    Map<?, ?> parameters = request.getParameterMap();
    urlBuilder.addParameters(parameters);
    String returnUrl = urlBuilder.toString();
    boolean ajax = "true".equals(request.getParameter("ajax"));
    ServletContext servletContext = ElementsThreadLocals.getServletContext();
    Configuration configuration = (Configuration) servletContext
            .getAttribute(BaseModule.PORTOFINO_CONFIGURATION);
    if (!subject.isAuthenticated() && !ajax) {
        logger.info("Anonymous user not allowed. Redirecting to login.");
        String loginPage = configuration.getString(PortofinoProperties.LOGIN_PAGE);
        RedirectResolution redirectResolution = new RedirectResolution(loginPage, true);
        redirectResolution.addParameter("returnUrl", returnUrl);
        redirectResolution.execute(request, response);
    } else {
        if (ajax) {
            logger.debug("AJAX call while user disconnected");
            //TODO where to redirect?
            String loginPage = configuration.getString(PortofinoProperties.LOGIN_PAGE);
            UrlBuilder loginUrlBuilder = new UrlBuilder(Locale.getDefault(), loginPage, false);
            response.setStatus(UNAUTHORIZED);
            new StreamingResolution("text/plain", loginUrlBuilder.toString()).execute(request, response);
        } else {
            logger.warn("User not authorized for url {}.", returnUrl);
            new ErrorResolution(UNAUTHORIZED, errorMessage).execute(request, response);
        }
    }
}

From source file:com.happyuno.controller.EventController.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*w  w  w . j  av a 2s  . c  o m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");
    response.setHeader("Cache-Control", "no-cache");

    int playerId = Integer.parseInt(request.getParameter("playerId").trim());
    int gameId = Integer.parseInt(request.getParameter("tableId").trim());

    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");
    //?
    Game game = gameTableMap.get(gameId).getCurrentGame();

    ArrayList<JSONObject> eventsAL = game.getEventCenter().getEvents(game.getPlayerFromId(playerId));

    JSONArray events = new JSONArray();
    for (int i = 0; i < eventsAL.size(); ++i) {
        events.put(eventsAL.get(i));
    }

    response.getWriter().write(events.toString());
}

From source file:de.ingrid.iplug.web.PlugdescriptionContextListener.java

public void contextInitialized(ServletContextEvent servletcontextevent) {
    ServletContext servletContext = servletcontextevent.getServletContext();
    String pdFile = servletContext.getInitParameter("plugdescription.xml");
    BeanFactory beanFactory = (BeanFactory) servletContext.getAttribute("beanFactory");
    try {/*from  w  w w  .j  a v  a 2 s. c om*/
        beanFactory.addBean("pd_file", new File(pdFile));
    } catch (IOException e) {
        LOG.error("can not add plugdescription", e);
    }

}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testSuccessfulAuthorisation() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms"))
            .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms());
    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(true);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);

    assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED));
}

From source file:org.carrot2.webapp.LogInitContextListener.java

/**
 * Callback hook from the application container. Initialize logging appenders
 * immediately or defer initialization until possible.
 *//*from  w w w.j av a2s .  c o  m*/
public void contextInitialized(ServletContextEvent event) {
    final ServletContext servletContext = event.getServletContext();
    if (servletContext.getAttribute(CONTEXT_ID) != null) {
        // Only one instance needed.
        return;
    }

    /*
     * If the container has Servlet 2.5 API, init loggers immediately. Otherwise, save
     * itself to the context and wait for {@link QueryProcessorServlet} to perform
     * deferred initialization.
     */
    try {
        final Method method = ServletContext.class.getMethod("getContextPath");
        final String contextPath = (String) method.invoke(servletContext);
        addAppenders(contextPath);
    } catch (RuntimeException e) {
        // Rethrow runtime exceptions, if any.
        throw e;
    } catch (Exception e) {
        /*
         * No servlet 2.5 API (getContextPath), save in the context for deferred
         * initialization.
         */
        servletContext.setAttribute(CONTEXT_ID, this);
    }
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testNotAuthorised() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms"))
            .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms());
    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(false);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);
    assertThat("User should not be authorised", auth, nullValue());

    verify(response, times(1)).sendError(HttpServletResponse.SC_FORBIDDEN);
    verifyNoMoreInteractions(response);//w w  w. ja va 2 s . c om
}

From source file:com.skilrock.lms.web.scratchService.gameMgmt.common.InitialUploadGameDetailsBasic.java

/**
 * This method is used to read properties from Application context.
 * /*from  w w w. j a  v a  2  s . com*/
 * @return SUCCESS
 */
public String initialUploadBasicDetails() throws Exception {

    ServletContext sc = ServletActionContext.getServletContext();
    agent_sale_comm_rate = (String) sc.getAttribute("AGT_SALE_COMM_RATE");
    retailer_sale_comm_rate = (String) sc.getAttribute("RET_SALE_COMM_RATE");
    agent_pwt_comm_rate = (String) sc.getAttribute("AGT_PWT_COMM_RATE");
    retailer_pwt_comm_rate = (String) sc.getAttribute("RET_PWT_COMM_RATE");
    govtCommRule = (String) sc.getAttribute("GOVT_COMM_RULE");
    vat_applicable = (String) sc.getAttribute("VAT_APPLICABLE");
    session = getRequest().getSession();

    // this.setAgent_sale_comm_rate(agent_sale_comm_rate);
    session.setAttribute("x", this);
    return SUCCESS;

}