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.infoglue.deliver.applications.actions.ExtranetLoginAction.java

private void handleCookies() throws Exception {
    DesEncryptionHelper encHelper = new DesEncryptionHelper();
    String userName = this.getRequest().getParameter("j_username");
    String encryptedName = encHelper.encrypt(userName);
    String password = this.getRequest().getParameter("j_password");
    String encryptedPassword = encHelper.encrypt(password);

    String encryptedNameAsBase64 = Base64.encodeBase64URLSafeString(encryptedName.getBytes("utf-8"));
    String encryptedPasswordAsBase64 = Base64.encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8"));

    //logger.info("encryptedName:" + encryptedName);
    //logger.info("encryptedPassword:" + encryptedPassword);

    try {/*from ww w . j a v a2s.  c o  m*/
        String cmsBaseUrl = CmsPropertyHandler.getCmsFullBaseUrl();
        //logger.info("cmsBaseUrl:" + cmsBaseUrl);
        String[] parts = cmsBaseUrl.split("/");

        cmsBaseUrl = "/" + parts[parts.length - 1];
        //logger.info("used cmsBaseUrl:" + cmsBaseUrl);

        ServletContext servletContext = ActionContext.getServletContext().getContext(cmsBaseUrl);
        //logger.info("servletContext:" + servletContext.getServletContextName() + ":" + servletContext.getServletNames());

        if (servletContext == null) {
            logger.error("Could not autologin to CMS. Set cross context = true in Tomcat config.");
        } else {
            servletContext.setAttribute(encryptedName, userName);
        }

        //logger.info(encryptedName + "=" + userName);
        //logger.info("After attribute:" + servletContext.getAttribute(encryptedName));
    } catch (Exception e) {
        logger.error("Error: " + e.getMessage(), e);
    }

    int cmsCookieTimeout = 1800; //30 minutes default
    String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout();
    if (cmsCookieTimeoutString != null) {
        try {
            cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim());
        } catch (Exception e) {
        }
    }

    try {
        //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ"));
        Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64);
        cookie_iguserid.setPath("/");
        cookie_iguserid.setMaxAge(cmsCookieTimeout);
        this.getResponse().addCookie(cookie_iguserid);

        //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ"));
        Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64);
        cookie_igpassword.setPath("/");
        cookie_igpassword.setMaxAge(cmsCookieTimeout);
        this.getResponse().addCookie(cookie_igpassword);
    } catch (Exception e) {
        logger.error("Could not set cookies:" + e.getMessage(), e);
    }
    //END CMS COOKIE

    if (storeUserInfoCookie == null || !storeUserInfoCookie.equalsIgnoreCase("true"))
        return;

    boolean enableExtranetCookies = getEnableExtranetCookies();
    int extranetCookieTimeout = 43200; //30 days default
    String extranetCookieTimeoutString = CmsPropertyHandler.getExtranetCookieTimeout();
    if (extranetCookieTimeoutString != null) {
        try {
            extranetCookieTimeout = Integer.parseInt(extranetCookieTimeoutString.trim());
        } catch (Exception e) {
        }
    }

    if (enableExtranetCookies) {
        //Cookie cookie_userid = new Cookie("igextranetuserid", encryptedName);
        Cookie cookie_userid = new Cookie("igextranetuserid", encryptedNameAsBase64);
        cookie_userid.setMaxAge(30 * 24 * 60 * 60); //30 days
        this.getResponse().addCookie(cookie_userid);

        //Cookie cookie_password = new Cookie ("igextranetpassword", encryptedPassword);
        Cookie cookie_password = new Cookie("igextranetpassword", encryptedPasswordAsBase64);
        cookie_password.setMaxAge(30 * 24 * 60 * 60); //30 days
        this.getResponse().addCookie(cookie_password);
    }
}

From source file:org.sakaiproject.tool.gradebook.ui.EntryServlet.java

private void handleMyFacesSecret(ServletContext servletContext) {
    String secret = servletContext.getInitParameter(INIT_SECRET);
    if (secret == null) { // this means that org.apache.myfaces.secret context param was removed from gradebook web.xml
        if (logger.isWarnEnabled())
            logger.warn(//from   w  w  w. ja  v  a  2 s .  com
                    "MyFaces ViewState encryption has been disabled.  See the MyFaces Wiki for encryption options.");
    } else if (secret.equalsIgnoreCase(GENERATE_RANDOM_SECRET)) {
        int length = 8;
        byte[] bytes = new byte[length];
        new Random().nextBytes(bytes);
        SecretKey secretKey = new SecretKeySpec(bytes, DEFAULT_ALGORITHM);
        servletContext.setAttribute("org.apache.myfaces.secret.CACHE", secretKey);
        if (logger.isDebugEnabled())
            logger.debug("generated random MyFaces secret");
    } // else if this is not true, then org.apache.myfaces.secret context param was customized in web.xml, so let MyFaces StateUtils handle secret
}

From source file:edu.isi.wings.portal.controllers.RunController.java

public void runExecutionPlan(RuntimePlan rplan, ServletContext context) {
    PlanExecutionEngine engine = config.getDomainExecutionEngine();
    // "execute" below is an asynchronous call
    engine.execute(rplan);//from w w  w.  j a v a  2 s . co  m

    // Save the engine for an abort if needed
    context.setAttribute("plan_" + rplan.getID(), rplan);
    context.setAttribute("engine_" + rplan.getID(), engine);
}

From source file:org.openspaces.pu.container.jee.context.BootstrapWebApplicationContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    Boolean bootstraped = (Boolean) servletContext.getAttribute(BOOTSTRAP_CONTEXT_KEY);
    if (bootstraped != null && bootstraped) {
        logger.debug("Already performed bootstrap, ignoring");
        return;//from  w  w  w. j  a  v a  2  s  . c om
    }
    servletContext.setAttribute(BOOTSTRAP_CONTEXT_KEY, true);

    logger.info("Booting OpenSpaces Web Application Support");
    logger.info(ClassLoaderUtils.getCurrentClassPathString("Web Class Loader"));
    final ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig();

    InputStream is = servletContext.getResourceAsStream(MARSHALLED_CLUSTER_INFO);
    if (is != null) {
        try {
            config.setClusterInfo((ClusterInfo) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT,
                    config.getClusterInfo());
        } catch (Exception e) {
            logger.warn("Failed to read cluster info from " + MARSHALLED_CLUSTER_INFO, e);
        }
    } else {
        logger.debug("No cluster info found at " + MARSHALLED_CLUSTER_INFO);
    }
    is = servletContext.getResourceAsStream(MARSHALLED_BEAN_LEVEL_PROPERTIES);
    if (is != null) {
        try {
            config.setBeanLevelProperties(
                    (BeanLevelProperties) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT,
                    config.getBeanLevelProperties());
        } catch (Exception e) {
            logger.warn("Failed to read bean level properties from " + MARSHALLED_BEAN_LEVEL_PROPERTIES, e);
        }
    } else {
        logger.debug("No bean level properties found at " + MARSHALLED_BEAN_LEVEL_PROPERTIES);
    }

    Resource resource = null;
    String realPath = servletContext.getRealPath("/META-INF/spring/pu.xml");
    if (realPath != null) {
        resource = new FileSystemResource(realPath);
    }
    if (resource != null && resource.exists()) {
        logger.debug("Loading [" + resource + "]");
        // create the Spring application context
        final ResourceApplicationContext applicationContext = new ResourceApplicationContext(
                new Resource[] { resource }, null, config);
        // "start" the application context
        applicationContext.refresh();

        servletContext.setAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT,
                applicationContext);
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            if (applicationContext.getType(beanName) != null)
                servletContext.setAttribute(beanName, applicationContext.getBean(beanName));
        }

        if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
            final String key = config.getClusterInfo().getUniqueName();

            SharedServiceData.addServiceDetails(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceDetails> serviceDetails = new ArrayList<ServiceDetails>();
                    Map map = applicationContext.getBeansOfType(ServiceDetailsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceDetails[] details = ((ServiceDetailsProvider) it.next()).getServicesDetails();
                        if (details != null) {
                            for (ServiceDetails detail : details) {
                                serviceDetails.add(detail);
                            }
                        }
                    }
                    return serviceDetails.toArray(new Object[serviceDetails.size()]);
                }
            });

            SharedServiceData.addServiceMonitors(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceMonitors> serviceMonitors = new ArrayList<ServiceMonitors>();
                    Map map = applicationContext.getBeansOfType(ServiceMonitorsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceMonitors[] monitors = ((ServiceMonitorsProvider) it.next())
                                .getServicesMonitors();
                        if (monitors != null) {
                            for (ServiceMonitors monitor : monitors) {
                                serviceMonitors.add(monitor);
                            }
                        }
                    }
                    return serviceMonitors.toArray(new Object[serviceMonitors.size()]);
                }
            });

            Map map = applicationContext.getBeansOfType(MemberAliveIndicator.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final MemberAliveIndicator memberAliveIndicator = (MemberAliveIndicator) it.next();
                if (memberAliveIndicator.isMemberAliveEnabled()) {
                    SharedServiceData.addMemberAliveIndicator(key, new Callable<Boolean>() {
                        public Boolean call() throws Exception {
                            return memberAliveIndicator.isAlive();
                        }
                    });
                }
            }

            map = applicationContext.getBeansOfType(ProcessingUnitUndeployingListener.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final ProcessingUnitUndeployingListener listener = (ProcessingUnitUndeployingListener) it
                        .next();
                SharedServiceData.addUndeployingEventListener(key, new Callable() {
                    public Object call() throws Exception {
                        listener.processingUnitUndeploying();
                        return null;
                    }
                });
            }

            map = applicationContext.getBeansOfType(InternalDumpProcessor.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                SharedServiceData.addDumpProcessors(key, it.next());
            }
        }
    } else {
        logger.debug("No [" + ApplicationContextProcessingUnitContainerProvider.DEFAULT_PU_CONTEXT_LOCATION
                + "] to load");
    }

    // load jee specific context listener
    if (config.getBeanLevelProperties() != null) {
        String jeeContainer = JeeProcessingUnitContainerProvider
                .getJeeContainer(config.getBeanLevelProperties());
        String className = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + StringUtils.capitalize(jeeContainer) + "WebApplicationContextListener";
        Class clazz = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            // no class, ignore
        }
        if (clazz != null) {
            try {
                jeeContainerContextListener = (ServletContextListener) clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Failed to create JEE specific context listener [" + clazz.getName() + "]", e);
            }
            jeeContainerContextListener.contextInitialized(servletContextEvent);
        }
    }

    // set the class loader used so the service bean can use it
    if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
        SharedServiceData.putWebAppClassLoader(config.getClusterInfo().getUniqueName(),
                Thread.currentThread().getContextClassLoader());
    }
}

From source file:org.tonguetied.web.servlet.ServletContextInitializer.java

/**
 * Create the list of supported languages used by the web front end and add
 * as a application scope variable./*  w ww.j  ava  2 s.  c o  m*/
 * 
 * @param context the {@linkplain ServletContext} to add the list of 
 * languages
 */
private void loadSupportedLanguages(ServletContext context) {
    // read language.properties
    if (logger.isInfoEnabled())
        logger.info("loading resources from file: " + LANGUAGE_PROPERTIES);
    final ResourceBundle bundle = ResourceBundle.getBundle(LANGUAGE_PROPERTIES);
    Set<String> languageKeys = new TreeSet<String>(Collections.list(bundle.getKeys()));
    if (languageKeys.isEmpty()) {
        logger.warn("Resource file " + LANGUAGE_PROPERTIES + ".properties contains no entries");
        languageKeys.add(Locale.ENGLISH.getLanguage());
    }

    context.setAttribute(KEY_SUPPORTED_LANGUAGES, languageKeys);
}

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

@Override
public UserFormDetails getNewFormDetails(RapidRequest rapidRequest) {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // the master form id as a string
    String nextFormIdString = (String) servletContext.getAttribute(NEXT_FORM_ID);
    // if null set to "0"
    if (nextFormIdString == null)
        nextFormIdString = "0";
    // add 1 to the master form id
    String formId = Integer.toString(Integer.parseInt(nextFormIdString) + 1);
    // retain it in the context
    servletContext.setAttribute(NEXT_FORM_ID, formId);
    // return it//from   w w w  .  j a v a  2s .  c o  m
    return new UserFormDetails(formId, null);
}

From source file:com.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java

@Override
public void processConfig(ServletContext ctx, Properties props, HashMap<String, String> rmap, boolean isNew) {
    super.processConfig(ctx, props, rmap, isNew);

    if (isNew) {//from w w  w.  ja va  2 s  .c  o m
        props.put(PrjMgrConstants.PREMOTE_GIT_NAME, PrjMgrConstants.DEFAULT_REMOTE_NAME);

        // Restricted value
        props.put(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME,
                rmap.get(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME) != null
                        ? rmap.get(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)
                        : PrjMgrConstants.DEFAULT_MAX_FILE_UPLOAD_SIZE);
    }

    ctx.setAttribute(PrjMgrConstants.PREMOTE_GIT_NAME,
            props.getProperty(PrjMgrConstants.PREMOTE_GIT_NAME, PrjMgrConstants.DEFAULT_REMOTE_NAME));
    ctx.setAttribute("git_remote_url", props.getProperty("git_remote_url", null));

    ctx.setAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME,
            rmap.get(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME) != null
                    ? rmap.get(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)
                    : Integer.parseInt(props.getProperty(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME,
                            PrjMgrConstants.DEFAULT_MAX_FILE_UPLOAD_SIZE)));

    // Read system component list
    String clist = getComponentList();
    if (clist != null)
        // Escape all double quotes so comp_list can be evaluated separate
        addSysParam(ctx, "comp_list", clist.replace("\"", "\\\""));
}

From source file:com.ikon.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;/* w  w  w  .  ja  va  2  s.c  o m*/

    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);
    }
}

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

protected Map<String, Boolean> getUserFormCompleteValues(RapidRequest rapidRequest) {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // get the map of completed values
    Map<String, Boolean> userFormCompleteValues = (Map<String, Boolean>) servletContext
            .getAttribute(USER_FORM_COMPLETE_VALUES);
    // if there aren't any yet
    if (userFormCompleteValues == null) {
        // make some
        userFormCompleteValues = new HashMap<String, Boolean>();
        // store them
        servletContext.setAttribute(USER_FORM_COMPLETE_VALUES, userFormCompleteValues);
    }/*  w w  w  .j  a  v  a 2s .c o  m*/
    // return
    return userFormCompleteValues;
}

From source file:com.concursive.connect.web.listeners.ContextListener.java

/**
 * Code initialization for global objects like ConnectionPools
 *
 * @param event Description of the Parameter
 *///from   w w w.ja  va  2s  . co m
public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    LOG.info("Initializing");
    LOG.info("Version: " + ApplicationVersion.VERSION);
    // Start the connection pool
    try {
        ConnectionPool cp = new ConnectionPool();
        cp.setDebug(true);
        cp.setTestConnections(false);
        cp.setAllowShrinking(true);
        cp.setMaxConnections(10);
        cp.setMaxIdleTime(60000);
        cp.setMaxDeadTime(300000);
        context.setAttribute(Constants.CONNECTION_POOL, cp);
        LOG.info("Connection pool added");
    } catch (Exception e) {
        LOG.error("Connection pool error", e);
    }

    // Start the cache manager (caches are configured later)
    CacheManager.create();
    LOG.info("CacheManager created");
    // Start the work flow manager
    try {
        // Workflow manager
        WorkflowManager wfManager = new WorkflowManager();
        context.setAttribute(Constants.WORKFLOW_MANAGER, wfManager);
        // Hook manager
        ObjectHookManager hookManager = new ObjectHookManager();
        hookManager.setWorkflowManager(wfManager);
        context.setAttribute(Constants.OBJECT_HOOK_MANAGER, hookManager);
        LOG.info("Workflow manager added");
    } catch (Exception e) {
        LOG.error("Workflow manager error", e);
    }

    // Setup a web tracker
    Tracker tracker = new Tracker();
    context.setAttribute(Constants.USER_SESSION_TRACKER, tracker);

    // Setup Webdav Manager
    WebdavManager webdavManager = new WebdavManager();
    context.setAttribute(Constants.WEBDAV_MANAGER, webdavManager);
    LOG.info("Webdav manager added");

    // Setup scheduler
    try {
        SchedulerFactory schedulerFactory = new org.quartz.impl.StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        context.setAttribute(Constants.SCHEDULER, scheduler);
        LOG.info("Scheduler added");
    } catch (Exception e) {
        LOG.error("Scheduler error", e);
    }

    // Portlet container
    try {
        // Add the Container
        PortletContainerFactory portletFactory = PortletContainerFactory.getInstance();
        ContainerServicesImpl services = new ContainerServicesImpl();
        PortletContainer portletContainer = portletFactory.createContainer("PortletContainer", services,
                services);
        portletContainer.init(context);
        context.setAttribute(Constants.PORTLET_CONTAINER, portletContainer);
        LOG.info("PortletContainer added");
    } catch (Exception e) {
        LOG.error("PortletContainer error", e);
    }

    // Finished
    LOG.info("Initialized");
}