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.seasar.struts.hotdeploy.plugin.HotdeployPlugIn.java

private void initMessageResources(ServletContext context, ModuleConfig config) {
    S2Container container = getContainer();
    if (!container.hasComponentDef(ReloadMessageResourcesFactory.class)) {
        return;/*from w  w  w .  j a va2 s .co  m*/
    }

    ReloadMessageResourcesFactory reloadResourcesFactory = (ReloadMessageResourcesFactory) container
            .getComponent(ReloadMessageResourcesFactory.class);
    MessageResourcesConfig[] mrcs = config.findMessageResourcesConfigs();
    for (int i = 0; i < mrcs.length; i++) {
        MessageResources resources = (MessageResources) context
                .getAttribute(mrcs[i].getKey() + config.getPrefix());
        MessageResources reloadResources = reloadResourcesFactory.createResources(resources);
        context.setAttribute(mrcs[i].getKey() + config.getPrefix(), reloadResources);
    }
}

From source file:com.liangc.hq.base.web.ConfiguratorListener.java

private void loadPreferences(ServletContext ctx) {
    ConfigResponse userPrefs = new ConfigResponse();
    ConfigResponse userDashPrefs = new ConfigResponse();
    ConfigResponse roleDashPrefs = new ConfigResponse();

    try {/*from   w w w  .  ja v  a  2s. co m*/
        // Load User Preferences
        Properties userProps = loadProperties(ctx, getPreferenceFile());
        Enumeration keys = userProps.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            userPrefs.setValue(key, userProps.getProperty(key));
        }
        ctx.setAttribute(Constants.DEF_USER_PREFS, userPrefs);

        // Load User Dashboard Preferences
        Properties userDashProps = loadProperties(ctx, getUserDashboardPreferenceFile());
        keys = userDashProps.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            userDashPrefs.setValue(key, userDashProps.getProperty(key));
        }
        ctx.setAttribute(Constants.DEF_USER_DASH_PREFS, userDashPrefs);

        // Load Role Dashboard Preferences
        Properties roleDashProps;
        try {
            roleDashProps = loadProperties(ctx, getRoleDashboardPreferenceFile());
        } catch (Exception e) {
            roleDashProps = null;
        }
        if (roleDashProps != null) {
            keys = roleDashProps.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                roleDashPrefs.setValue(key, roleDashProps.getProperty(key));
            }
        }
        ctx.setAttribute(Constants.DEF_ROLE_DASH_PREFS, roleDashPrefs);
    } catch (Exception e) {
        error("loading table properties file " + Constants.PROPS_TAGLIB + "failed: ", e);

    }

}

From source file:org.seasar.cubby.plugins.guice.CubbyModuleTest.java

@Test
public void configure() throws Exception {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ServletContext servletContext = createNiceMock(ServletContext.class);
    expect(servletContext.getInitParameter("cubby.guice.module")).andStubReturn(TestModule.class.getName());
    final Hashtable<String, Object> attributes = new Hashtable<String, Object>();
    expect(servletContext.getAttribute((String) anyObject())).andStubAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(getCurrentArguments()[0]);
        }// w w  w  . jav a 2  s  .  c  o  m

    });
    servletContext.setAttribute((String) anyObject(), anyObject());
    expectLastCall().andAnswer(new IAnswer<Void>() {

        public Void answer() throws Throwable {
            attributes.put((String) getCurrentArguments()[0], getCurrentArguments()[1]);
            return null;
        }

    });
    replay(servletContext);

    final CubbyGuiceServletContextListener cubbyGuiceServletContextListener = new CubbyGuiceServletContextListener();
    cubbyGuiceServletContextListener.contextInitialized(new ServletContextEvent(servletContext));

    final GuiceFilter guiceFilter = new GuiceFilter();
    guiceFilter.init(new FilterConfig() {

        public String getFilterName() {
            return "guice";
        }

        public String getInitParameter(final String name) {
            return null;
        }

        @SuppressWarnings("unchecked")
        public Enumeration getInitParameterNames() {
            return new Vector<String>().elements();
        }

        public ServletContext getServletContext() {
            return servletContext;
        }

    });

    final FilterChain chain = new FilterChain() {

        public void doFilter(final ServletRequest request, final ServletResponse response)
                throws IOException, ServletException {
            final PluginRegistry pluginRegistry = PluginRegistry.getInstance();
            final GuicePlugin guicePlugin = new GuicePlugin();
            try {
                guicePlugin.initialize(servletContext);
                guicePlugin.ready();
                pluginRegistry.register(guicePlugin);
            } catch (final Exception e) {
                throw new ServletException(e);
            }

            final Injector injector = guicePlugin.getInjector();
            System.out.println(injector);

            final PathResolverProvider pathResolverProvider = ProviderFactory.get(PathResolverProvider.class);
            final PathResolver pathResolver = pathResolverProvider.getPathResolver();
            System.out.println(pathResolver);

            final PathTemplateParser pathTemplateParser = injector.getInstance(PathTemplateParser.class);
            System.out.println(pathTemplateParser);
            assertTrue(pathTemplateParser instanceof MyPathTemplateParser);

            final ContainerProvider containerProvider = ProviderFactory.get(ContainerProvider.class);
            final Container container = containerProvider.getContainer();
            final Foo foo = container.lookup(Foo.class);
            System.out.println(foo);
            System.out.println(foo.pathResolver);

            assertSame(pathResolver, foo.pathResolver);

            try {
                final Baz baz = injector.getInstance(Baz.class);
                System.out.println(baz);
                fail();
            } catch (final ConfigurationException e) {
                // ok
            }

            final ConverterProvider converterProvider = ProviderFactory.get(ConverterProvider.class);
            System.out.println(converterProvider);
            System.out.println(converterProvider.getConverter(BigDecimalConverter.class));

            final FileUpload fileUpload1 = injector.getInstance(FileUpload.class);
            System.out.println(fileUpload1);
            System.out.println(fileUpload1.getFileItemFactory());

            final FileUpload fileUpload2 = injector.getInstance(FileUpload.class);
            System.out.println(fileUpload2);
            System.out.println(fileUpload2.getFileItemFactory());

            assertNotSame(fileUpload1, fileUpload2);
            assertNotSame(fileUpload1.getFileItemFactory(), fileUpload2.getFileItemFactory());
        }

    };
    guiceFilter.doFilter(request, response, chain);
    cubbyGuiceServletContextListener.contextDestroyed(new ServletContextEvent(servletContext));
    ThreadContext.remove();
}

From source file:org.sindice.summary.rest.SummaryRestContextListener.java

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

    logger.info("initializing SummaryRest context");
    final ServletContext context = sce.getServletContext();
    final XMLConfiguration config = (XMLConfiguration) context.getAttribute("config");

    /*/*from   w  ww . j  ava  2s .  co m*/
     * TODO: Find a better way to get these backend configurations
     */
    final String recommenderBackend = getParameterWithLogging(config, RECOMMENDER_BACKEND,
            BackendType.HTTP.toString());
    final String[] recommenderBackendArgs = getParametersWithLogging(config, RECOMMENDER_BACKEND_ARGS,
            new String[] { "" });
    final String proxyBackend = getParameterWithLogging(config, PROXY_BACKEND, BackendType.HTTP.toString());
    final String[] proxyBackendArgs = getParametersWithLogging(config, PROXY_BACKEND_ARGS, new String[] { "" });

    context.setAttribute(RECOMMENDER_BACKEND, recommenderBackend);
    context.setAttribute(RECOMMENDER_BACKEND_ARGS, recommenderBackendArgs);
    context.setAttribute(PROXY_BACKEND, proxyBackend);
    context.setAttribute(PROXY_BACKEND_ARGS, proxyBackendArgs);

    logger.info("{}={} {}={} {}={} {}={}",
            new Object[] { PROXY_BACKEND, proxyBackend, PROXY_BACKEND_ARGS, Arrays.toString(proxyBackendArgs),
                    RECOMMENDER_BACKEND, recommenderBackend, RECOMMENDER_BACKEND_ARGS,
                    Arrays.toString(recommenderBackendArgs) });
}

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

/**
 * Send error to be displayed inline//from   w  w  w .  j  a va 2  s  .c o m
 */
protected void sendError(ServletContext sc, HttpServletRequest request, HttpServletResponse response,
        Exception e) throws ServletException, IOException {
    sc.setAttribute("exception", e);
    sc.setAttribute("globalResults", null);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

From source file:com.liferay.portal.servlet.MainServlet.java

public void init(ServletConfig config) throws ServletException {
    synchronized (MainServlet.class) {
        super.init(config);
        Config.initializeConfig();/*from   www.ja  v  a  2 s.c  o  m*/
        com.dotmarketing.util.Config.setMyApp(config.getServletContext());
        // Need the plugin root dir before Hibernate comes up
        try {
            APILocator.getPluginAPI()
                    .setPluginJarDir(new File(config.getServletContext().getRealPath("WEB-INF/lib")));
        } catch (IOException e1) {
            Logger.debug(InitServlet.class, "IOException: " + e1.getMessage(), e1);
        }

        // Checking for execute upgrades
        try {
            StartupTasksExecutor.getInstance().executeUpgrades(config.getServletContext().getRealPath("."));
        } catch (DotRuntimeException e1) {
            throw new ServletException(e1);
        } catch (DotDataException e1) {
            throw new ServletException(e1);
        }

        // Starting the reindexation threads
        ClusterThreadProxy.createThread();
        if (Config.getBooleanProperty("DIST_INDEXATION_ENABLED")) {
            ClusterThreadProxy.startThread(Config.getIntProperty("DIST_INDEXATION_SLEEP", 500),
                    Config.getIntProperty("DIST_INDEXATION_INIT_DELAY", 5000));
        }

        ReindexThread.startThread(Config.getIntProperty("REINDEX_THREAD_SLEEP", 500),
                Config.getIntProperty("REINDEX_THREAD_INIT_DELAY", 5000));

        try {
            EventsProcessor.process(new String[] { StartupAction.class.getName() }, true);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Context path

        ServletConfig sc = getServletConfig();
        ServletContext ctx = getServletContext();

        String ctxPath = GetterUtil.get(sc.getInitParameter("ctx_path"), "/");

        ctx.setAttribute(WebKeys.CTX_PATH, StringUtil.replace(ctxPath + "/c", "//", "/"));

        ctx.setAttribute(WebKeys.CAPTCHA_PATH, StringUtil.replace(ctxPath + "/captcha", "//", "/"));

        ctx.setAttribute(WebKeys.IMAGE_PATH, StringUtil.replace(ctxPath + "/image", "//", "/"));

        // Company id

        _companyId = ctx.getInitParameter("company_id");

        ctx.setAttribute(WebKeys.COMPANY_ID, _companyId);

        // Initialize portlets

        try {
            String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")),
                    Http.URLtoString(ctx.getResource("/WEB-INF/portlet-ext.xml")),
                    Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")),
                    Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet-ext.xml")) };

            PortletManagerUtil.initEAR(xmls);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Initialize portlets display

        try {
            String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml"));

            Map oldCategories = (Map) WebAppPool.get(_companyId, WebKeys.PORTLET_DISPLAY);

            Map newCategories = PortletManagerUtil.getEARDisplay(xml);

            Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories);

            WebAppPool.put(_companyId, WebKeys.PORTLET_DISPLAY, mergedCategories);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Initialize skins
        //
        //         try {
        //            String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/liferay-skin.xml")),
        //                  Http.URLtoString(ctx.getResource("/WEB-INF/liferay-skin-ext.xml")) };
        //
        //            SkinManagerUtil.init(xmls);
        //         } catch (Exception e) {
        //            Logger.error(this, e.getMessage(), e);
        //         }

        // Check company

        try {
            CompanyLocalManagerUtil.checkCompany(_companyId);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Check web settings

        try {
            String xml = Http.URLtoString(ctx.getResource("/WEB-INF/web.xml"));

            _checkWebSettings(xml);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Scheduler

        // try {
        // Iterator itr =
        // PortletManagerUtil.getPortlets(_companyId).iterator();
        //
        // while (itr.hasNext()) {
        // Portlet portlet = (Portlet)itr.next();
        //
        // String className = portlet.getSchedulerClass();
        //
        // if (portlet.isActive() && className != null) {
        // Scheduler scheduler =
        // (Scheduler)InstancePool.get(className);
        //
        // scheduler.schedule();
        // }
        // }
        // }
        // catch (ObjectAlreadyExistsException oaee) {
        // }
        // catch (Exception e) {
        // Logger.error(this,e.getMessage(),e);
        // }

        // Message Resources

        MultiMessageResources messageResources = (MultiMessageResources) ctx.getAttribute(Globals.MESSAGES_KEY);

        messageResources.setServletContext(ctx);

        WebAppPool.put(_companyId, Globals.MESSAGES_KEY, messageResources);

        // Current users

        WebAppPool.put(_companyId, WebKeys.CURRENT_USERS, new TreeMap());

        // HttpBridge

        TaskController.bridgeUserServicePath = "/httpbridge/home";
        TaskController.bridgeHttpServicePath = "/httpbridge/http";
        TaskController.bridgeGotoTag = "(goto)";
        TaskController.bridgeThenTag = "(then)";
        TaskController.bridgePostTag = "(post)";

        // Process startup events

        try {
            EventsProcessor.process(PropsUtil.getArray(PropsUtil.GLOBAL_STARTUP_EVENTS), true);

            EventsProcessor.process(PropsUtil.getArray(PropsUtil.APPLICATION_STARTUP_EVENTS),
                    new String[] { _companyId });
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        PortalInstances.init(_companyId);
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** {@inheritDoc} */
public void init(FilterConfig filterConfig) throws ServletException {
    ServletContext context = filterConfig.getServletContext();
    Configuration conf = new Configuration(false);
    conf.addResource("hdfsproxy-default.xml");
    conf.addResource("ssl-server.xml");
    conf.addResource("hdfsproxy-site.xml");
    String nn = conf.get("hdfsproxy.dfs.namenode.address");
    if (nn == null) {
        throw new ServletException("Proxy source cluster name node address not speficied");
    }//w  w  w  . java  2 s .c  o m
    InetSocketAddress nAddr = NetUtils.createSocketAddr(nn);
    context.setAttribute("name.node.address", nAddr);
    context.setAttribute("name.conf", new Configuration());

    context.setAttribute("org.apache.hadoop.hdfsproxy.conf", conf);
    LOG.info("proxyFilter initialization success: " + nn);
}

From source file:org.red5.server.tomcat.TomcatVHostLoader.java

/**
 * Initialization./*from   w ww.  j ava 2 s  . c  om*/
 */
@SuppressWarnings("cast")
public void init() {
    log.info("Loading tomcat virtual host");

    if (webappFolder != null) {
        //check for match with base webapp root
        if (webappFolder.equals(webappRoot)) {
            log.error("Web application root cannot be the same as base");
            return;
        }
    }

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();

    //ensure we have a host
    if (host == null) {
        host = createHost();
    }

    host.setParentClassLoader(classloader);

    String propertyPrefix = name;
    if (domain != null) {
        propertyPrefix += '_' + domain.replace('.', '_');
    }
    log.debug("Generating name (for props) {}", propertyPrefix);
    System.setProperty(propertyPrefix + ".webapp.root", webappRoot);

    log.info("Virtual host root: {}", webappRoot);

    log.info("Virtual host context id: {}", defaultApplicationContextId);

    // Root applications directory
    File appDirBase = new File(webappRoot);
    // Subdirs of root apps dir
    File[] dirs = appDirBase.listFiles(new TomcatLoader.DirectoryFilter());
    // Search for additional context files
    for (File dir : dirs) {
        String dirName = '/' + dir.getName();
        // check to see if the directory is already mapped
        if (null == host.findChild(dirName)) {
            String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
            Context ctx = null;
            if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
                log.debug("Adding ROOT context");
                ctx = addContext("/", webappContextDir);
            } else {
                log.debug("Adding context from directory scan: {}", dirName);
                ctx = addContext(dirName, webappContextDir);
            }
            log.debug("Context: {}", ctx);
            webappContextDir = null;
        }
    }
    appDirBase = null;
    dirs = null;

    // Dump context list
    if (log.isDebugEnabled()) {
        for (Container cont : host.findChildren()) {
            log.debug("Context child name: {}", cont.getName());
        }
    }

    engine.addChild(host);

    // Start server
    try {
        log.info("Starting Tomcat virtual host");

        //may not have to do this step for every host
        LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext));

        for (Container cont : host.findChildren()) {
            if (cont instanceof StandardContext) {
                StandardContext ctx = (StandardContext) cont;

                ServletContext servletContext = ctx.getServletContext();
                log.debug("Context initialized: {}", servletContext.getContextPath());

                //set the hosts id
                servletContext.setAttribute("red5.host.id", getHostId());

                String prefix = servletContext.getRealPath("/");
                log.debug("Path: {}", prefix);

                try {
                    Loader cldr = ctx.getLoader();
                    log.debug("Loader type: {}", cldr.getClass().getName());
                    ClassLoader webClassLoader = cldr.getClassLoader();
                    log.debug("Webapp classloader: {}", webClassLoader);
                    //create a spring web application context
                    XmlWebApplicationContext appctx = new XmlWebApplicationContext();
                    appctx.setClassLoader(webClassLoader);
                    appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" });
                    //check for red5 context bean
                    if (applicationContext.containsBean(defaultApplicationContextId)) {
                        appctx.setParent(
                                (ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
                    } else {
                        log.warn("{} bean was not found in context: {}", defaultApplicationContextId,
                                applicationContext.getDisplayName());
                        //lookup context loader and attempt to get what we need from it
                        if (applicationContext.containsBean("context.loader")) {
                            ContextLoader contextLoader = (ContextLoader) applicationContext
                                    .getBean("context.loader");
                            appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
                        } else {
                            log.debug("Context loader was not found, trying JMX");
                            MBeanServer mbs = JMXFactory.getMBeanServer();
                            //get the ContextLoader from jmx
                            ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader");
                            ContextLoaderMBean proxy = null;
                            if (mbs.isRegistered(oName)) {
                                proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs,
                                        oName, ContextLoaderMBean.class, true);
                                log.debug("Context loader was found");
                                appctx.setParent(proxy.getContext(defaultApplicationContextId));
                            } else {
                                log.warn("Context loader was not found");
                            }
                        }
                    }
                    if (log.isDebugEnabled()) {
                        if (appctx.getParent() != null) {
                            log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
                        }
                    }
                    //
                    appctx.setServletContext(servletContext);
                    //set the root webapp ctx attr on the each servlet context so spring can find it later               
                    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                            appctx);
                    appctx.refresh();
                } catch (Throwable t) {
                    log.error("Error setting up context: {}", servletContext.getContextPath(), t);
                    if (log.isDebugEnabled()) {
                        t.printStackTrace();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Error loading Tomcat virtual host", e);
    }

}

From source file:com.nmote.xr.spring.XRSpringExporter.java

public void setServletContext(ServletContext servletContext) {
    Assert.notNull(servers);//from  w ww .  j  a v  a  2 s . c  o  m
    Assert.notEmpty(servers);

    // Save servlet context for destroy
    this.servletContext = servletContext;

    ObjectEndpoint endpoint = new ObjectEndpoint();
    for (@SuppressWarnings("rawtypes")
    XRExportDef e : servers) {
        endpoint.prefix(e.getPrefix());
        endpoint.faultMapper(e.getFaultMapper() != null ? e.getFaultMapper() : faultMapper);
        endpoint.typeConverter(typeConverter);
        endpoint.export(e.getServer(), e.getExport());
    }

    // Export system.* methods
    if (exportMeta) {
        endpoint.prefix(null);
        endpoint.faultMapper(faultMapper);
        endpoint.exportMeta();
    }

    servletContext.setAttribute(endpointKey, prepare(endpoint));
}