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:dinistiq.web.DinistiqContextLoaderListener.java

/**
 * Web related dinistiq initialization with parameters taken from the web.xml.
 *
 * Looks up relevant packages for scanning and a custom class resolver's implementation class name. Exposes any
 * bean from the dinistiq scope to the application scope (servlet context) of the web layer including an instance
 * of dinistiq itself./*from  w ww.j  a  v a2  s  .com*/
 *
 * @param contextEvent
 */
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    // just to check what our log instance looks like
    LOG.warn("contextInitialized() log: {}", LOG.getClass().getName());
    ServletContext context = contextEvent.getServletContext();
    Set<String> packages = new HashSet<>();
    String packagNameString = context.getInitParameter(DINISTIQ_PACKAGES);
    if (StringUtils.isNotBlank(packagNameString)) {
        for (String packageName : packagNameString.split(",")) {
            packageName = packageName.trim();
            packages.add(packageName);
        } // for
    } // if
    String classResolverName = context.getInitParameter(DINISTIQ_CLASSRESOLVER);
    ClassResolver classResolver = null;
    if (StringUtils.isNotBlank(classResolverName)) {
        try {
            Class<?> forName = Class.forName(classResolverName);
            Object[] args = new Object[1];
            args[0] = packages;
            classResolver = (ClassResolver) forName.getConstructors()[0].newInstance(args);
        } catch (Exception e) {
            LOG.error("contextInitialized() cannot obtain custom class resolver", e);
        } // try/catch
    } // if
    LOG.info("contextInitialized() classResolver: {} :{}", classResolver, classResolverName);
    classResolver = (classResolver == null) ? new SimpleClassResolver(packages) : classResolver;
    try {
        Map<String, Object> externalBeans = new HashMap<>();
        externalBeans.put("servletContext", context);
        Dinistiq dinistiq = new Dinistiq(classResolver, externalBeans);
        context.setAttribute(DINISTIQ_INSTANCE, dinistiq);
        for (String name : dinistiq.getAllBeanNames()) {
            context.setAttribute(name, dinistiq.findBean(Object.class, name));
        } // for
        Collection<RegisterableServlet> servlets = dinistiq.findBeans(RegisterableServlet.class);
        List<RegisterableServlet> orderedServlets = new ArrayList<>(servlets.size());
        orderedServlets.addAll(servlets);
        Collections.sort(orderedServlets);
        LOG.debug("contextInitialized() servlets {}", orderedServlets);
        for (RegisterableServlet servlet : orderedServlets) {
            ServletRegistration registration = context.addServlet(servlet.getClass().getSimpleName(), servlet);
            for (String urlPattern : servlet.getUrlPatterns()) {
                LOG.debug("contextInitialized() * {}", urlPattern);
                registration.addMapping(urlPattern);
            } // for
        } // for
    } catch (Exception ex) {
        LOG.error("init()", ex);
    } // try/catch
}

From source file:com.gisgraphy.webapp.listener.StartupListener.java

@SuppressWarnings({ "unchecked" })
public void contextInitialized(ServletContextEvent event) {
    log.debug("initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }/*from   ww w .  j  a v  a  2 s. c o  m*/

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    boolean encryptPassword = true;

    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean(ctx.getBeanNamesForType(ProviderManager.class)[0]);
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            }
            config.put(Constants.ENCRYPT_PASSWORD, Boolean.TRUE);
            config.put(Constants.ENC_ALGORITHM, "SHA");
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        log.debug("Encrypt Passwords? " + encryptPassword);
        if (encryptPassword) {
            log.debug("Encryption Algorithm: " + config.get(Constants.ENC_ALGORITHM));
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);
}

From source file:com.happyuno.controller.JoinGameTable.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?// w  w  w .j av  a 2  s .  c om
    String tableId = (String) request.getParameter("tableId");
    //      int tableId =Integer.parseInt(request.getSession().getAttribute("tableId").toString());

    //      String setNum = request.getParameter("setNum").trim();

    //      
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    //?ID user
    String userId = (String) request.getSession().getAttribute("userId");
    maindeal md = new maindeal();
    List dbUserList = md.query("from User as u where u.id='" + userId + "'");
    User curUser = (User) dbUserList.get(0);

    //
    String resultMessage = "?";
    int index = Integer.parseInt(tableId);
    System.out.println(index);
    //
    GameTable gametable = gameTableMap.get(index);
    if (gametable == null) {
        System.out.println("true");
    }

    int defiNum = gametable.getDefiNum();

    //
    if (gametable.isStateStart() == false) { //?
        if (gametable.getUserList().size() < defiNum) { //??
            if (!gametable.getUserList().contains(curUser)) {
                gametable.getUserList().add(curUser);
            }
            resultMessage = "??";
        } else {
            resultMessage = "???";
        }
    } else {
        resultMessage = "????";
    }

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //??
    HttpSession session = request.getSession();
    session.setAttribute("tableId", index);
    session.setAttribute("userList", gameTableMap.get(index).getUserList());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/waiting.jsp");
    dispatcher.forward(request, response);

    //      PrintWriter out = response.getWriter();
    //      out.print("ID");
    //      out.println(userId);
    //      out.print("?:");
    //      out.println(resultMessage);
    //      out.print("?");
    //      out.println(gametable.getUserList().size());

}

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

/**
 * Execute Hibernate query//  ww w.ja v a 2s  . c  om
 */
private void executeHibernate(Session session, String qs, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException, HibernateException,
        DatabaseException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    StringTokenizer st = new StringTokenizer(qs, "\n\r");
    List<GlobalResult> globalResults = new ArrayList<DatabaseQueryServlet.GlobalResult>();

    // For each query line
    while (st.hasMoreTokens()) {
        String tk = st.nextToken().trim();

        if (tk.toUpperCase().startsWith("--") || tk.equals("") || tk.equals("\r")) {
            // Is a comment, so ignore it
        } else {
            if (tk.endsWith(";")) {
                tk = tk.substring(0, tk.length() - 1);
            }

            globalResults.add(executeHQL(session, tk, null));
        }
    }

    //sc.setAttribute("sql", HibernateUtil.toSql(qs));
    sc.setAttribute("exception", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

From source file:com.happyuno.controller.StartGame.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*  w  w  w  .j  a  v  a 2 s . c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?tableId
    String tableId = (String) request.getParameter("tableId");

    System.out.println(tableId);
    //?userId
    String userId = (String) request.getSession().getAttribute("userId");

    //
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    String resultMessage = "??";

    //User??Player
    ArrayList<Player> players = new ArrayList<Player>();

    int tindex = Integer.parseInt(tableId);
    GameTable gt = gameTableMap.get(tindex);
    ArrayList<User> userList = gt.getUserList();

    resultMessage = "??";
    //????
    gt.setStateStart(true);
    System.out.println(userList.size() + "changdu");
    for (int i = 0; i < userList.size(); i++) {
        //Playerid,nameUser?
        System.out.println(i + "position");
        String curUserId = ((User) userList.get(i)).getId();
        System.out.println("UserId" + curUserId);
        int cUserId = Integer.parseInt(curUserId);
        String curUserName = ((User) userList.get(i)).getName();
        Player curPlayer = new Player(cUserId, curUserName);
        players.add(curPlayer);
    }
    gt.getCurrentGame().initGame(players);

    HttpSession session = request.getSession();
    session.setAttribute("tableId", tindex);
    session.setAttribute("players", players);
    session.setAttribute("curPlayerId", Integer.parseInt(userId));

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //tableMap?
    application.setAttribute("tatoNum", gameTableMap.size());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/table.jsp");
    dispatcher.forward(request, response);

}

From source file:jeeves.monitor.MonitorManager.java

public void init(ServletContext context, String baseUrl) {

    String webappName = "";

    if (StringUtils.isNotEmpty(baseUrl)) {
        webappName = baseUrl.substring(1);
    }//from   w w w  .  ja v a2 s .  c o  m

    if (context != null) {
        HealthCheckRegistry tmpHealthCheckRegistry = lookUpHealthCheckRegistry(context, HEALTH_CHECK_REGISTRY);
        HealthCheckRegistry criticalTmpHealthCheckRegistry = lookUpHealthCheckRegistry(context,
                CRITICAL_HEALTH_CHECK_REGISTRY);
        HealthCheckRegistry warningTmpHealthCheckRegistry = lookUpHealthCheckRegistry(context,
                WARNING_HEALTH_CHECK_REGISTRY);
        HealthCheckRegistry expensiveTmpHealthCheckRegistry = lookUpHealthCheckRegistry(context,
                EXPENSIVE_HEALTH_CHECK_REGISTRY);

        healthCheckRegistry = tmpHealthCheckRegistry;
        criticalHealthCheckRegistry = criticalTmpHealthCheckRegistry;
        warningHealthCheckRegistry = warningTmpHealthCheckRegistry;
        expensiveHealthCheckRegistry = expensiveTmpHealthCheckRegistry;

        MetricsRegistry tmpMetricsRegistry = (MetricsRegistry) context.getAttribute(METRICS_REGISTRY);
        if (tmpMetricsRegistry == null) {
            tmpMetricsRegistry = new MetricsRegistry();
        }

        metricsRegistry = tmpMetricsRegistry;
        context.setAttribute(METRICS_REGISTRY, tmpMetricsRegistry);

        jmxReporter = new GeonetworkJmxReporter(metricsRegistry, webappName);
        jmxReporter.start();
    } else {
        healthCheckRegistry = new HealthCheckRegistry();
        criticalHealthCheckRegistry = new HealthCheckRegistry();
        warningHealthCheckRegistry = new HealthCheckRegistry();
        expensiveHealthCheckRegistry = new HealthCheckRegistry();
        metricsRegistry = new MetricsRegistry();

        jmxReporter = new GeonetworkJmxReporter(metricsRegistry, webappName);
        jmxReporter.start();

    }

    LogManager.getRootLogger().addAppender(new InstrumentedAppender(metricsRegistry));
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private void bindWithRequestAndPropertyValues(ServletRequest request, MutablePropertyValues mpvs) {
    GrailsWebRequest webRequest = GrailsWebRequest.lookup((HttpServletRequest) request);
    if (webRequest != null) {
        final ApplicationContext applicationContext = webRequest.getApplicationContext();
        if (applicationContext != null) {
            ServletContext servletContext = webRequest.getServletContext();
            @SuppressWarnings("unchecked")
            Map<String, BindEventListener> bindEventListenerMap = (Map<String, BindEventListener>) servletContext
                    .getAttribute(BIND_EVENT_LISTENERS);
            if (bindEventListenerMap == null) {
                bindEventListenerMap = applicationContext.getBeansOfType(BindEventListener.class);
                if (!Environment.isDevelopmentMode()) {
                    servletContext.setAttribute(BIND_EVENT_LISTENERS, bindEventListenerMap);
                }//w ww  .  java 2s .  co m
            }
            for (BindEventListener bindEventListener : bindEventListenerMap.values()) {
                bindEventListener.doBind(getTarget(), mpvs, getTypeConverter());
            }
        }
    }
    preProcessMutablePropertyValues(mpvs);

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
    }
    doBind(mpvs);
}

From source file:org.openhie.openempi.webapp.listener.StartupListener.java

@SuppressWarnings({ "unchecked" })
public void contextInitialized(ServletContextEvent event) {
    log.debug("Initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }/*from  w w w .  j  av  a 2  s.  c  o m*/

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
        config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*String[] beans = ctx.getBeanDefinitionNames();
    for (String bean : beans) {
    log.debug(bean);
    }*/

    PasswordEncoder passwordEncoder = null;
    try {
        ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager");
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            log.debug("Password Encoder: " + passwordEncoder.getClass().getName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

private void setupClassSummaryInformation(ServletContext servletContext, ObjectStoreSummary oss,
        final Model model) {
    Map<String, String> classes = new LinkedHashMap<String, String>();
    Map<String, Integer> classCounts = new LinkedHashMap<String, Integer>();

    for (String className : new TreeSet<String>(model.getClassNames())) {
        if (!className.equals(InterMineObject.class.getName())) {
            classes.put(className, TypeUtil.unqualifiedName(className));
        }/*  w ww .j a va  2 s .  co m*/
        try {
            classCounts.put(className, new Integer(oss.getClassCount(className)));
        } catch (Exception e) {
            LOG.error("Unable to get class count for " + className, e);
            blockingErrorKeys.put("errors.init.objectstoresummary.classcount", e.getMessage());
        }
    }
    servletContext.setAttribute("classes", classes);
    servletContext.setAttribute("classCounts", classCounts);
    // Build subclass lists for JSPs
    Map<String, List<String>> subclassesMap = new LinkedHashMap<String, List<String>>();
    for (ClassDescriptor cld : model.getClassDescriptors()) {
        ArrayList<String> subclasses = new ArrayList<String>();
        for (String thisClassName : new TreeSet<String>(getChildren(cld))) {
            if (classCounts.get(thisClassName).intValue() > 0) {
                subclasses.add(TypeUtil.unqualifiedName(thisClassName));
            }
        }
        subclassesMap.put(TypeUtil.unqualifiedName(cld.getName()), subclasses);
    }
    servletContext.setAttribute(Constants.SUBCLASSES, subclassesMap);
}

From source file:org.apache.pluto.driver.PortalStartupListener.java

/**
 * Initializes the portlet container. This method constructs and initializes
 * the portlet container, and saves it to the servlet context scope.
 *
 * @param servletContext the servlet context.
 */// ww w  .java 2s . com
private void initContainer(ServletContext servletContext) {

    WebApplicationContext springContext = (WebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    // Retrieve the driver configuration from servlet context.
    DriverConfiguration driverConfig = (DriverConfiguration) servletContext.getAttribute(DRIVER_CONFIG_KEY);

    try {
        LOG.info("Initializing Portlet Container. . .");

        LOG.debug(" [1] Loading RequiredContainerServices. . .");
        RequiredContainerServices required = (RequiredContainerServices) springContext
                .getBean("RequiredContainerServices");

        LOG.debug(" [2] Loading OptionalContainerServices. . .");
        OptionalContainerServices optional = (OptionalContainerServices) springContext
                .getBean("OptionalContainerServices");

        // Create portlet container.
        LOG.debug(" [3] Creating portlet container...");
        PortletContainerFactory factory = PortletContainerFactory.getInstance();
        PortletContainer container = factory.createContainer(driverConfig.getContainerName(), required,
                optional);

        // Initialize portlet container.
        LOG.debug(" [4] Initializing portlet container...");
        container.init();

        // Save portlet container to the servlet context scope.
        servletContext.setAttribute(CONTAINER_KEY, container);
        LOG.info("Pluto portlet container started.");

    } catch (DriverConfigurationException ex) {
        LOG.error("Unable to retrieve driver configuration " + "due to configuration error: " + ex.getMessage(),
                ex);
    } catch (PortletContainerException ex) {
        LOG.error("Unable to start up portlet container: " + ex.getMessage(), ex);
    }
}