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.concursive.connect.indexer.jobs.DirectoryIndexerJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    // The RAM index is lazy loaded so that application startup is not blocked.
    // The index can also be interrupted if the application needs to shutdown
    // before the index is loaded.
    SchedulerContext schedulerContext = null;
    try {/*from w  w w  .ja  v a  2  s .  c om*/
        schedulerContext = context.getScheduler().getContext();
        ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs");
        ServletContext servletContext = (ServletContext) schedulerContext.get("ServletContext");
        //@todo remove the servlet context and use the indexer
        if (servletContext != null) {
            IIndexerService indexer = IndexerFactory.getInstance().getIndexerService();
            if (indexer == null) {
                throw (new JobExecutionException("Indexer Configuration error: No indexer defined."));
            }
            // Determine the database connection to use
            Connection db = null;
            ConnectionPool commonCP = (ConnectionPool) servletContext.getAttribute(Constants.CONNECTION_POOL);
            ConnectionElement ce = new ConnectionElement();
            ce.setDriver(prefs.get(ApplicationPrefs.CONNECTION_DRIVER));
            ce.setUrl(prefs.get(ApplicationPrefs.CONNECTION_URL));
            ce.setUsername(prefs.get(ApplicationPrefs.CONNECTION_USER));
            ce.setPassword(prefs.get(ApplicationPrefs.CONNECTION_PASSWORD));
            // Setup the directory index
            indexerContext = new IndexerContext(prefs);
            indexerContext.setIndexType(Constants.INDEXER_DIRECTORY);
            try {
                db = commonCP.getConnection(ce, true);
                indexer.initializeData(indexerContext, db);
            } catch (Exception e) {
                LOG.error("Could not load RAM index", e);
            } finally {
                commonCP.free(db);
            }
            // Tell the indexer it's ok to create other writers now
            servletContext.setAttribute(Constants.DIRECTORY_INDEX_INITIALIZED, "true");
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e.getMessage());
    }
}

From source file:com.ecyrd.jspwiki.WikiEngine.java

/**
 *  Gets a WikiEngine related to the servlet. Works just like getInstance( ServletConfig )
 *
 *  @param context The ServletContext of the webapp servlet/JSP calling this method.
 *  @param props  A set of properties, or null, if we are to load JSPWiki's default
 *                jspwiki.properties (this is the usual case).
 *
 *  @return One fully functional, properly behaving WikiEngine.
 *  @throws InternalWikiException If the WikiEngine instantiation fails.
 *//*from  ww w. j  av  a2s  .  c o m*/

// FIXME: Potential make-things-easier thingy here: no need to fetch the wikiengine anymore
//        Wiki.jsp.jspInit() [really old code]; it's probably even faster to fetch it
//        using this method every time than go to pageContext.getAttribute().

public static synchronized WikiEngine getInstance(ServletContext context, Properties props)
        throws InternalWikiException {
    WikiEngine engine = (WikiEngine) context.getAttribute(ATTR_WIKIENGINE);

    if (engine == null) {
        String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type.

        context.log(" Assigning new engine to " + appid);
        try {
            if (props == null) {
                props = PropertyReader.loadWebAppProps(context);
            }

            engine = new WikiEngine(context, appid, props);
            context.setAttribute(ATTR_WIKIENGINE, engine);
        } catch (Exception e) {
            context.log("ERROR: Failed to create a Wiki engine: " + e.getMessage());
            throw new InternalWikiException("No wiki engine, check logs.");
        }

    }

    return engine;
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.common.util.ContextListener.java

/**
 * This method loads wap-provisioning file / property file, sets wap-provisioning file and
 * extracted properties as attributes in servlet context.
 *
 * @param servletContextEvent - Uses when servlet communicating with servlet container.
 *///from  w  ww .  j  av  a2s  .  co  m
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {

    ServletContext servletContext = servletContextEvent.getServletContext();

    File propertyFile = new File(
            getClass().getClassLoader().getResource(Constants.CertificateEnrolment.PROPERTIES_XML).getFile());
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("XML parsing configuration exception.");
    }
    Document document = null;
    try {
        document = docBuilder.parse(propertyFile);
    } catch (SAXException e) {
        logger.error("XML Parsing Exception.");
    } catch (IOException e) {
        logger.error("XML property file reading exception.");
    }

    String MDMPassword = document.getElementsByTagName(Constants.CertificateEnrolment.MDM_PASSWORD)
            .item(FIRST_ITEM).getTextContent();
    String MDMPrivateKeyPassword = document
            .getElementsByTagName(Constants.CertificateEnrolment.MDM_PRIVATE_KEY_PASSWORD).item(FIRST_ITEM)
            .getTextContent();
    String signedCertCommonName = document.getElementsByTagName(SIGNED_CERT_CN).item(FIRST_ITEM)
            .getTextContent();
    int signedCertNotBeforeDate = Integer
            .valueOf(document.getElementsByTagName(SIGNED_CERT_NOT_BEFORE).item(FIRST_ITEM).getTextContent());
    int signedCertNotAfterDate = Integer
            .valueOf(document.getElementsByTagName(SIGNED_CERT_NOT_AFTER).item(FIRST_ITEM).getTextContent());

    servletContext.setAttribute(Constants.CONTEXT_MDM_PASSWORD, MDMPassword);
    servletContext.setAttribute(Constants.CONTEXT_MDM_PRIVATE_KEY_PASSWORD, MDMPrivateKeyPassword);
    servletContext.setAttribute(Constants.CONTEXT_COMMON_NAME, signedCertCommonName);
    servletContext.setAttribute(Constants.CONTEXT_NOT_BEFORE_DATE, signedCertNotBeforeDate);
    servletContext.setAttribute(Constants.CONTEXT_NOT_AFTER_DATE, signedCertNotAfterDate);

    File wapProvisioningFile = new File(getClass().getClassLoader()
            .getResource(Constants.CertificateEnrolment.WAP_PROVISIONING_XML).getFile());
    servletContext.setAttribute(Constants.CONTEXT_WAP_PROVISIONING_FILE, wapProvisioningFile);
}

From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java

public ActionForward updateAlbumUrl(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.debug("in updateAlbumUrl...");

    ServletContext sCtx = request.getSession().getServletContext();

    if (!isTokenValid(request)) {
        return mapping.findForward(BaseConstants.FWD_INVALID_TOKEN);
    }//from   ww  w .  j av  a2 s . c  o  m
    ActionMessages msgs = new ActionMessages();
    SystemConfigForm rssForm = (SystemConfigForm) form;

    systemConfigService.updateAlbumUrl(rssForm.getAlbumUrl(), getLastModifiedBy(request));
    sCtx.setAttribute(BaseConstants.ALBUM_URL, rssForm.getAlbumUrl());
    msgs.add(BaseConstants.INFO_KEY, new ActionMessage("message.record.updated"));
    saveMessages(request, msgs);
    resetToken(request);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java

public ActionForward updateForumUrl(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.debug("in updateForumUrl...");

    ServletContext sCtx = request.getSession().getServletContext();

    if (!isTokenValid(request)) {
        return mapping.findForward(BaseConstants.FWD_INVALID_TOKEN);
    }/* w w  w .j a v  a2 s .  c o  m*/
    ActionMessages msgs = new ActionMessages();
    SystemConfigForm rssForm = (SystemConfigForm) form;

    systemConfigService.updateForumUrl(rssForm.getForumUrl(), getLastModifiedBy(request));
    sCtx.setAttribute(BaseConstants.FORUM_URL, rssForm.getForumUrl());
    msgs.add(BaseConstants.INFO_KEY, new ActionMessage("message.record.updated"));
    saveMessages(request, msgs);
    resetToken(request);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.common.util.ContextListener.java

/**
 * This method loads wap-provisioning file / property file, sets wap-provisioning file and
 * extracted properties as attributes in servlet context.
 *
 * @param servletContextEvent - Uses when servlet communicating with servlet container.
 *//*from  w w  w  .  ja  va 2s  .  c om*/
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {

    ServletContext servletContext = servletContextEvent.getServletContext();

    File propertyFile = new File(
            getClass().getClassLoader().getResource(Constants.CertificateEnrollment.PROPERTIES_XML).getFile());
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("XML parsing configuration exception.");
    }
    Document document = null;
    try {
        document = docBuilder.parse(propertyFile);
    } catch (SAXException e) {
        logger.error("XML Parsing Exception.");
    } catch (IOException e) {
        logger.error("XML property file reading exception.");
    }

    String MDMPassword = document.getElementsByTagName(Constants.CertificateEnrollment.MDM_PASSWORD)
            .item(FIRST_ITEM).getTextContent();
    String MDMPrivateKeyPassword = document
            .getElementsByTagName(Constants.CertificateEnrollment.MDM_PRIVATE_KEY_PASSWORD).item(FIRST_ITEM)
            .getTextContent();
    String signedCertCommonName = document.getElementsByTagName(SIGNED_CERT_CN).item(FIRST_ITEM)
            .getTextContent();
    int signedCertNotBeforeDate = Integer
            .valueOf(document.getElementsByTagName(SIGNED_CERT_NOT_BEFORE).item(FIRST_ITEM).getTextContent());
    int signedCertNotAfterDate = Integer
            .valueOf(document.getElementsByTagName(SIGNED_CERT_NOT_AFTER).item(FIRST_ITEM).getTextContent());

    servletContext.setAttribute(Constants.CONTEXT_MDM_PASSWORD, MDMPassword);
    servletContext.setAttribute(Constants.CONTEXT_MDM_PRIVATE_KEY_PASSWORD, MDMPrivateKeyPassword);
    servletContext.setAttribute(Constants.CONTEXT_COMMON_NAME, signedCertCommonName);
    servletContext.setAttribute(Constants.CONTEXT_NOT_BEFORE_DATE, signedCertNotBeforeDate);
    servletContext.setAttribute(Constants.CONTEXT_NOT_AFTER_DATE, signedCertNotAfterDate);

    File wapProvisioningFile = new File(getClass().getClassLoader()
            .getResource(Constants.CertificateEnrollment.WAP_PROVISIONING_XML).getFile());
    servletContext.setAttribute(Constants.CONTEXT_WAP_PROVISIONING_FILE, wapProvisioningFile);
}

From source file:org.openmrs.contrib.metadatarepository.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/* ww w  . j  av a2 s .  c  om*/
 */
@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>();
    }

    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("org.springframework.security.authentication.ProviderManager#0");
        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().getSimpleName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);
}

From source file:org.apache.wiki.WikiEngine.java

/**
 *  Gets a WikiEngine related to the servlet. Works just like getInstance( ServletConfig )
 *
 *  @param context The ServletContext of the webapp servlet/JSP calling this method.
 *  @param props  A set of properties, or null, if we are to load JSPWiki's default
 *                jspwiki.properties (this is the usual case).
 *
 *  @return One fully functional, properly behaving WikiEngine.
 *  @throws InternalWikiException If the WikiEngine instantiation fails.
 *//*ww  w .  j  a v  a 2s .c o  m*/

// FIXME: Potential make-things-easier thingy here: no need to fetch the wikiengine anymore
//        Wiki.jsp.jspInit() [really old code]; it's probably even faster to fetch it
//        using this method every time than go to pageContext.getAttribute().

public static synchronized WikiEngine getInstance(ServletContext context, Properties props)
        throws InternalWikiException {
    WikiEngine engine = (WikiEngine) context.getAttribute(ATTR_WIKIENGINE);

    if (engine == null) {
        String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type.

        context.log(" Assigning new engine to " + appid);
        try {
            if (props == null) {
                props = PropertyReader.loadWebAppProps(context);
            }

            engine = new WikiEngine(context, appid, props);
            context.setAttribute(ATTR_WIKIENGINE, engine);
        } catch (Exception e) {
            context.log("ERROR: Failed to create a Wiki engine: " + e.getMessage());
            log.error("ERROR: Failed to create a Wiki engine, stacktrace follows ", e);
            throw new InternalWikiException("No wiki engine, check logs.");
        }

    }

    return engine;
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

private void applyCustomerCss(ServletContext context, List<CssAttribute> cssAttributes, String customerName)
        throws Exception {
    if (!cssAttributes.isEmpty()) {
        Path tempPath = Files.createTempDirectory(customerName);
        File tempDir = tempPath.toFile();

        //copy css sortedFiles to data directory
        copyResources(context, FOLDER_CSS, tempDir);

        //copy less sortedFiles
        copyResources(context, FOLDER_LESS, tempDir);

        //replace variables in variables.less, 90_project.less, 96_loader.less
        replaceVariables(context, cssAttributes, VARIABLES_LESS, tempDir);
        replaceVariables(context, cssAttributes, PROJECT_LESS, tempDir);
        replaceVariables(context, cssAttributes, LOADER_LESS, tempDir);

        //compile less and overwrite css sortedFiles in data directory
        if (lessCompiler == null) {
            lessCompiler = new LessCompiler();
        }/*w  ww. j  av  a  2 s  . c  o m*/
        lessCompiler.compile(new File(tempDir, PROJECT_LESS), new File(tempDir, PROJECT_CSS));
        lessCompiler.compile(new File(tempDir, BOOTSTRAP_LESS), new File(tempDir, BOOTSTRAP_CSS));
        lessCompiler.compile(new File(tempDir, LOADER_LESS), new File(tempDir, LOADER_CSS));

        Path allMinCssPath = new File(tempDir, ALL_MIN_CSS).toPath();
        //concatenate all sortedFiles into all.min.css
        String css = concatenateCss(context, new File(tempDir, FOLDER_CSS).toPath(), allMinCssPath);

        //set content for css controller
        context.setAttribute(customerName, css);
    }
}

From source file:ejportal.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/*  w  ww . j a  v a2s . c  o m*/
 */
@SuppressWarnings("unchecked")
public void contextInitialized(final ServletContextEvent event) {
    StartupListener.log.debug("Initializing context...");

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

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

    final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

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

    PasswordEncoder passwordEncoder = null;
    try {
        final ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager");
        for (final Object o : provider.getProviders()) {
            final 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 (final NoSuchBeanDefinitionException n) {
        StartupListener.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 (StartupListener.log.isDebugEnabled()) {
        StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        StartupListener.log.debug("Populating drop-downs...");
    }

    StartupListener.setupContext(context);
}