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:com.ikon.servlet.admin.ReportServlet.java

/**
 * List reports parameters/*from   ww  w  .  j  a  v  a  2  s  . c  o  m*/
 */
private void paramList(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException, ParseException {
    log.debug("paramList({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    int rpId = WebUtils.getInt(request, "rp_id");
    List<FormElement> params = ReportUtils.getReportParameters(rpId);
    List<Map<String, String>> fMaps = new ArrayList<Map<String, String>>();

    for (FormElement fe : params) {
        fMaps.add(FormUtils.toString(fe));
    }

    sc.setAttribute("rp_id", rpId);
    sc.setAttribute("params", fMaps);
    sc.getRequestDispatcher("/admin/report_param_list.jsp").forward(request, response);
    log.debug("paramList: void");
}

From source file:org.red5.server.war.WarLoaderServlet.java

public void registerSubContext(String webAppKey) {
    // get the sub contexts - servlet context
    ServletContext ctx = servletContext.getContext(webAppKey);
    if (ctx == null) {
        ctx = servletContext;/*from   ww w  . ja  va  2s  .com*/
    }
    ContextLoader loader = new ContextLoader();
    ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader
            .initWebApplicationContext(ctx);
    appCtx.setParent(applicationContext);
    appCtx.refresh();

    ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);

    ConfigurableBeanFactory appFactory = appCtx.getBeanFactory();

    logger.debug("About to grab Webcontext bean for " + webAppKey);
    Context webContext = (Context) appCtx.getBean("web.context");
    webContext.setCoreBeanFactory(parentFactory);
    webContext.setClientRegistry(clientRegistry);
    webContext.setServiceInvoker(globalInvoker);
    webContext.setScopeResolver(globalResolver);
    webContext.setMappingStrategy(globalStrategy);

    WebScope scope = (WebScope) appFactory.getBean("web.scope");
    scope.setServer(server);
    scope.setParent(global);
    scope.register();
    scope.start();

    // register the context so we dont try to reinitialize it
    registeredContexts.add(ctx);

}

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 w w  . j  a v  a  2s.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:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/** {@inheritDoc} */
public void init(FilterConfig filterConfig) throws ServletException {
    ServletContext context = filterConfig.getServletContext();

    contextPath = context.getContextPath();

    Configuration conf = new Configuration(false);
    conf.addResource("hdfsproxy-default.xml");
    conf.addResource("hdfsproxy-site.xml");
    // extract namenode from source conf.
    String nn = getNamenode(conf);

    InetSocketAddress nAddr = NetUtils.createSocketAddr(nn);
    context.setAttribute("name.node.address", nAddr);
    context.setAttribute("name.conf", conf);
    context.setAttribute(JspHelper.CURRENT_CONF, conf);

    // for storing hostname <--> cluster mapping to decide which source cluster
    // to forward
    context.setAttribute("org.apache.hadoop.hdfsproxy.conf", conf);

    if (lctx == null) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(InitialLdapContext.INITIAL_CONTEXT_FACTORY,
                conf.get("hdfsproxy.ldap.initial.context.factory", "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(InitialLdapContext.PROVIDER_URL, conf.get("hdfsproxy.ldap.provider.url"));

        try {//from  w  ww  .j  a v  a  2 s. c  om
            lctx = new InitialLdapContext(env, null);
        } catch (NamingException ne) {
            throw new ServletException("NamingException in initializing ldap" + ne.toString());
        }

        baseName = conf.get("hdfsproxy.ldap.role.base");
        hdfsIpSchemaStr = conf.get("hdfsproxy.ldap.ip.schema.string", "uniqueMember");
        hdfsIpSchemaStrPrefix = conf.get("hdfsproxy.ldap.ip.schema.string.prefix", "cn=");
        hdfsUidSchemaStr = conf.get("hdfsproxy.ldap.uid.schema.string", "uid");
        hdfsPathSchemaStr = conf.get("hdfsproxy.ldap.hdfs.path.schema.string", "documentLocation");
    }
    LOG.info(contextPath + ":: LdapIpDirFilter initialization successful");
}

From source file:org.jboss.web.tomcat.tc5.WebCtxLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 *///  w  w w  .  j a  v  a  2s . co  m
private void setClassPath() {
    // Validate our current state information
    if (!(webContainer instanceof Context))
        return;
    ServletContext servletContext = ((Context) webContainer).getServletContext();
    if (servletContext == null)
        return;

    try {
        Method method = webContainer.getClass().getMethod("getCompilerClasspath", null);
        Object baseClasspath = method.invoke(webContainer, null);
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath.toString());
            return;
        }
    } catch (Exception e) {
        // Ignore
        e.printStackTrace();
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our repositories
    for (int i = 0; i < repositories.size(); i++) {
        String repository = repositories.get(i).toString();
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else if (repository.startsWith("jndi:"))
            repository = servletContext.getRealPath(repository.substring(5));
        else
            continue;
        if (repository == null)
            continue;
        if (i > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    // Store the assembled class path as a servlet context attribute
    servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());

}

From source file:org.apache.struts2.views.zipscript.ZipScriptResult.java

/**
 * Creates a ZipScript context from the action, loads a ZipScript template and
 * executes the template. Output is written to the servlet output stream.
 * // w  w  w . ja  v  a  2s  . co  m
 * @param finalLocation
 *            the location of the ZipScript template
 * @param invocation
 *            an encapsulation of the action execution state.
 * @throws Exception
 *             if an error occurs when creating the ZipScript context,
 *             loading or executing the template or writing output to the
 *             servlet response stream.
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    ResultData resultData = new ResultData(finalLocation);

    // get working values
    ValueStack stack = ActionContext.getContext().getValueStack();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    JspFactory jspFactory = null;
    ServletContext servletContext = ServletActionContext.getServletContext();
    Servlet servlet = JspSupportServlet.jspSupportServlet;

    if (null == zipScriptManager) {
        zipScriptManager = (ZipScriptManager) servletContext.getAttribute(ZipScriptManager.class.getName());
        if (null == zipScriptManager) {
            zipScriptManager = new ZipScriptManager();
            servletContext.setAttribute(ZipScriptManager.class.getName(), zipScriptManager);
        }
    }

    ZipEngine zipEngine = zipScriptManager.getZipEngine(servletContext);

    boolean usedJspFactory = false;
    PageContext pageContext = (PageContext) ActionContext.getContext().get(ServletActionContext.PAGE_CONTEXT);

    if (pageContext == null && servlet != null) {
        jspFactory = JspFactory.getDefaultFactory();
        pageContext = jspFactory.getPageContext(servlet, request, response, null, true, 8192, true);
        ActionContext.getContext().put(ServletActionContext.PAGE_CONTEXT, pageContext);
        usedJspFactory = true;
    }

    try {
        String encoding = getEncoding(finalLocation);
        String contentType = getContentType(finalLocation);

        if (encoding != null) {
            contentType = contentType + ";charset=" + encoding;
        }

        Writer writer = new OutputStreamWriter(response.getOutputStream(), encoding);
        Context context = zipScriptManager.createContext(invocation, resultData, request);
        loadContext(context);

        writeOutput(context, stack, zipEngine, invocation, resultData, servletContext, request, response,
                writer);

        response.setContentType(contentType);
        writer.flush();
    } catch (Exception e) {
        log.error("Unable to render ZipScript Template, '" + finalLocation + "'", e);
        throw e;
    } catch (Throwable e) {
        log.error("Unable to render ZipScript Template, '" + finalLocation + "'", e);
        throw new Exception(e);
    } finally {
        if (usedJspFactory) {
            jspFactory.releasePageContext(pageContext);
        }
    }
    return;
}

From source file:com.jaspersoft.jasperserver.war.util.SpringBeanServletContextPlublisher.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();
    ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    String beanNamesAttr = servletContext.getInitParameter(ATTRIBUTE_BEAN_NAMES);
    String[] beanNames = beanNamesAttr.split("\\,");
    for (int i = 0; i < beanNames.length; i++) {
        String beanName = beanNames[i];
        Object bean = applicationContext.getBean(beanName);
        if (bean == null) {
            log.warn("Bean \"" + beanName + "\" not found");
        } else {//from  ww w .j a  va  2 s .  c o  m
            servletContext.setAttribute(beanName, bean);

            if (log.isDebugEnabled()) {
                log.debug("Bean \"" + beanName + "\" published in the application context");
            }
        }
    }
}

From source file:org.josso.liferay5.agent.LiferaySSOAgentFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    // Validate and update our current component state
    ServletContext ctx = filterConfig.getServletContext();
    ctx.setAttribute(KEY_SESSION_MAP, new HashMap());

    if (_agent == null) {

        try {//from   ww w.j ava2 s  .  c  o  m

            Lookup lookup = Lookup.getInstance();
            lookup.init("josso-agent-config.xml"); // For spring compatibility ...

            // We need at least an abstract SSO Agent
            _agent = (HttpSSOAgent) lookup.lookupSSOAgent();
            if (log.isDebugEnabled())
                _agent.setDebug(1);
            _agent.start();

            // Publish agent in servlet context
            filterConfig.getServletContext().setAttribute("org.josso.agent", _agent);

        } catch (Exception e) {
            throw new ServletException("Error starting SSO Agent : " + e.getMessage(), e);
        }
    }
}

From source file:org.reficio.ws.server.core.SoapServer.java

private void configureWebContext() {
    ServletContext servletContext = getServletContext();
    GenericWebApplicationContext webContext = new GenericWebApplicationContext();
    webContext.setServletContext(servletContext);
    webContext.setParent(context);/* ww  w  . j  av a 2 s .  c  o  m*/
    webContext.refresh();
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
    if (webContext != null) {
        endpoint = webContext.getBean(SoapServerConstants.ENDPOINT_BEAN_NAME, GenericContextDomEndpoint.class);
    }
}

From source file:com.github.glue.mvc.general.DefaultConfigListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    super.contextInitialized(servletContextEvent);
    final ServletContext servletContext = servletContextEvent.getServletContext();
    container = new DefaultContainer();
    MvcConfig mvcConfig = createViewConfig();
    RequestDefinitionScanner scanner = new RequestDefinitionScanner(mvcConfig.getActionPackages());
    container.bind(RequestDefinitionScanner.class.getName(), scanner);

    for (ViewResolver resolver : mvcConfig.getViewResolvers()) {
        container.bind(resolver.getClass().getName() + ":" + resolver.getViewName(), resolver);
    }//from  www  . jav a 2  s  .c o  m
    container.bind(ViewConfig.class.getName(), new DefaultViewConfig(container));

    servletContext.setAttribute(CONTAINER, container);
}