Example usage for javax.servlet ServletContext getClass

List of usage examples for javax.servlet ServletContext getClass

Introduction

In this page you can find the example usage for javax.servlet ServletContext getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.psikeds.common.config.ServletContextProxy.java

private static Object createProxy(final ServletContext ctx) {
    // Get runtime class of CTX which is something that implements
    // ServletContext
    final Class<? extends ServletContext> clazz = ctx.getClass();
    // Get the Classloader for that runtime class
    final ClassLoader loader = getClassloader(clazz);
    // Create a new Proxy for that Class using our ServletContextProxy
    return Proxy.newProxyInstance(loader, clazz.getInterfaces(), new ServletContextProxy(ctx));
}

From source file:arena.utils.ServletUtils.java

/**
 * Do a reflective call to the getContextPath method on the context object, since we don't want
 * to require the 2.5 servlet API, but we want to call it if it's available.
 *//* w  w  w.  ja  va 2 s  .c o m*/
public static String getContextPath(ServletContext context) {
    String contextPath = null;
    try {
        Method methContextPath = context.getClass().getMethod("getContextPath", new Class[0]);
        if (methContextPath.getReturnType().equals(String.class)) {
            contextPath = (String) methContextPath.invoke(context, new Object[0]);
        }
    } catch (Throwable err) {
    }
    return contextPath;
}

From source file:com.alfaariss.oa.OAContextListener.java

/**
 * Starts the engine before all servlets are initialized.
 * /*from  w w w  .  ja va2  s . co m*/
 * Searches for the properties needed for the configuration in:
 * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code>
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent oServletContextEvent) {
    Properties pConfig = new Properties();
    try {
        _logger.info("Starting Asimba");

        Package pCurrent = OAContextListener.class.getPackage();

        String sSpecVersion = pCurrent.getSpecificationVersion();
        if (sSpecVersion != null)
            _logger.info("Specification-Version: " + sSpecVersion);

        String sImplVersion = pCurrent.getImplementationVersion();
        if (sImplVersion != null)
            _logger.info("Implementation-Version: " + sImplVersion);

        ServletContext oServletContext = oServletContextEvent.getServletContext();

        Enumeration enumContextAttribs = oServletContext.getInitParameterNames();
        while (enumContextAttribs.hasMoreElements()) {
            String sName = (String) enumContextAttribs.nextElement();
            pConfig.put(sName, oServletContext.getInitParameter(sName));
        }

        if (pConfig.size() > 0) {
            _logger.info("Using configuration items found in servlet context: " + pConfig);
        }

        // Add MountingPoint to PathTranslator
        PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath(""));

        // Try to see whether there is a system property with the location of the properties file:
        String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY);
        if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) {
            File fConfig = new File(sPropertiesFilename);
            if (fConfig.exists()) {
                _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath());
                pConfig.putAll(getProperties(fConfig));
            }
        }

        String sWebInf = oServletContext.getRealPath("WEB-INF");
        if (sWebInf != null) {
            _logger.info("Cannot find path in ServletContext for WEB-INF");
            StringBuffer sbConfigFile = new StringBuffer(sWebInf);
            if (!sbConfigFile.toString().endsWith(File.separator))
                sbConfigFile.append(File.separator);
            sbConfigFile.append(PROPERTIES_FILENAME);

            File fConfig = new File(sbConfigFile.toString());
            if (fConfig.exists()) {
                _logger.info("Updating configuration items with the items in file: " + fConfig.toString());
                pConfig.putAll(getProperties(fConfig));
            } else {
                _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME
                        + ") file found at: " + fConfig.toString());
            }
        }
        //Search for PROPERTIES_FILENAME file in servlet context classloader classpath 
        //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME]
        //if previous location didn't contain PROPERTIES_FILENAME then checking: 
        //./tomcat/common/classes/PROPERTIES_FILENAME
        URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME);
        if (urlProperties != null) {
            String sProperties = urlProperties.getFile();
            _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties);
            File fProperties = new File(sProperties);
            if (fProperties != null && fProperties.exists()) {
                _logger.info("Updating configuration items with the items in file: "
                        + fProperties.getAbsolutePath());
                pConfig.putAll(getProperties(fProperties));
            } else
                _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
        } else
            _logger.info("No optional '" + PROPERTIES_FILENAME
                    + "' configuration file found in servlet context classpath");

        if (!pConfig.containsKey("configuration.handler.filename")) {
            StringBuffer sbOAConfigFile = new StringBuffer(sWebInf);
            if (!sbOAConfigFile.toString().endsWith(File.separator))
                sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("conf");
            sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("asimba.xml");
            File fOAConfig = new File(sbOAConfigFile.toString());
            if (fOAConfig.exists()) {
                pConfig.put("configuration.handler.filename", sbOAConfigFile.toString());
                _logger.info(
                        "Setting 'configuration.handler.filename' configuration property with configuration file found at: "
                                + fOAConfig.toString());
            }
        }

        _oEngineLauncher.start(pConfig);

        _logger.info("Started Engine with OAContextListener");
    } catch (Exception e) {
        _logger.error("Can't start Engine with OAContextListener", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();
    }

}

From source file:org.apache.tiles.servlet.context.ServletUtil.java

/**
 * Configures the container to be used in the application.
 *
 * @param context The servlet context object to use.
 * @param container The container object to set.
 * @param key The key under which the container will be stored.
 * @since 2.1.2/*from   ww w .  j  a va  2s. c om*/
 */
public static void setContainer(ServletContext context, TilesContainer container, String key) {
    Log log = LogFactory.getLog(ServletUtil.class);
    if (key == null) {
        key = TilesAccess.CONTAINER_ATTRIBUTE;
    }

    if (container == null) {
        if (log.isInfoEnabled()) {
            log.info("Removing TilesContext for context: " + context.getClass().getName());
        }
        context.removeAttribute(key);
    }
    if (container != null && log.isInfoEnabled()) {
        log.info("Publishing TilesContext for context: " + context.getClass().getName());
    }
    context.setAttribute(key, container);
}

From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java

/**
 * Disable sessionId in URL (Servlet 3.0 containers) by setting the session tracking mode to SessionTrackingMode.COOKIE
 * For Servlet container < 3.0 we use different method (for tomcat 6 we use custom context.xml and for jetty
 * there is a custom jetty.xml file)./*  ww  w  .  ja  v a2 s .  c o  m*/
 */
@SuppressWarnings("unchecked")
private void setSessionTrackingMode(ServletContext servletContext) {
    // Only for Servlet container version 3.0 and above
    if (servletContext.getMajorVersion() < 3) {
        return;
    }

    // We cannot use ConstantValue.enableURLSessionId.getBoolean() since ArtifactoryHome is not binded yet.
    ArtifactoryHome artifactoryHome = (ArtifactoryHome) servletContext
            .getAttribute(ArtifactoryHome.SERVLET_CTX_ATTR);
    if (artifactoryHome == null) {
        throw new IllegalStateException("Artifactory home not initialized.");
    }

    if (artifactoryHome.getArtifactoryProperties()
            .getBooleanProperty(ConstantValues.supportUrlSessionTracking)) {
        getLogger().debug("Skipping setting session tracking mode to COOKIE, enableURLSessionId flag it on.");
        return;
    }

    try {
        // load enum with reflection
        ClassLoader cl = ClassUtils.getDefaultClassLoader();
        Class<Enum> trackingModeEnum = (Class<Enum>) cl.loadClass("javax.servlet.SessionTrackingMode");
        Enum cookieTrackingMode = Enum.valueOf(trackingModeEnum, "COOKIE");

        // reflective call servletContext.setSessionTrackingModes(trackingModes)
        Method method = servletContext.getClass().getMethod("setSessionTrackingModes", Set.class);
        method.setAccessible(true);
        ReflectionUtils.invokeMethod(method, servletContext, Sets.newHashSet(cookieTrackingMode));
        getLogger().debug("Successfully set session tracking mode to COOKIE");
    } catch (Exception e) {
        getLogger().warn("Failed to set session tracking mode: " + e.getMessage());
    }
}

From source file:org.nuxeo.runtime.deployment.NuxeoStarter.java

protected void findEnv(ServletContext servletContext) {
    for (String param : Arrays.asList( //
            NUXEO_RUNTIME_HOME, //
            NUXEO_CONFIG_DIR, //
            NUXEO_DATA_DIR, //
            NUXEO_LOG_DIR, //
            NUXEO_TMP_DIR, //
            NUXEO_WEB_DIR)) {/*w  w  w .  ja  v  a2 s.  com*/
        String value = servletContext.getInitParameter(param);
        if (value != null && !"".equals(value.trim())) {
            env.put(param, value);
        }
    }
    // default env values
    if (!env.containsKey(NUXEO_CONFIG_DIR)) {
        String webinf = servletContext.getRealPath("/WEB-INF");
        env.put(NUXEO_CONFIG_DIR, webinf);
    }
    if (!env.containsKey(NUXEO_RUNTIME_HOME)) {
        File home = new File(DEFAULT_HOME);
        env.put(NUXEO_RUNTIME_HOME, home.getAbsolutePath());
    }
    // host
    if (getClass().getClassLoader().getClass().getName().startsWith("org.jboss.classloader")) {
        env.put(FrameworkLoader.HOST_NAME, JBOSS_HOST);
    } else if (servletContext.getClass().getName().startsWith("org.apache.catalina")) {
        env.put(FrameworkLoader.HOST_NAME, TOMCAT_HOST);
    }
}