Example usage for javax.servlet ServletConfig getServletContext

List of usage examples for javax.servlet ServletConfig getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletConfig getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns a reference to the ServletContext in which the caller is executing.

Usage

From source file:org.ff4j.web.embedded.ConsoleServlet.java

/**
 * Servlet initialization, init FF4J from "ff4jProvider" attribute Name.
 *
 * @param servletConfig/*from   w  ww .j  av  a 2  s  .  com*/
 *            current {@link ServletConfig} context
 * @throws ServletException
 *             error during servlet initialization
 */
public void init(ServletConfig servletConfig) throws ServletException {
    LOGGER.info("  __  __ _  _   _ ");
    LOGGER.info(" / _|/ _| || | (_)");
    LOGGER.info("| |_| |_| || |_| |");
    LOGGER.info("|  _|  _|__   _| |");
    LOGGER.info("|_| |_|    |_|_/ |");
    LOGGER.info(
            "             |__/   Embedded Console - v" + getClass().getPackage().getImplementationVersion());
    LOGGER.info(" ");

    if (ff4j == null) {
        String className = servletConfig.getInitParameter(PROVIDER_PARAM_NAME);
        try {
            Class<?> c = Class.forName(className);
            Object o = c.newInstance();
            ff4jProvider = (FF4jProvider) o;
            LOGGER.info("ff4j context has been successfully initialized - {} feature(s)",
                    ff4jProvider.getFF4j().getFeatures().size());
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Cannot load ff4jProvider as " + ff4jProvider, e);
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("Cannot instantiate  " + ff4jProvider + " as ff4jProvider", e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(
                    "No public constructor for  " + ff4jProvider + " as ff4jProvider", e);
        } catch (ClassCastException ce) {
            throw new IllegalArgumentException("ff4jProvider expected instance of " + FF4jProvider.class, ce);
        }

        // Put the FF4J in ApplicationScope (useful for tags)
        ff4j = ff4jProvider.getFF4j();
        servletConfig.getServletContext().setAttribute(FF4J_SESSIONATTRIBUTE_NAME, ff4j);
        LOGGER.debug("Servlet has been initialized and ff4j store in session with {} ",
                ff4j.getFeatures().size());
    } else {
        LOGGER.debug("Servlet has been initialized, ff4j was injected");
    }
}

From source file:weave.servlets.AdminService.java

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    configManager = SQLConfigManager.getInstance(config.getServletContext());

    tempPath = configManager.getContextParams().getTempPath();
    uploadPath = configManager.getContextParams().getUploadPath();
    docrootPath = configManager.getContextParams().getDocrootPath();
}

From source file:org.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Initial the parameters class. Web.xml is in UTF-8 format. No need to do
 * encoding convertion.//  w ww . ja v  a  2  s. c  o  m
 * 
 * @param config
 *            Servlet configuration
 */

public synchronized static void initParameters(ServletConfig config) {
    if (!isInitContext) {
        ParameterAccessor.initParameters(config.getServletContext());
    }
}

From source file:org.getobjects.servlets.WOServletAdaptor.java

@Override
public void init(final ServletConfig _cfg) throws ServletException {
    // Jetty: org.mortbay.jetty.servlet.ServletHolder$Config@114024
    super.init(_cfg);

    String an = this.valueFromServletConfig(_cfg, "WOAppName");
    String ac = this.valueFromServletConfig(_cfg, "WOAppClass");
    if (ac == null)
        ac = an;//from   ww w .j  av a  2 s .  co  m
    if (an == null && ac != null) {
        /* if only the class is set, we use the shortname of the class */
        int dotidx = ac.lastIndexOf('.');
        an = dotidx < 1 ? ac : ac.substring(dotidx + 1);
    }

    if (an == null) {
        log.warn("no WOAppName specified in servlet context: " + _cfg);
        an = WOApplication.class.getName();
    }

    /* Construct properties for the volatile "domain" from servlet init
     * parameters and context init parameters and attributes.
     * It's probably best to have a real UserDefaults concept, but for the
     * time being this is better than nothing.
     */
    final Properties properties = new Properties();
    Enumeration parameterNamesEnum = _cfg.getInitParameterNames();
    while (parameterNamesEnum.hasMoreElements()) {
        final String name = (String) parameterNamesEnum.nextElement();
        final String value = _cfg.getInitParameter(name);
        if (name != null && value != null)
            properties.put(name, value);
        else if (value == null)
            log.error("Got no value for init parameter: " + name);
    }

    /* The ServletContext may override the previous init parameters.
     * ServletContext init parameters will be overridden by attributes.
     */
    final ServletContext sctx = _cfg.getServletContext();
    if (sctx != null) {
        parameterNamesEnum = sctx.getInitParameterNames();
        while (parameterNamesEnum.hasMoreElements()) {
            final String name = (String) parameterNamesEnum.nextElement();
            properties.put(name, sctx.getInitParameter(name));
        }
        final Enumeration attributeNamesEnum = sctx.getAttributeNames();
        while (attributeNamesEnum.hasMoreElements()) {
            final String name = (String) attributeNamesEnum.nextElement();
            properties.put(name, sctx.getAttribute(name));
        }
    }

    this.initApplicationWithName(an, ac, properties);
}

From source file:com.acciente.induction.template.FreemarkerTemplatingEngine.java

public FreemarkerTemplatingEngine(Config.Templating oConfig, ClassLoader oClassLoader,
        ServletConfig oServletConfig) throws IOException, ClassNotFoundException {
    Log oLog;//from  w  w w.ja va2s .c  om

    oLog = LogFactory.getLog(FreemarkerTemplatingEngine.class);

    _oConfiguration = new Configuration();

    // set up the template loading path
    List oTemplateLoaderList = new ArrayList(oConfig.getTemplatePath().getList().size());

    for (Iterator oIter = oConfig.getTemplatePath().getList().iterator(); oIter.hasNext();) {
        Object oLoaderPathItem = oIter.next();

        if (oLoaderPathItem instanceof Config.Templating.TemplatePath.Dir) {
            Config.Templating.TemplatePath.Dir oDir = (Config.Templating.TemplatePath.Dir) oLoaderPathItem;

            if (!oDir.getDir().exists()) {
                oLog.warn("freemarker > template load path > ignoring missing directory > " + oDir.getDir());
            } else {
                oLog.info("freemarker > template load path > adding directory > " + oDir.getDir());

                oTemplateLoaderList.add(new FileTemplateLoader(oDir.getDir()));
            }
        } else if (oLoaderPathItem instanceof Config.Templating.TemplatePath.LoaderClass) {
            Config.Templating.TemplatePath.LoaderClass oLoaderClass = (Config.Templating.TemplatePath.LoaderClass) oLoaderPathItem;

            Class oClass = Class.forName(oLoaderClass.getLoaderClassName());

            oLog.info("freemarker > template load path > adding class > " + oLoaderClass.getLoaderClassName()
                    + ", prefix: " + oLoaderClass.getPath());

            oTemplateLoaderList.add(new ClassTemplateLoader(oClass, oLoaderClass.getPath()));
        } else if (oLoaderPathItem instanceof Config.Templating.TemplatePath.WebappPath) {
            Config.Templating.TemplatePath.WebappPath oWebappPath = (Config.Templating.TemplatePath.WebappPath) oLoaderPathItem;

            oLog.info("freemarker > template load path > adding webapp path > " + oWebappPath.getPath());

            oTemplateLoaderList
                    .add(new WebappTemplateLoader(oServletConfig.getServletContext(), oWebappPath.getPath()));
        } else {
            throw new IllegalArgumentException(
                    "Unexpected template path type in configuration: " + oLoaderPathItem.getClass());
        }
    }

    TemplateLoader[] oTemplateLoaderArray = new TemplateLoader[oTemplateLoaderList.size()];
    oTemplateLoaderList.toArray(oTemplateLoaderArray);
    _oConfiguration.setTemplateLoader(new MultiTemplateLoader(oTemplateLoaderArray));

    // next set the object wrapper handler
    DefaultObjectWrapper oDefaultObjectWrapper = new DefaultObjectWrapper();

    // should publics fields in views be available in the templates
    oDefaultObjectWrapper.setExposeFields(oConfig.isExposePublicFields());

    oLog.info("freemarker > expose public fields > " + oConfig.isExposePublicFields());

    _oConfiguration.setObjectWrapper(oDefaultObjectWrapper);

    if (oConfig.getLocale() != null) {
        _oConfiguration.setLocale(oConfig.getLocale());

        oLog.info("freemarker > using configured locale > " + oConfig.getLocale());
    } else {
        oLog.warn("freemarker > no locale configured, using default > " + _oConfiguration.getLocale());
    }
}

From source file:net.ontopia.topicmaps.db2tm.SynchronizationServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    log.info("Initializing synchronization servlet.");

    try {/*from ww  w.ja  v  a  2 s .c om*/
        // no default starttime
        Date time = null;
        long delay = 180 * 1000;
        String timeval = config.getInitParameter("start-time");
        if (timeval != null) {
            Date d = df.parse(timeval);
            Calendar c0 = Calendar.getInstance();
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, 1);
            c.set(Calendar.MINUTE, 0);
            c.add(Calendar.MILLISECOND, (int) d.getTime());
            if (c.before(c0))
                c.add(Calendar.HOUR_OF_DAY, 24);
            time = c.getTime();
            log.info("Setting synchronization start time to {} ms.", time);
        } else {
            // default delay is 180 sec.
            delay = getLongProperty(config, "delay", delay);
            log.info("Setting synchronization delay to {} ms.", delay);
        }

        // default interval is 24 hours.
        long interval = getLongProperty(config, "interval", 1000 * 60 * 60 * 24);
        log.info("Setting synchronization interval to {} ms.", interval);

        // load relation mapping file
        String mapping = config.getInitParameter("mapping");
        if (mapping == null)
            throw new OntopiaRuntimeException("Servlet init-param 'mapping' must be specified.");

        // get relation names (comma separated)
        Collection<String> relnames = null;
        String relations = config.getInitParameter("relations");
        if (relations != null)
            relnames = Arrays.asList(StringUtils.split(relations, ","));

        // get hold of the topic map
        String tmid = config.getInitParameter("topicmap");
        if (tmid == null)
            throw new OntopiaRuntimeException("Servlet init-param 'topicmap' must be specified.");
        TopicMapRepositoryIF rep = NavigatorUtils.getTopicMapRepository(config.getServletContext());
        TopicMapReferenceIF ref = rep.getReferenceByKey(tmid);

        // make sure delay is at least 10 seconds to make sure that it doesn't
        // start too early
        if (time == null)
            task = new SynchronizationTask(config.getServletName(), (delay < 10000 ? 10000 : delay), interval);
        else
            task = new SynchronizationTask(config.getServletName(), time, interval);

        task.setRelationMappingFile(mapping);
        task.setRelationNames(relnames);
        task.setTopicMapReference(ref);
        task.setBaseLocator(null);

    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java

/**
 * /*w  w  w.  j  a  v  a2s  .co m*/
 * {@inheritDoc}
 */
@SuppressWarnings("rawtypes")
public void afterPropertiesSet() throws Exception {

    try {
        ServletConfig servletConfig = new DelegatingServletConfig();

        // allocate thread local variables
        initThreadLocals();

        // Set the servlet config as thread local
        FlexContext.setThreadLocalObjects(null, null, null, null, null, servletConfig);

        // Get the configuration manager
        if (this.configurationManager == null) {
            this.configurationManager = new FlexConfigurationManager(this.resourceLoader,
                    this.servicesConfigPath);
        }

        // Load configuration
        MessagingConfiguration messagingConfig = this.configurationManager
                .getMessagingConfiguration(servletConfig);

        // Set up logging system ahead of everything else.
        messagingConfig.createLogAndTargets();

        // Create broker.
        this.messageBroker = messagingConfig.createBroker(this.name, this.beanClassLoader);

        // Set the servlet config as thread local
        FlexContext.setThreadLocalObjects(null, null, this.messageBroker, null, null, servletConfig);

        setupPathResolvers();

        setInitServletContext();

        if (logger.isInfoEnabled()) {
            logger.info(VersionInfo.buildMessage());
        }

        // Create endpoints, services, security, and log on the broker based
        // on configuration
        messagingConfig.configureBroker(this.messageBroker);

        long timeBeforeStartup = 0;
        if (logger.isInfoEnabled()) {
            timeBeforeStartup = System.currentTimeMillis();
            logger.info("MessageBroker with id '" + this.messageBroker.getId() + "' is starting.");
        }

        // initialize the httpSessionToFlexSessionMap
        synchronized (HttpFlexSession.mapLock) {
            if (servletConfig.getServletContext().getAttribute(HttpFlexSession.SESSION_MAP) == null) {
                servletConfig.getServletContext().setAttribute(HttpFlexSession.SESSION_MAP,
                        new ConcurrentHashMap());
            }
        }

        this.messageBroker = processBeforeStart(this.messageBroker);

        this.messageBroker.start();

        this.messageBroker = processAfterStart(this.messageBroker);

        if (logger.isInfoEnabled()) {
            long timeAfterStartup = System.currentTimeMillis();
            Long diffMillis = new Long(timeAfterStartup - timeBeforeStartup);
            logger.info("MessageBroker with id '" + this.messageBroker.getId() + "' is ready (startup time: '"
                    + diffMillis + "' ms)");
        }

        // Report replaced tokens
        this.configurationManager.reportTokens();

        // Report any unused properties.
        messagingConfig.reportUnusedProperties();

        // Setup provider for FlexSessions that wrap underlying J2EE HttpSessions.
        this.messageBroker.getFlexSessionManager().registerFlexSessionProvider(HttpFlexSession.class,
                new HttpFlexSessionProvider());

        // clear the broker and servlet config as this thread is done
        clearThreadLocals();

    } catch (Throwable error) {
        // Ensure the broker gets cleaned up properly, then re-throw
        if (logger.isErrorEnabled()) {
            logger.error("Error thrown during MessageBroker initialization", error);
        }
        destroy();
        throw new BeanInitializationException("MessageBroker initialization failed", error);
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}/*from  w  ww  .  j ava 2  s .  co m*/
 */
@Override
public void init(ServletConfig config) throws ServletException {

    this.userIdentifier = config.getInitParameter(USER_IDENTIFIER_PARAM);
    this.spDestination = config.getInitParameter(SP_DESTINATION_PARAM);
    this.spDestinationPage = config.getInitParameter(SP_DESTINATION_PAGE_PARAM);
    this.languages = config.getInitParameter(LANGUAGES_PARAM);
    this.authenticationRequestServiceLocator = new ServiceLocator<AuthenticationRequestService>(
            AUTHN_REQUEST_SERVICE_PARAM, config);

    // validate necessary configuration params
    if (null == this.userIdentifier && !this.authenticationRequestServiceLocator.isConfigured()) {
        throw new ServletException("need to provide either " + USER_IDENTIFIER_PARAM + " or "
                + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-params");
    }

    if (null == this.spDestination && null == this.spDestinationPage
            && !this.authenticationRequestServiceLocator.isConfigured()) {
        throw new ServletException("need to provide either " + SP_DESTINATION_PARAM + " or "
                + SP_DESTINATION_PAGE_PARAM + " or " + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-param");
    }

    // SSL configuration
    String trustServer = config.getInitParameter(TRUST_SERVER_PARAM);
    if (null != trustServer) {
        this.trustServer = Boolean.parseBoolean(trustServer);
    }
    X509Certificate serverCertificate = null;
    if (this.authenticationRequestServiceLocator.isConfigured()) {
        AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
        serverCertificate = service.getServerCertificate();
    }

    if (this.trustServer) {

        LOG.warn("Trusting all SSL server certificates!");
        try {
            OpenIDSSLSocketFactory.installAllTrusted();
        } catch (Exception e) {
            throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e);
        }
    } else if (null != serverCertificate) {

        LOG.info("Trusting specified SSL certificate: " + serverCertificate);
        try {
            OpenIDSSLSocketFactory.install(serverCertificate);
        } catch (Exception e) {
            throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e);
        }
    }

    ServletContext servletContext = config.getServletContext();
    this.consumerManager = (ConsumerManager) servletContext.getAttribute(CONSUMER_MANAGER_ATTRIBUTE);

    if (null == this.consumerManager) {
        try {
            if (this.trustServer || null != serverCertificate) {

                TrustManager trustManager;
                if (this.trustServer) {
                    trustManager = new OpenIDTrustManager();
                } else {
                    trustManager = new OpenIDTrustManager(serverCertificate);
                }

                SSLContext sslContext = SSLContext.getInstance("SSL");
                TrustManager[] trustManagers = { trustManager };
                sslContext.init(null, trustManagers, null);
                HttpFetcherFactory httpFetcherFactory = new HttpFetcherFactory(sslContext,
                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                YadisResolver yadisResolver = new YadisResolver(httpFetcherFactory);
                RealmVerifierFactory realmFactory = new RealmVerifierFactory(yadisResolver);
                HtmlResolver htmlResolver = new HtmlResolver(httpFetcherFactory);
                XriResolver xriResolver = Discovery.getXriResolver();
                Discovery discovery = new Discovery(htmlResolver, yadisResolver, xriResolver);
                this.consumerManager = new ConsumerManager(realmFactory, discovery, httpFetcherFactory);

            } else {
                this.consumerManager = new ConsumerManager();
            }
        } catch (Exception e) {
            throw new ServletException("could not init OpenID ConsumerManager");
        }
        servletContext.setAttribute(CONSUMER_MANAGER_ATTRIBUTE, this.consumerManager);
    }
}