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.apache.struts.webapp.tiles.portal.UserMenuAction.java

/**
 * Get catalog of available menu entries.
 * This implementation creates catalog list from the provided menu bar 
 * entries.//from www .ja  v a  2  s  .  co m
 */
public static List getCatalog(ComponentContext context, HttpServletRequest request,
        ServletContext servletContext) throws ServletException {

    // Retrieve name used to store catalog in application context.
    // If not found, use default name
    String catalogName = (String) context.getAttribute(MENU_CATALOG_NAME_ATTRIBUTE);

    if (catalogName == null) {
        catalogName = DEFAULT_MENU_CATALOG_NAME;
    }

    // Get catalog from context
    List catalog = (List) servletContext.getAttribute(catalogName);

    // If not found, initialize it from provided default menu
    if (catalog == null) {
        Object menuBar = context.getAttribute(CATALOG_SETTING_ATTRIBUTE);
        if (menuBar == null) {
            throw new ServletException("Attribute '" + CATALOG_SETTING_ATTRIBUTE
                    + "' must be set. It define entries used in catalog");
        }

        catalog = new ArrayList();
        extractItems(catalog, menuBar, request, servletContext);
        if (catalog.size() == 0) {
            throw new ServletException("Can't initialize menu items catalog");
        }

        // save it for future use
        servletContext.setAttribute(catalogName, catalog);
    }

    return catalog;
}

From source file:org.apache.solr.security.KerberosPlugin.java

@VisibleForTesting
protected FilterConfig getInitFilterConfig(Map<String, Object> pluginConfig, boolean skipKerberosChecking) {
    Map<String, String> params = new HashMap();
    params.put("type", "kerberos");
    putParam(params, "kerberos.name.rules", NAME_RULES_PARAM, "DEFAULT");
    putParam(params, "token.valid", TOKEN_VALID_PARAM, "30");
    putParam(params, "cookie.path", COOKIE_PATH_PARAM, "/");
    if (!skipKerberosChecking) {
        putParam(params, "kerberos.principal", PRINCIPAL_PARAM, null);
        putParam(params, "kerberos.keytab", KEYTAB_PARAM, null);
    } else {//  w ww  .  j  a v a 2  s . co m
        putParamOptional(params, "kerberos.principal", PRINCIPAL_PARAM);
        putParamOptional(params, "kerberos.keytab", KEYTAB_PARAM);
    }

    String delegationTokenStr = System.getProperty(DELEGATION_TOKEN_ENABLED, null);
    boolean delegationTokenEnabled = (delegationTokenStr == null) ? false
            : Boolean.parseBoolean(delegationTokenStr);
    ZkController controller = coreContainer.getZkController();

    if (delegationTokenEnabled) {
        putParam(params, "delegation-token.token-kind", DELEGATION_TOKEN_KIND, DELEGATION_TOKEN_TYPE_DEFAULT);
        if (coreContainer.isZooKeeperAware()) {
            putParam(params, "signer.secret.provider", DELEGATION_TOKEN_SECRET_PROVIDER, "zookeeper");
            if ("zookeeper".equals(params.get("signer.secret.provider"))) {
                String zkHost = controller.getZkServerAddress();
                putParam(params, "token.validity", DELEGATION_TOKEN_VALIDITY, "36000");
                params.put("zk-dt-secret-manager.enable", "true");

                String chrootPath = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : "";
                String znodeWorkingPath = chrootPath + SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH
                        + "/zkdtsm";
                // Note - Curator complains if the znodeWorkingPath starts with /
                znodeWorkingPath = znodeWorkingPath.startsWith("/") ? znodeWorkingPath.substring(1)
                        : znodeWorkingPath;
                putParam(params, "zk-dt-secret-manager.znodeWorkingPath",
                        DELEGATION_TOKEN_SECRET_MANAGER_ZNODE_WORKING_PATH, znodeWorkingPath);
                putParam(params, "signer.secret.provider.zookeeper.path",
                        DELEGATION_TOKEN_SECRET_PROVIDER_ZK_PATH, "/token");
                // ensure krb5 is setup properly before running curator
                getHttpClientBuilder(SolrHttpClientBuilder.create());
            }
        } else {
            log.info("CoreContainer is not ZooKeeperAware, not setting ZK-related delegation token properties");
        }
    }

    // Special handling for the "cookie.domain" based on whether port should be
    // appended to the domain. Useful for situations where multiple solr nodes are
    // on the same host.
    String usePortStr = System.getProperty(COOKIE_PORT_AWARE_PARAM, null);
    boolean needPortAwareCookies = (usePortStr == null) ? false : Boolean.parseBoolean(usePortStr);

    if (!needPortAwareCookies || !coreContainer.isZooKeeperAware()) {
        putParam(params, "cookie.domain", COOKIE_DOMAIN_PARAM, null);
    } else { // we need port aware cookies and we are in SolrCloud mode.
        String host = System.getProperty(COOKIE_DOMAIN_PARAM, null);
        if (host == null) {
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    "Missing required parameter '" + COOKIE_DOMAIN_PARAM + "'.");
        }
        int port = controller.getHostPort();
        params.put("cookie.domain", host + ":" + port);
    }

    // check impersonator config
    for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements();) {
        String key = e.nextElement().toString();
        if (key.startsWith(IMPERSONATOR_PREFIX)) {
            if (!delegationTokenEnabled) {
                throw new SolrException(ErrorCode.SERVER_ERROR,
                        "Impersonator configuration requires delegation tokens to be enabled: " + key);
            }
            params.put(key, System.getProperty(key));
        }
    }
    final ServletContext servletContext = new AttributeOnlyServletContext();
    if (controller != null) {
        servletContext.setAttribute(DELEGATION_TOKEN_ZK_CLIENT, controller.getZkClient());
    }
    if (delegationTokenEnabled) {
        kerberosFilter = new DelegationTokenKerberosFilter();
        // pass an attribute-enabled context in order to pass the zkClient
        // and because the filter may pass a curator instance.
    } else {
        kerberosFilter = new KerberosFilter();
    }
    log.info("Params: " + params);

    FilterConfig conf = new FilterConfig() {
        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "KerberosFilter";
        }
    };

    return conf;
}

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

/**
 * List languages/*from www. ja  va  2 s  .  c  o m*/
 * 
 * Translations reference is english
 */
private void list(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("list({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    sc.setAttribute("langs", LanguageDAO.findAll());
    sc.setAttribute("max", LanguageDAO.findByPk(Language.DEFAULT).getTranslations().size());
    sc.getRequestDispatcher("/admin/language_list.jsp").forward(request, response);
    log.debug("list: void");
}

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

/**
 * Create language// ww  w  .java 2  s.  c  o  m
 */
private void create(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("edit({}, {}, {})", new Object[] { userId, request, response });

    ServletContext sc = getServletContext();
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("persist", true);
    sc.setAttribute("lg", null);
    sc.getRequestDispatcher("/admin/language_edit.jsp").forward(request, response);

    log.debug("edit: void");
}

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

/**
 * New omr template//w  w  w . ja  va2 s. c om
 */
private void create(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException, ParseException, RepositoryException {
    log.debug("create({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    Omr om = new Omr();
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("om", om);
    sc.setAttribute("properties", PropertyGroupUtils.getAllGroupsProperties());
    sc.getRequestDispatcher("/admin/omr_edit.jsp").forward(request, response);
    log.debug("create: void");
}

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

/**
 * Create language//  w w  w .ja v  a  2  s  .  c  o  m
 */
private void addTranslation(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("addTranslation({}, {}, {})", new Object[] { userId, request, response });

    if (WebUtils.getBoolean(request, "persist")) {
        Language lang = LanguageDAO.findByPk(Language.DEFAULT);
        Translation trans = new Translation();
        trans.getTranslationId().setModule(WebUtils.getString(request, "tr_module"));
        trans.getTranslationId().setKey(WebUtils.getString(request, "tr_key"));
        trans.getTranslationId().setLanguage(lang.getId());
        trans.setText(WebUtils.getString(request, "tr_text"));
        lang.getTranslations().add(trans);
        LanguageDAO.update(lang);
    }

    List<String> modules = new ArrayList<String>();
    modules.add(Translation.MODULE_FRONTEND);
    modules.add(Translation.MODULE_EXTENSION);
    modules.add(Translation.MODULE_ADMINISTRATION);
    ServletContext sc = getServletContext();
    sc.setAttribute("action", WebUtils.getString(request, "action"));
    sc.setAttribute("persist", true);
    sc.setAttribute("tr_module", modules);
    sc.setAttribute("tr_key", "");
    sc.setAttribute("tr_text", "");
    sc.setAttribute("lang", LanguageDAO.findByPk(Language.DEFAULT));
    sc.getRequestDispatcher("/admin/translation_add.jsp").forward(request, response);

    log.debug("addTranslation: void");
}

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

private void addToContext(ServletContext context, Map map) {
    for (Object key : map.keySet()) {
        if (context.getAttribute(key.toString()) == null) {
            context.setAttribute(key.toString(), map.get(key));
        }//from  w w  w.j  av a2  s.c  o m
    }
}

From source file:net.sourceforge.vulcan.web.struts.plugin.SpringMessageResourcesPlugIn.java

@Override
protected void onInit() throws ServletException {
    final WebApplicationContext wac = getWacInternal();

    final ServletContext context = getServletContextInternal();

    if (context.getAttribute(Globals.MESSAGES_KEY) != null) {
        logger.warn("Overriding default MessageResources");
    }/*from  w w  w. java  2 s .c  o m*/

    MessageResources messageResources = new MessageResources(null, null) {
        @Override
        public String getMessage(Locale locale, String key) {
            return wac.getMessage(key, null, locale);
        }
    };

    context.setAttribute(Globals.MESSAGES_KEY, messageResources);
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

/**
 * Does nothing if the user has disabled the SecretKey cache. This is
 * useful when dealing with a JCA provider whose SecretKey 
 * implementation is not thread safe.//from   w  ww .  j  a v  a 2 s  . com
 * 
 * Instantiates a SecretKey instance based upon what the user has 
 * specified in the deployment descriptor.  The SecretKey is then 
 * stored in application scope where it can be used for all requests.
 */

public static void initSecret(ServletContext ctx) {

    if (ctx == null) {
        throw new NullPointerException("ServletContext ctx");
    }

    if (log.isLoggable(Level.FINE)) {
        log.fine("Storing SecretKey @ " + INIT_SECRET_KEY_CACHE);
    }

    // Create and store SecretKey on application scope
    String cache = ctx.getInitParameter(INIT_SECRET_KEY_CACHE);

    if (cache == null) {
        cache = ctx.getInitParameter(INIT_SECRET_KEY_CACHE.toLowerCase());
    }

    if (!"false".equals(cache)) {
        String algorithm = findAlgorithm(ctx);
        // you want to create this as few times as possible
        ctx.setAttribute(INIT_SECRET_KEY_CACHE, new SecretKeySpec(findSecret(ctx, algorithm), algorithm));
    }

    if (log.isLoggable(Level.FINE)) {
        log.fine("Storing SecretKey @ " + INIT_MAC_SECRET_KEY_CACHE);
    }

    String macCache = ctx.getInitParameter(INIT_MAC_SECRET_KEY_CACHE);

    if (macCache == null) {
        macCache = ctx.getInitParameter(INIT_MAC_SECRET_KEY_CACHE.toLowerCase());
    }

    if (!"false".equals(macCache)) {
        String macAlgorithm = findMacAlgorithm(ctx);
        // init mac secret and algorithm 
        ctx.setAttribute(INIT_MAC_SECRET_KEY_CACHE,
                new SecretKeySpec(findMacSecret(ctx, macAlgorithm), macAlgorithm));
    }
}