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.SafeDispatcherServlet.java

public void init(final ServletConfig config) {
    try {//from ww w  . j a  v  a2  s.c  om
        this.delegate.init(config);

    } catch (final Throwable t) {
        // let the service method know initialization failed.
        this.initSuccess = false;

        /*
         * no matter what went wrong, our role is to capture this error and
         * prevent it from blocking initialization of the servlet. 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 = "SafeDispatcherServlet: \n"
                + "The Spring DispatcherServlet we wrap threw on init.\n"
                + "But for our having caught this error, the servlet 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 = config.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:org.jwatch.listener.settings.SettingsLoaderListener.java

public void contextInitialized(ServletContextEvent event) {
    try {// www .j av a2s .  c o m
        log.info("Starting Settings Load...");
        long start = Calendar.getInstance().getTimeInMillis();

        ServletContext sc = event.getServletContext();
        if (sc != null) {
            String sMaxEvents = sc.getInitParameter("maxevents");
            int maxEvents = NumberUtils.toInt(sMaxEvents, EventService.DEFAULT_MAX_EVENT_LIST_SIZE);
            sc.setAttribute("maxevents", maxEvents); // expose to other servlets
            EventService.setMaxEventListSize(maxEvents);

            String sMaxShowEvents = sc.getInitParameter("maxshowevents");
            int maxShowEvents = NumberUtils.toInt(sMaxShowEvents,
                    EventService.DEFAULT_MAX_SHOW_EVENT_LIST_SIZE);
            sc.setAttribute("maxshowevents", maxShowEvents); // expose to other servlets
            EventService.setMaxShowEventListSize(maxShowEvents);
        }

        // load config file and instances
        QuartzInstanceService.initQuartzInstanceMap();

        SettingsUtil.loadProperties();

        // connect/start DB
        connectionUtil = new ConnectionUtil(SettingsUtil.getDBFilePath());
        StringBuffer jwatchLog = new StringBuffer();
        jwatchLog.append("CREATE TEXT TABLE IF NOT EXISTS JWATCHLOG (").append("id INTEGER IDENTITY,")
                .append("CALENDARNAME VARCHAR(256),").append("JOBGROUP VARCHAR(256),")
                .append("JOBNAME VARCHAR(256),").append("SCHEDULERNAME VARCHAR(256),")
                .append("TRIGGERGROUP VARCHAR(256),").append("TRIGGERNAME VARCHAR(256),")
                .append("FIRETIME DATE,").append("NEXTFIRETIME  DATE,").append("PREVIOUSFIRETIME  DATE,")
                .append("SCHEDULEDFIRETIME  DATE,").append("RECOVERING BOOLEAN,").append("JOBRUNTIME BIGINT, ")
                .append("REFIRECOUNT INTEGER, ").append("SCHEDULERID VARCHAR(256),")
                .append("QUARTZINSTANCEID VARCHAR(256)").append(")");
        connectionUtil.update(jwatchLog.toString());

        long end = Calendar.getInstance().getTimeInMillis();
        log.info("Settings startup completed in: " + (end - start) + " ms");
    } catch (Throwable t) {
        log.error("Failed to initialize Settings.", t);
    }
}

From source file:com.umeng.core.utils.wurfl.SpringWurflManagerByMe.java

public void setServletContext(ServletContext servletContext) {
    servletContext.setAttribute(wurflHolderKey, this);
    if (logger.isInfoEnabled()) {
        logger.info("Exported WURFLHolder in Servlet Context with attribute key '" + wurflHolderKey + "'");
    }// ww w .  j  a  v  a  2s  .  c  o  m
}

From source file:org.apache.wiki.TestEngine.java

License:asdf

public TestEngine(Properties props) throws WikiException {
    super(new MockServletContext("test"), "test", cleanTestProps(props));

    // Stash the WikiEngine in the servlet context
    ServletContext servletContext = this.getServletContext();
    servletContext.setAttribute("org.apache.wiki.WikiEngine", this);
}

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

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");
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from   www.j  a v a2 s.  co  m*/

    try {
        if (action.equals("create")) {
            ServletContext sc = getServletContext();
            Report rp = new Report();
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            ServletContext sc = getServletContext();
            int rpId = WebUtils.getInt(request, "rp_id");
            Report rp = ReportDAO.findByPk(rpId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            ServletContext sc = getServletContext();
            int rpId = WebUtils.getInt(request, "rp_id");
            Report rp = ReportDAO.findByPk(rpId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("paramList")) {
            paramList(userId, request, response);
        } else if (action.equals("getParams")) {
            getParams(userId, request, response);
        } else if (action.equals("execute")) {
            execute(userId, request, response);
        } else {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (JRException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (EvalError e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:org.seasar.struts.hotdeploy.plugin.HotdeployPlugIn.java

private void initModuleConfig(ServletContext context, ModuleConfig config) {
    S2Container container = getContainer();
    if (!container.hasComponentDef(ModuleConfigWrapper.class)) {
        return;/*  ww  w .ja v  a2  s  .c  o  m*/
    }

    ModuleConfigWrapper configWrapper = (ModuleConfigWrapper) container.getComponent(ModuleConfigWrapper.class);
    configWrapper.init(config);
    context.setAttribute(Globals.MODULE_KEY + config.getPrefix(), configWrapper);
}

From source file:org.sindice.servlet.sparqlqueryservlet.SparqlQueryServletListener.java

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

    final ServletContext context = sce.getServletContext();

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

    // PreProcessing
    final String prep = config.getString(SQS_WRAPPER + "." + PREPROCESSING, "");
    context.setAttribute(SQS_WRAPPER + PREPROCESSING, prep);
    final String[] prepArgs = getParametersWithLogging(config, SQS_WRAPPER + "." + PREPROCESSING_ARGS,
            new String[] {});
    context.setAttribute(SQS_WRAPPER + PREPROCESSING_ARGS, prepArgs);

    final String backend = config.getString(SQS_WRAPPER + "." + BACKEND, BackendType.NATIVE.toString());
    context.setAttribute(SQS_WRAPPER + BACKEND, backend);
    // TODO handle HTTPmode
    final String[] backendArgs = getParametersWithLogging(config, SQS_WRAPPER + "." + BACKEND_ARGS,
            new String[] { "./native-repository" });
    context.setAttribute(SQS_WRAPPER + BACKEND_ARGS, backendArgs);

    logger.info("Backend={} BackendArgs={}", backend, Arrays.toString(backendArgs));

    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 {//from  w  ww.  jav a2 s.co  m
            final List<InetSocketAddress> addresses = AddrUtil
                    .getAddresses(memcachedHost + ":" + memcachedPort);
            wrapper = new MemcachedClientWrapper(new MemcachedClient(addresses));
            sce.getServletContext().setAttribute(SQS_WRAPPER + MemcachedClientWrapper.class.getName(), wrapper);
        } catch (IOException e) {
            logger.error("Could not initialize memcached !!!", e);
        }
    }
}

From source file:org.springframework.boot.web.SpringServletInitializer.java

protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
    ApplicationContext parent = null;/*from   www  .ja va  2  s .  co m*/
    Object object = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (object instanceof ApplicationContext) {
        this.logger.info("Root context already created (using as parent).");
        parent = (ApplicationContext) object;
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
    }
    SpringApplication application = new SpringApplication((Object[]) getConfigClasses());
    AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext();
    context.setParent(parent);
    context.setServletContext(servletContext);
    application.setApplicationContext(context);
    return (WebApplicationContext) application.run();
}

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageSetup.java

/**
 * Create an implementation of {@link FileStorage} and store it in the
 * {@link ServletContext}, as an attribute named according to
 * {@link #ATTRIBUTE_NAME}.//from  w  w w  . j a v  a  2  s  . co  m
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    StartupStatus ss = StartupStatus.getBean(ctx);

    try {
        File baseDirectory = figureBaseDir(sce);
        Collection<String> fileNamespace = confirmDefaultNamespace(sce);
        FileStorage fs = new FileStorageImpl(baseDirectory, fileNamespace);

        ctx.setAttribute(ATTRIBUTE_NAME, fs);
    } catch (Exception e) {
        log.fatal("Failed to initialize the file system.", e);
        ss.fatal(this, "Failed to initialize the file system.", e);
    }
}