Example usage for javax.servlet ServletContext setAttribute

List of usage examples for javax.servlet ServletContext setAttribute

Introduction

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

Prototype

public void setAttribute(String name, Object object);

Source Link

Document

Binds an object to a given attribute name in this ServletContext.

Usage

From source file:org.jasig.cas.web.init.SafeContextLoaderListener.java

public void contextInitialized(final ServletContextEvent sce) {
    try {/*w w  w.  j a  v a 2  s. co m*/
        this.delegate.contextInitialized(sce);
    } catch (Throwable t) {
        /*
         * no matter what went wrong, our role is to capture this error and
         * prevent it from blocking initialization of the context. logging
         * overkill so that our deployer will find a record of this problem
         * even if unfamiliar with Commons Logging and properly configuring
         * it.
         */

        final String message = "SafeContextLoaderListener: \n"
                + "The Spring ContextLoaderListener we wrap threw on contextInitialized.\n"
                + "But for our having caught this error, the web application context would not have initialized.";

        // log it via Commons Logging
        log.fatal(message, t);

        // log it to System.err
        System.err.println(message);
        t.printStackTrace();

        // log it to the ServletContext
        ServletContext context = sce.getServletContext();
        context.log(message, t);

        /*
         * record the error so that the application has access to later
         * display a proper error message based on the exception.
         */
        context.setAttribute(CAUGHT_THROWABLE_KEY, t);
    }
}

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

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    String clName = context.getInitParameter(LOCALE_RESOLVER_CLASS_NAME_ATTR);
    String baseName = context.getInitParameter(MESSAGE_SOURCE_BASENAME_ATTR);
    try {/*from   ww  w .j a v a 2 s . com*/
        LocaleResolver obj = (LocaleResolver) Class.forName(clName).newInstance();
        context.setAttribute(LocaleUtils.LOCALE_RESOLVER_NAME, obj);
        if (MessageSourceProxy.getMessageSource() == null && baseName != null) {
            MessageSourceProxy.setMessageSource(createMessageSource(baseName.split(",")));
        }
    } catch (Exception ex) {
        log.debug(ex.getMessage());
    }
}

From source file:org.obiba.mica.config.WebConfiguration.java

/**
 * Initializes Metrics.//from w  w w .j av  a  2s . c  o  m
 */
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    log.debug("Initializing Metrics registries");
    servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry);
    servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);

    log.debug("Registering Metrics Filter");
    FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
            new InstrumentedFilter());

    metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
    metricsFilter.setAsyncSupported(true);

    log.debug("Registering Metrics Servlet");
    ServletRegistration.Dynamic metricsAdminServlet = servletContext.addServlet("metricsServlet",
            new MetricsServlet());

    metricsAdminServlet.addMapping("/jvm/*");
    metricsAdminServlet.setAsyncSupported(true);
    metricsAdminServlet.setLoadOnStartup(2);
}

From source file:com.openkm.servlet.admin.CronTabServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    updateSessionManager(request);/*from   w  w w . j av a  2s.co  m*/

    try {
        Map<String, String> types = new LinkedHashMap<String, String>();
        types.put(MimeTypeConfig.MIME_BSH, "BSH");
        types.put(MimeTypeConfig.MIME_JAR, "JAR");

        if (action.equals("create")) {
            ServletContext sc = getServletContext();
            CronTab ct = new CronTab();
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            ServletContext sc = getServletContext();
            int ctId = WebUtils.getInt(request, "ct_id");
            CronTab ct = CronTabDAO.findByPk(ctId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            ServletContext sc = getServletContext();
            int ctId = WebUtils.getInt(request, "ct_id");
            CronTab ct = CronTabDAO.findByPk(ctId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("execute")) {
            execute(request, response);
            list(request, response);
        } else if (action.equals("download")) {
            download(request, response);
        } else {
            list(request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (EvalError e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:org.broadleafcommerce.test.BroadleafGenericGroovyXmlWebContextLoader.java

/**
 * Configures web resources for the supplied web application context (WAC).
 *
 * <h4>Implementation Details</h4>
 *
 * <p>If the supplied WAC has no parent or its parent is not a WAC, the
 * supplied WAC will be configured as the Root WAC (see "<em>Root WAC
 * Configuration</em>" below)./*from  w w w  .  j a  va 2 s .c  o  m*/
 *
 * <p>Otherwise the context hierarchy of the supplied WAC will be traversed
 * to find the top-most WAC (i.e., the root); and the {@link ServletContext}
 * of the Root WAC will be set as the {@code ServletContext} for the supplied
 * WAC.
 *
 * <h4>Root WAC Configuration</h4>
 *
 * <ul>
 * <li>The resource base path is retrieved from the supplied
 * {@code WebMergedContextConfiguration}.</li>
 * <li>A {@link ResourceLoader} is instantiated for the {@link MockServletContext}:
 * if the resource base path is prefixed with "{@code classpath:/}", a
 * {@link DefaultResourceLoader} will be used; otherwise, a
 * {@link FileSystemResourceLoader} will be used.</li>
 * <li>A {@code MockServletContext} will be created using the resource base
 * path and resource loader.</li>
 * <li>The supplied {@link MergeXmlWebApplicationContext} is then stored in
 * the {@code MockServletContext} under the
 * {@link MergeXmlWebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.</li>
 * <li>Finally, the {@code MockServletContext} is set in the
 * {@code MergeXmlWebApplicationContext}.</li>
 *
 * @param context the merge xml web application context for which to configure the web
 * resources
 * @param webMergedConfig the merged context configuration to use to load the
 * merge xml web application context
 */
protected void configureWebResources(MergeXmlWebApplicationContext context,
        WebMergedContextConfiguration webMergedConfig) {

    ApplicationContext parent = context.getParent();

    // if the WAC has no parent or the parent is not a WAC, set the WAC as
    // the Root WAC:
    if (parent == null || (!(parent instanceof WebApplicationContext))) {
        String resourceBasePath = webMergedConfig.getResourceBasePath();
        ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)
                ? new DefaultResourceLoader()
                : new FileSystemResourceLoader();

        ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
        context.setServletContext(servletContext);
    } else {
        ServletContext servletContext = null;

        // find the Root WAC
        while (parent != null) {
            if (parent instanceof WebApplicationContext
                    && !(parent.getParent() instanceof WebApplicationContext)) {
                servletContext = ((WebApplicationContext) parent).getServletContext();
                break;
            }
            parent = parent.getParent();
        }
        Assert.state(servletContext != null,
                "Failed to find Root MergeXmlWebApplicationContext in the context hierarchy");
        context.setServletContext(servletContext);
    }
}

From source file:be.fedict.eid.idp.protocol.saml2.AbstractSAML2ProtocolService.java

protected void setIdPConfiguration(ServletContext servletContext, IdentityProviderConfiguration configuration) {
    servletContext.setAttribute(IDP_CONFIG_CONTEXT_ATTRIBUTE, configuration);
}

From source file:com.ikon.servlet.admin.MimeTypeServlet.java

/**
 * Create mime type//from   w ww  . j a  v  a 2s .c  o  m
 */
private void create(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("create({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    MimeType mt = new MimeType();
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("extensions", null);
    sc.setAttribute("mt", mt);
    sc.getRequestDispatcher("/admin/mime_edit.jsp").forward(request, response);
    log.debug("create: void");
}

From source file:org.sindice.analytics.servlet.AssistedSparqlEditorListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

    final ServletContext context = sce.getServletContext();

    logger.info("initializing ASE context");
    XMLConfiguration config = (XMLConfiguration) sce.getServletContext().getAttribute("config");

    context.setAttribute(RECOMMENDER_WRAPPER + RANKING_CONFIGURATION, createRankingConfigFile());

    final String datasetLabelDef = getParameterWithLogging(config,
            RECOMMENDER_WRAPPER + "." + DATASET_LABEL_DEF, AnalyticsVocab.DATASET_LABEL_DEF.toString());
    context.setAttribute(RECOMMENDER_WRAPPER + DATASET_LABEL_DEF, datasetLabelDef);

    final String domainUriPrefix = getParameterWithLogging(config,
            RECOMMENDER_WRAPPER + "." + DOMAIN_URI_PREFIX, AnalyticsVocab.DOMAIN_URI_PREFIX);
    context.setAttribute(RECOMMENDER_WRAPPER + DOMAIN_URI_PREFIX, domainUriPrefix);

    final String backend = getParameterWithLogging(config, RECOMMENDER_WRAPPER + "." + BACKEND,
            BackendType.HTTP.toString());
    context.setAttribute(RECOMMENDER_WRAPPER + BACKEND, backend);
    final String[] backendArgs = getParametersWithLogging(config, RECOMMENDER_WRAPPER + "." + BACKEND_ARGS,
            new String[] { "http://sparql.sindice.com/sparql" });
    context.setAttribute(RECOMMENDER_WRAPPER + BACKEND_ARGS, backendArgs);

    final String limit = getParameterWithLogging(config, RECOMMENDER_WRAPPER + "." + PAGINATION,
            Integer.toString(SesameBackend.LIMIT));
    context.setAttribute(RECOMMENDER_WRAPPER + PAGINATION, Integer.valueOf(limit));

    final String[] classAttributes = getParametersWithLogging(config,
            RECOMMENDER_WRAPPER + "." + CLASS_ATTRIBUTES,
            new String[] { AnalyticsClassAttributes.DEFAULT_CLASS_ATTRIBUTE });
    context.setAttribute(RECOMMENDER_WRAPPER + CLASS_ATTRIBUTES, classAttributes);

    final String useMemcached = getParameterWithLogging(config, "USE_MEMCACHED", "false");
    final String memcachedHost = getParameterWithLogging(config, "MEMCACHED_HOST", "localhost");
    final String memcachedPort = getParameterWithLogging(config, "MEMCACHED_PORT", "11211");

    if (Boolean.parseBoolean(useMemcached)) {
        try {/*  w  ww .j a  v  a 2s. c o  m*/
            final List<InetSocketAddress> addresses = AddrUtil
                    .getAddresses(memcachedHost + ":" + memcachedPort);
            wrapper = new MemcachedClientWrapper(new MemcachedClient(addresses));
            sce.getServletContext().setAttribute(MemcachedClientWrapper.class.getName(), wrapper);
        } catch (IOException e) {
            logger.error("Could not initialize memcached !!!", e);
        }
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.service.ServletContextAttributeExporter.java

/** {@inheritDoc} */
public void initialize() throws ServiceException {
    if (!(appCtx instanceof WebApplicationContext)) {
        log.warn("This service may only be used when services are loaded within a web application context.");
        return;//  w ww.j  a  va2  s. c om
    }

    Object bean;
    if (exportedBeans != null) {
        WebApplicationContext webAppCtx = (WebApplicationContext) appCtx;
        ServletContext servletCtx = webAppCtx.getServletContext();
        for (String beanId : exportedBeans) {
            bean = webAppCtx.getBean(beanId);
            if (bean != null) {
                log.debug("Exporting bean {} to servlet context.", beanId);
                servletCtx.setAttribute(beanId, bean);
            } else {
                log.warn("No {} bean located, unable to export it to the servlet context", beanId);
            }
        }
    }

    initialized = true;
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.syncml.impl.SyncmlServiceImpl.java

private void setChannelURI(String channelURI) {
    ServletContext ctx = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
    ctx.setAttribute("channelURI", channelURI);
}