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:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java

@SuppressWarnings("unchecked")
public void init(FilterConfig filterConfig) throws ServletException {
    ServletContext servletContext = filterConfig.getServletContext();
    usernameHttpSessionWrapperMap = (Map<String, HttpSessionWrapper>) servletContext
            .getAttribute(USERNAME_SESSIONID_MAP_ATTR);

    if (usernameHttpSessionWrapperMap == null) {
        usernameHttpSessionWrapperMap = Collections.synchronizedMap(new HashMap<String, HttpSessionWrapper>());
        servletContext.setAttribute(USERNAME_SESSIONID_MAP_ATTR, usernameHttpSessionWrapperMap);
    }/*from   w  ww  .jav  a  2 s  .co m*/

    String[] disallowConcurrentLoginUsernamesArray = StringUtils
            .split(filterConfig.getInitParameter("disallowConcurrentLoginUsernames"), " ,\t\r\n");

    if (disallowConcurrentLoginUsernamesArray != null && disallowConcurrentLoginUsernamesArray.length > 0) {
        disallowConcurrentLoginUsernames = new HashSet<String>(
                Arrays.asList(disallowConcurrentLoginUsernamesArray));
    }

    log.info(
            "HstConcurrentLoginFilter's disallowConcurrentLoginUsernames: " + disallowConcurrentLoginUsernames);

    String[] allowConcurrentLoginUsernamesArray = StringUtils
            .split(filterConfig.getInitParameter("allowConcurrentLoginUsernames"), " ,\t\r\n");

    if (allowConcurrentLoginUsernamesArray != null && allowConcurrentLoginUsernamesArray.length > 0) {
        allowConcurrentLoginUsernames = new HashSet<String>(Arrays.asList(allowConcurrentLoginUsernamesArray));
    }

    earlySessionInvalidation = BooleanUtils
            .toBoolean(filterConfig.getInitParameter("earlySessionInvalidation"));

    log.info("HstConcurrentLoginFilter's allowConcurrentLoginUsernames: " + allowConcurrentLoginUsernames);
}

From source file:ejportal.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}//  ww w . ja v a  2  s. c  o  m
 */
@SuppressWarnings("unchecked")
public void contextInitialized(final ServletContextEvent event) {
    StartupListener.log.debug("Initializing context...");

    final ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*
     * String[] beans = ctx.getBeanDefinitionNames(); for (String bean :
     * beans) { log.debug(bean); }
     */

    PasswordEncoder passwordEncoder = null;
    try {
        final ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager");
        for (final Object o : provider.getProviders()) {
            final AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (final NoSuchBeanDefinitionException n) {
        StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (StartupListener.log.isDebugEnabled()) {
        StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        StartupListener.log.debug("Populating drop-downs...");
    }

    StartupListener.setupContext(context);
}

From source file:com.google.ratel.util.RatelUtils.java

/**
 * Return the application configuration service instance from the given servlet context.
 *
 * @param servletContext the servlet context to get the config service instance
 * @return the application config service instance
 *///from   ww w .j  av  a 2 s.  c o m
public static RatelConfig getRatelConfig(ServletContext servletContext) {
    RatelConfig ratelConfig = (RatelConfig) servletContext.getAttribute(RatelConfig.CONTEXT_NAME);
    return ratelConfig;
}

From source file:org.iterx.miru.support.servlet.HttpDispatcherServlet.java

public void init(ServletConfig servletConfig) throws ServletException {

    try {/* w  ww .  ja v  a  2  s. co  m*/
        DispatcherApplicationContext applicationContext;
        ApplicationContext parentApplicationContext;
        HandlerChainFactory handlerChainFactory;
        ServletContext servletContext;
        String parameter;

        servletContext = servletConfig.getServletContext();

        parentApplicationContext = (ApplicationContext) servletContext
                .getAttribute((DispatcherApplicationContext.class).getName());
        applicationContext = ((parentApplicationContext != null)
                ? new ServletDispatcherApplicationContext(parentApplicationContext, servletContext)
                : new ServletDispatcherApplicationContext(servletContext));

        if ((parameter = servletConfig.getInitParameter(ServletDispatcherApplicationContext.BEANS)) != null
                && applicationContext instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) applicationContext).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");
        }

        handlerChainFactory = applicationContext.getHandlerChainFactory();
        if ((parameter = servletConfig.getInitParameter(ServletDispatcherApplicationContext.CHAINS)) != null
                && handlerChainFactory instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) handlerChainFactory).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");
        }

        if (dispatcher == null
                && (dispatcher = (Dispatcher<HttpServletRequestContext, HttpServletResponseContext>) applicationContext
                        .getBeanOfType(Dispatcher.class)) == null)
            dispatcher = new Dispatcher<HttpServletRequestContext, HttpServletResponseContext>();

        dispatcher.setHandlerChainMap(handlerChainFactory.getHandlerChains());
        processingContextFactory = applicationContext.getProcessingContextFactory();
    } catch (Exception e) {
        LOGGER.error("Initialisation failed.", e);
        throw new ServletException("Initialisation failed.", e);
    }
}

From source file:alpha.portal.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/*w  w  w. j a va  2 s.  c  o  m*/
 */
@SuppressWarnings("unchecked")
public void contextInitialized(final ServletContextEvent event) {
    StartupListener.log.debug("Initializing context...");

    final ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*
     * String[] beans = ctx.getBeanDefinitionNames(); for (String bean :
     * beans) { log.debug(bean); }
     */

    PasswordEncoder passwordEncoder = null;
    try {
        final ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (final Object o : provider.getProviders()) {
            final AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (final NoSuchBeanDefinitionException n) {
        StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (StartupListener.log.isDebugEnabled()) {
        StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        StartupListener.log.debug("Populating drop-downs...");
    }

    StartupListener.setupContext(context);
}

From source file:com.concursive.connect.indexer.jobs.IndexerJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    SchedulerContext schedulerContext = null;
    try {//from www  .j av a 2s.c o  m
        schedulerContext = context.getScheduler().getContext();
        // Determine the indexer service
        IIndexerService indexer = IndexerFactory.getInstance().getIndexerService();
        if (indexer == null) {
            throw (new JobExecutionException("Indexer Configuration error: No indexer defined."));
        }
        // Determine if the indexer job can run
        boolean canExecute = true;
        ServletContext servletContext = (ServletContext) schedulerContext.get("ServletContext");
        if (servletContext != null) {
            // If used in a servlet environment, make sure the indexer is initialized
            canExecute = "true".equals(servletContext.getAttribute(Constants.DIRECTORY_INDEX_INITIALIZED));
        }
        // Execute the indexer
        if (canExecute) {
            Vector eventList = (Vector) schedulerContext.get(INDEX_ARRAY);
            if (eventList.size() > 0) {
                LOG.debug("Indexing data... " + eventList.size());
                indexer.obtainWriterLock();
                try {
                    while (eventList.size() > 0) {
                        IndexEvent indexEvent = (IndexEvent) eventList.get(0);
                        if (indexEvent.getAction() == IndexEvent.ADD) {
                            // The object was either added or updated
                            indexer.indexAddItem(indexEvent.getItem());
                        } else if (indexEvent.getAction() == IndexEvent.DELETE) {
                            // Delete the item and related data
                            indexer.indexDeleteItem(indexEvent.getItem());
                        }
                        eventList.remove(0);
                    }
                } catch (Exception e) {
                    LOG.error("Indexing error", e);
                    throw new JobExecutionException(e.getMessage());
                } finally {
                    indexer.releaseWriterLock();
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Indexing job error", e);
        throw new JobExecutionException(e.getMessage());
    }
}

From source file:org.apache.hadoop.hbase.http.HttpServer.java

/**
 * Get the admin ACLs from the given ServletContext and check if the given
 * user is in the ACL./*from   ww w  . j  a v a 2  s. c  om*/
 *
 * @param servletContext the context containing the admin ACL.
 * @param remoteUser the remote user to check for.
 * @return true if the user is present in the ACL, false if no ACL is set or
 *         the user is not present
 */
public static boolean userHasAdministratorAccess(ServletContext servletContext, String remoteUser) {
    AccessControlList adminsAcl = (AccessControlList) servletContext.getAttribute(ADMINS_ACL);
    UserGroupInformation remoteUserUGI = UserGroupInformation.createRemoteUser(remoteUser);
    return adminsAcl != null && adminsAcl.isUserAllowed(remoteUserUGI);
}

From source file:org.apache.pluto.driver.PortalStartupListener.java

/**
 * Initializes the portlet container. This method constructs and initializes
 * the portlet container, and saves it to the servlet context scope.
 *
 * @param servletContext the servlet context.
 *///from  w  w  w  .j a  v  a 2s.  c o  m
private void initContainer(ServletContext servletContext) {

    WebApplicationContext springContext = (WebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    // Retrieve the driver configuration from servlet context.
    DriverConfiguration driverConfig = (DriverConfiguration) servletContext.getAttribute(DRIVER_CONFIG_KEY);

    try {
        LOG.info("Initializing Portlet Container. . .");

        LOG.debug(" [1] Loading RequiredContainerServices. . .");
        RequiredContainerServices required = (RequiredContainerServices) springContext
                .getBean("RequiredContainerServices");

        LOG.debug(" [2] Loading OptionalContainerServices. . .");
        OptionalContainerServices optional = (OptionalContainerServices) springContext
                .getBean("OptionalContainerServices");

        // Create portlet container.
        LOG.debug(" [3] Creating portlet container...");
        PortletContainerFactory factory = PortletContainerFactory.getInstance();
        PortletContainer container = factory.createContainer(driverConfig.getContainerName(), required,
                optional);

        // Initialize portlet container.
        LOG.debug(" [4] Initializing portlet container...");
        container.init();

        // Save portlet container to the servlet context scope.
        servletContext.setAttribute(CONTAINER_KEY, container);
        LOG.info("Pluto portlet container started.");

    } catch (DriverConfigurationException ex) {
        LOG.error("Unable to retrieve driver configuration " + "due to configuration error: " + ex.getMessage(),
                ex);
    } catch (PortletContainerException ex) {
        LOG.error("Unable to start up portlet container: " + ex.getMessage(), ex);
    }
}

From source file:com.athena.sqs.MessageReceiveListener.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();
    listenQueueName = servletContext.getInitParameter("listenQueueName");
    if (listenQueueName == null) {
        listenQueueName = "your_listen_queue_name";
    }//from w w w  .  j a va  2s.c  o m

    ApplicationContext applicationContext = (ApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    receiver = applicationContext.getBean(MessageReceiver.class);

    // If you want to run multiple receivers, create tasks or change doReceive method to async.
    /*
     * List<BizQueue> list = dao.getBizQueueList();
     * for(BizQueue queue : list) {
     *     BizQueueTask task = new BiaQueueTask(sqsContext, queue);
     *     task.run(); // thread start.
     * }
     */
    try {
        logger.debug("***********************************************");
        logger.debug("SQS Message Receiver is starting");
        logger.debug("***********************************************");

        // Queue names are loaded from sqsContext.xml

        List<String> queueList = (List<String>) applicationContext.getBean("initialQueueList");

        for (String queueName : queueList) {
            receiver.doReceive(queueName);
            Thread.sleep(2000);
        }

        // Default listen queue start
        receiver.doReceive(listenQueueName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.uci.ics.asterix.api.http.servlet.RESTAPIServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response, String query)
        throws IOException {
    SessionConfig sessionConfig = initResponse(request, response);
    AqlTranslator.ResultDelivery resultDelivery = whichResultDelivery(request);

    ServletContext context = getServletContext();
    IHyracksClientConnection hcc;// ww w .j  a va  2 s.  com
    IHyracksDataset hds;

    try {
        synchronized (context) {
            hcc = (IHyracksClientConnection) context.getAttribute(HYRACKS_CONNECTION_ATTR);
            hds = (IHyracksDataset) context.getAttribute(HYRACKS_DATASET_ATTR);
            if (hds == null) {
                hds = new HyracksDataset(hcc, ResultReader.FRAME_SIZE, ResultReader.NUM_READERS);
                context.setAttribute(HYRACKS_DATASET_ATTR, hds);
            }
        }

        AQLParser parser = new AQLParser(query);
        List<Statement> aqlStatements = parser.parse();
        if (!containsForbiddenStatements(aqlStatements)) {
            MetadataManager.INSTANCE.init();
            AqlTranslator aqlTranslator = new AqlTranslator(aqlStatements, sessionConfig);
            aqlTranslator.compileAndExecute(hcc, hds, resultDelivery);
        }
    } catch (ParseException | TokenMgrError | edu.uci.ics.asterix.aqlplus.parser.TokenMgrError pe) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
        String errorMessage = ResultUtils.buildParseExceptionMessage(pe, query);
        JSONObject errorResp = ResultUtils.getErrorResponse(2, errorMessage, "", "");
        sessionConfig.out().write(errorResp.toString());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        ResultUtils.apiErrorHandler(sessionConfig.out(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}