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.openkm.servlet.admin.DatabaseQueryServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/* w  w w. j  a v a 2s. c om*/
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        sc.setAttribute("qs", null);
        sc.setAttribute("type", null);
        sc.setAttribute("showSql", null);
        sc.setAttribute("exception", null);
        sc.setAttribute("globalResults", null);
        sc.setAttribute("tables", listTables(session));
        sc.setAttribute("vtables", listVirtualTables());
        sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
    } catch (Exception e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

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

/**
 * Collects all PropertyEditorRegistrars in the application context and
 * calls them to register their custom editors
 *
 * @param servletContext/*from   w  w w  .j  a v a2  s .  com*/
 * @param registry The PropertyEditorRegistry instance
 */
private static void registerCustomEditors(ServletContext servletContext, PropertyEditorRegistry registry) {
    if (servletContext == null) {
        return;
    }

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    if (context == null) {
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, PropertyEditorRegistrar> editors = (Map<String, PropertyEditorRegistrar>) servletContext
            .getAttribute(PROPERTY_EDITOR_REGISTRARS);
    if (editors == null) {
        editors = context.getBeansOfType(PropertyEditorRegistrar.class);
        if (!Environment.isDevelopmentMode()) {
            servletContext.setAttribute(PROPERTY_EDITOR_REGISTRARS, editors);
        }
    }
    for (PropertyEditorRegistrar editorRegistrar : editors.values()) {
        editorRegistrar.registerCustomEditors(registry);
    }
}

From source file:ro.cs.om.start.InitApplication.java

/**
 * Initializarea contextului. Aici se preiau nomenclatoarele ce se vor
 * pastra in OMContext//www .j  av  a 2  s.com
 */
public void init(ServletConfig conf) throws ServletException {
    logger.info("Initializare aplicatie...");
    try {

        ServletContext sc = conf.getServletContext();
        logger.info("*******************************************************");
        logger.info("*                                                     *");
        logger.info("*    ORGANISATION MANAGEMENT INITIALISATION: BEGIN    *");
        logger.info("*                                                     *");
        logger.info("*******************************************************");
        logger.info(IConstant.APP_VERSION.concat("/").concat(IConstant.APP_RELEASE_DATE));
        sc.setAttribute("VERSION", IConstant.APP_VERSION);
        sc.setAttribute("RELEASE_DATE", IConstant.APP_RELEASE_DATE);
        sc.setAttribute("RELEASE_YEAR", IConstant.APP_RELEASE_YEAR);

        //CLASSIFIED LISTS
        ListLoader.getInstance().load_nom_module();
        ListLoader.getInstance().load_nom_resultsPerPage();
        ListLoader.getInstance().load_nom_organisationType();
        ListLoader.getInstance().load_nom_group_companies_Type();

        RoleVoter rv = (RoleVoter) OMContext.getApplicationContext().getBean("roleVoter");

        // put permissionConstant bean on servletContext
        sc.setAttribute(IConstant.PERMISSION_CONSTANT, PermissionConstant.getInstance());

        // put exceptionContant bean on servletContect
        sc.setAttribute(IConstant.EXCEPTION_CONSTANT, ExceptionConstant.getInstance());

        // put backConstant on bean on servletContext
        sc.setAttribute(IConstant.BACK_CONSTANT, BackConstant.getInstance());

        // Set on App Context all Organizations' trees
        OMContext.storeOnContext(IConstant.ORGANISATION_TREES,
                BLOrganisationStructure.getInstance().getAllOrganisationTrees());

        //Set on App Context a map specifying which organisation has the audit module
        OMContext.storeOnContext(IConstant.HAS_AUDIT_CONTEXT_MAP, composeHasAuditContextMap());

        // Set up the security context for cross modules authentication and authorization
        OMContext.storeOnContext(IConstant.SECURITY_TOKEN_REPOSITORY, new ConcurrentHashMap<String, Token>());
        SecurityTokenMonitor.getInstance().start();
        logger.debug("Cross modules security context initialized!");

        // initialize scheduler
        initScheduler(true);

        if (isTrialVersion) {
            // manage the trial version timing
            manageTrial();
        }

        // manage the ooo profiles
        manageOOO();

        logger.info("Role Prefix: \"" + rv.getRolePrefix() + "\"");
        logger.info("*******************************************************");
        logger.info("*                                                     *");
        logger.info("*    ORGANISATION MANAGEMENT INITIALISATION: END      *");
        logger.info("*                                                     *");
        logger.info("*******************************************************");

    } catch (Exception ex) {
        logger.info("*******************************************************");
        logger.info("*     EROARE LA INTIALIZAREA APLICATIEI !!!           *");
        logger.info("*******************************************************");
        logger.error("", ex);
    }
    logger.info("Aplicatia a fost initializata...");
}

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

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from  w  w w.j av  a  2  s . c o  m
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        sc.setAttribute("qs", null);
        //sc.setAttribute("sql", null);
        sc.setAttribute("type", null);
        sc.setAttribute("exception", null);
        sc.setAttribute("globalResults", null);
        sc.setAttribute("tables", listTables(session));
        sc.setAttribute("vtables", listVirtualTables());
        sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
    } catch (Exception e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.rapid.forms.RapidFormAdapter.java

protected Map<String, String> getUserFormPageVariableValues(RapidRequest rapidRequest, String formId) {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // get the map of form values
    Map<String, HashMap<String, String>> userFormPageVariableValues = (Map<String, HashMap<String, String>>) servletContext
            .getAttribute(USER_FORM_PAGE_VARIABLE_VALUES);
    // if there aren't any yet
    if (userFormPageVariableValues == null) {
        // make some
        userFormPageVariableValues = new HashMap<String, HashMap<String, String>>();
        // store them
        servletContext.setAttribute(USER_FORM_PAGE_VARIABLE_VALUES, userFormPageVariableValues);
    }/*  ww w.  j  a  v a2  s.  c om*/
    // get the map of values
    HashMap<String, String> formPageVariableValues = userFormPageVariableValues.get(formId);
    // if it's null
    if (formPageVariableValues == null) {
        // make some
        formPageVariableValues = new HashMap<String, String>();
        // store them
        userFormPageVariableValues.put(formId, formPageVariableValues);
    }
    // return
    return formPageVariableValues;
}

From source file:com.facetime.communication.activemq.AmqConsumer.java

protected static synchronized void initConnectionFactory(ServletContext servletContext) {
    if (factory == null) {
        factory = (ConnectionFactory) servletContext.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);
    }/*www  . j a  v  a  2 s .  c o  m*/
    if (factory == null) {
        String brokerURL = servletContext.getInitParameter(BROKER_URL_INIT_PARAM);

        BROKER_URL = brokerURL;

        LOG.debug("Value of: " + BROKER_URL_INIT_PARAM + " is: " + brokerURL);

        if (brokerURL == null) {
            throw new IllegalStateException(
                    "missing brokerURL (specified via " + BROKER_URL_INIT_PARAM + " init-Param");
        }

        ActiveMQConnectionFactory amqfactory = new ActiveMQConnectionFactory(brokerURL);

        // Set prefetch policy for factory
        if (servletContext.getInitParameter(CONNECTION_FACTORY_PREFETCH_PARAM) != null) {
            int prefetch = Integer.valueOf(servletContext.getInitParameter(CONNECTION_FACTORY_PREFETCH_PARAM))
                    .intValue();
            amqfactory.getPrefetchPolicy().setAll(prefetch);
        }

        // Set optimize acknowledge setting
        if (servletContext.getInitParameter(CONNECTION_FACTORY_OPTIMIZE_ACK_PARAM) != null) {
            boolean optimizeAck = Boolean
                    .valueOf(servletContext.getInitParameter(CONNECTION_FACTORY_OPTIMIZE_ACK_PARAM))
                    .booleanValue();
            amqfactory.setOptimizeAcknowledge(optimizeAck);
        }

        factory = amqfactory;

        servletContext.setAttribute(CONNECTION_FACTORY_ATTRIBUTE, factory);
    }
}

From source file:org.red5.server.winstone.WinstoneLoader.java

/**
 * Initialization./* w ww.  j a v  a2s.  co m*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void init() {
    log.info("Loading Winstone context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    // configure the webapps folder, make sure we have one
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // create one embedded (server) and use it everywhere
    Map args = new HashMap();
    //args.put("webroot", webappFolder + "/root");
    args.put("webappsDir", webappFolder);
    // Start server
    try {
        log.info("Starting Winstone servlet engine");
        Launcher.initLogger(args);
        // spawns threads, so your application doesn't block
        embedded = new StoneLauncher(args);
        log.trace("Classloader for embedded: {} TCL: {}", Launcher.class.getClassLoader(), originalClassLoader);
        // get the default host
        HostConfiguration host = embedded.getHostGroup().getHostByName(null);
        // set the primary application loader
        LoaderBase.setApplicationLoader(new WinstoneApplicationLoader(host, applicationContext));
        // get root first, we may want to start a spring config internally but for now skip it
        WebAppConfiguration root = host.getWebAppByURI("/");
        log.trace("Root: {}", root);
        // scan the sub directories to determine our context names
        buildContextNameList(webappFolder);
        // loop the other contexts
        for (String contextName : contextNames) {
            WebAppConfiguration ctx = host.getWebAppByURI(contextName);
            // get access to the servlet context
            final ServletContext servletContext = ctx.getContext(contextName);
            log.debug("Context initialized: {}", servletContext.getContextPath());
            //set the hosts id
            servletContext.setAttribute("red5.host.id", host.getHostname());
            // get the path
            String prefix = servletContext.getRealPath("/");
            log.debug("Path: {}", prefix);
            try {
                final ClassLoader cldr = ctx.getLoader();
                log.debug("Loader type: {}", cldr.getClass().getName());
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                //set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(cldr);
                //create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(cldr);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        //web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, cldr);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class.", e);
                        }
                        appctx.setConfigLocations(new String[] { contextConfigLocation });
                        appctx.setServletContext(servletContext);
                        //set parent context or use current app context
                        if (parentContext != null) {
                            appctx.setParent(parentContext);
                        } else {
                            appctx.setParent(applicationContext);
                        }
                        // 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);
                        //refresh the factory
                        log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                        appctx.refresh();
                        if (log.isDebugEnabled()) {
                            log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                    appctx.isRunning());
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading Winstone, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading Winstone", e);
        }
    } finally {
        registerJMX();
    }

}

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

/**
 * Translate language//from w  w w  .  j  a  va2 s . c o m
 */
private void translate(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("translate({}, {}, {})", new Object[] { userId, request, response });

    if (WebUtils.getBoolean(request, "persist")) {
        Set<Translation> newTranslations = new HashSet<Translation>();
        Language langBase = LanguageDAO.findByPk(Language.DEFAULT);
        Language lang = LanguageDAO.findByPk(request.getParameter("lg_id"));

        for (Translation translation : langBase.getTranslations()) {
            String text = request.getParameter(translation.getTranslationId().getKey());

            if (text != null && !text.equals("")) {
                Translation newTranslation = new Translation();
                newTranslation.getTranslationId().setModule(translation.getTranslationId().getModule());
                newTranslation.getTranslationId().setKey(translation.getTranslationId().getKey());
                newTranslation.getTranslationId().setLanguage(lang.getId());
                newTranslation.setText(text);
                newTranslations.add(newTranslation);
            }
        }

        lang.setTranslations(newTranslations);
        LanguageDAO.update(lang);
    } else {
        ServletContext sc = getServletContext();
        String lgId = WebUtils.getString(request, "lg_id");
        Language langToTranslate = LanguageDAO.findByPk(lgId);
        Map<String, String> translations = new HashMap<String, String>();

        for (Translation translation : langToTranslate.getTranslations()) {
            translations.put(translation.getTranslationId().getKey(), translation.getText());
        }

        sc.setAttribute("action", WebUtils.getString(request, "action"));
        sc.setAttribute("persist", true);
        sc.setAttribute("lg_id", lgId);
        sc.setAttribute("langToTranslateName", langToTranslate.getName());
        sc.setAttribute("translations", translations);
        sc.setAttribute("langBase", LanguageDAO.findByPk(Language.DEFAULT)); // English always it'll be used as a translations base
        sc.getRequestDispatcher("/admin/translation_edit.jsp").forward(request, response);
    }

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

From source file:org.apache.roller.weblogger.ui.core.RollerContext.java

/**
 * Setup Spring Security security features.
 *///from w  w w  . ja  v  a2s  .c o  m
protected void initializeSecurityFeatures(ServletContext context) {

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*String[] beanNames = ctx.getBeanDefinitionNames();
    for (String name : beanNames)
    System.out.println(name);*/

    String rememberMe = WebloggerConfig.getProperty("rememberme.enabled");
    boolean rememberMeEnabled = Boolean.valueOf(rememberMe).booleanValue();

    log.info("Remember Me enabled: " + rememberMeEnabled);

    context.setAttribute("rememberMeEnabled", rememberMe);

    if (!rememberMeEnabled) {
        ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager");
        for (Iterator it = provider.getProviders().iterator(); it.hasNext();) {
            AuthenticationProvider authProvider = (AuthenticationProvider) it.next();
            if (authProvider instanceof RememberMeAuthenticationProvider) {
                provider.getProviders().remove(authProvider);
            }
        }
    }

    String encryptPasswords = WebloggerConfig.getProperty("passwds.encryption.enabled");
    boolean doEncrypt = Boolean.valueOf(encryptPasswords).booleanValue();

    if (doEncrypt) {
        DaoAuthenticationProvider provider = (DaoAuthenticationProvider) ctx
                .getBean("org.springframework.security.providers.dao.DaoAuthenticationProvider#0");
        String algorithm = WebloggerConfig.getProperty("passwds.encryption.algorithm");
        PasswordEncoder encoder = null;
        if (algorithm.equalsIgnoreCase("SHA")) {
            encoder = new ShaPasswordEncoder();
        } else if (algorithm.equalsIgnoreCase("MD5")) {
            encoder = new Md5PasswordEncoder();
        } else {
            log.error("Encryption algorithm '" + algorithm + "' not supported, disabling encryption.");
        }
        if (encoder != null) {
            provider.setPasswordEncoder(encoder);
            log.info("Password Encryption Algorithm set to '" + algorithm + "'");
        }
    }

    if (WebloggerConfig.getBooleanProperty("securelogin.enabled")) {
        AuthenticationProcessingFilterEntryPoint entryPoint = (AuthenticationProcessingFilterEntryPoint) ctx
                .getBean("_formLoginEntryPoint");
        entryPoint.setForceHttps(true);
    }

    /*
    if (WebloggerConfig.getBooleanProperty("schemeenforcement.enabled")) {
            
    ChannelProcessingFilter procfilter =
            (ChannelProcessingFilter)ctx.getBean("channelProcessingFilter");
    ConfigAttributeDefinition secureDef = new ConfigAttributeDefinition();
    secureDef.addConfigAttribute(new SecurityConfig("REQUIRES_SECURE_CHANNEL"));
    ConfigAttributeDefinition insecureDef = new ConfigAttributeDefinition();
    insecureDef.addConfigAttribute(new SecurityConfig("REQUIRES_INSECURE_CHANNEL"));
    PathBasedFilterInvocationDefinitionMap defmap =
            (PathBasedFilterInvocationDefinitionMap)procfilter.getFilterInvocationDefinitionSource();
            
    // add HTTPS URL path patterns to Acegi config
    String httpsUrlsProp = WebloggerConfig.getProperty("schemeenforcement.https.urls");
    if (httpsUrlsProp != null) {
        String[] httpsUrls = StringUtils.stripAll(StringUtils.split(httpsUrlsProp, ",") );
        for (int i=0; i<httpsUrls.length; i++) {
            defmap.addSecureUrl(httpsUrls[i], secureDef);
        }
    }
    // all other action URLs are non-HTTPS
    defmap.addSecureUrl("/**<!-- need to remove this when uncommenting -->/*.do*", insecureDef);
    }
    */
}

From source file:com.openkm.servlet.PasswordResetServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String username = WebUtils.getString(request, "username");
    ServletContext sc = getServletContext();
    User usr = null;//from   w ww .  j  a  v a 2 s . com

    if (Config.USER_PASSWORD_RESET) {
        try {
            usr = AuthDAO.findUserByPk(username);
        } catch (DatabaseException e) {
            log.error(getServletName() + " User '" + username + "' not found");
        }

        if (usr != null) {
            try {
                String password = RandomStringUtils.randomAlphanumeric(8);
                AuthDAO.updateUserPassword(username, password);
                MailUtils.sendMessage(usr.getEmail(), usr.getEmail(), "Password reset", "Your new password is: "
                        + password + "<br/>"
                        + "To change it log in and then go to 'Tools' > 'Preferences' > 'User Configuration'.");
                sc.setAttribute("resetOk", usr.getEmail());
                response.sendRedirect("password_reset.jsp");
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
                sc.setAttribute("resetFailed", "Failed to send the new password by email");
                response.sendRedirect("password_reset.jsp");
            } catch (DatabaseException e) {
                log.error(e.getMessage(), e);
                sc.setAttribute("resetFailed", "Failed reset the user password");
                response.sendRedirect("password_reset.jsp");
            }
        } else {
            sc.setAttribute("resetFailed", "Invalid user name provided");
            sc.getRequestDispatcher("/password_reset.jsp").forward(request, response);
        }
    } else {
        sc.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}