Example usage for javax.servlet ServletContext log

List of usage examples for javax.servlet ServletContext log

Introduction

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

Prototype

public void log(String msg);

Source Link

Document

Writes the specified message to a servlet log file, usually an event log.

Usage

From source file:com.piusvelte.hydra.ConnectionManager.java

private ConnectionManager(ServletContext ctx) {

    ctx.log("Hydra ConnectionManager instantiated");

    String[] fullPathParts;/* ww w  . j a v  a2  s  .c om*/

    if (System.getProperty("os.name").startsWith("Windows")) {
        fullPathParts = ctx.getRealPath(File.separator).split("\\\\", -1);
        sHydraDir = fullPathParts[0] + File.separator + WIN_DIR;

    } else {
        fullPathParts = ctx.getRealPath(File.separator).split(File.separator, -1);
        sHydraDir = fullPathParts[0] + File.separator + NIX_DIR;
    }

    sHydraDir += File.separator + "hydra";
    ctx.log("Working Directory: " + sHydraDir);

    if (fullPathParts.length > 2) {
        if (fullPathParts.length > 3) {
            sHydraDir += File.separator + fullPathParts[fullPathParts.length - 3];
        }
        sHydraDir += File.separator + fullPathParts[fullPathParts.length - 2];
    }

    mQueueRetryInterval = QueueThread.DEFAULT_QUEUERETRYINTERVAL;

    File hydraDir = new File(sHydraDir);
    if (hydraDir.exists()) {
        sHydraDir += File.separator;

        InputStream is = null;

        try {
            is = new FileInputStream(sHydraDir + HYDRA_PROPERTIES);

        } catch (FileNotFoundException e1) {
            ctx.log("The properties file at " + (sHydraDir + HYDRA_PROPERTIES) + " could not be found.");
            e1.printStackTrace();
        }

        if (is != null) {
            Properties properties = new Properties();
            try {
                properties.load(is);
                ctx.log("Hydra properties file read");
                if (properties.containsKey(sPassphrase))
                    passphrase = properties.getProperty(sPassphrase);
                sQueueFile = sHydraDir + "queue";
                tokenFile = sHydraDir + "tokens";
                try {
                    loadTokens();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (properties.containsKey(sQueueRetryInterval))
                    mQueueRetryInterval = Integer.parseInt(properties.getProperty(sQueueRetryInterval));
                if (properties.containsKey(sDatabases)) {
                    String[] databaseAliases = properties.getProperty(sDatabases).split(",", -1);
                    String[] databaseProperties = new String[] { sType, sDatabase, sHost, sPort, sUsername,
                            sPassword, sConnections, sDASU, sDASP, sSQLENVINIT };
                    for (String databaseAlias : databaseAliases) {
                        HashMap<String, String> database = new HashMap<String, String>();
                        for (String databaseProperty : databaseProperties) {
                            database.put(databaseProperty,
                                    properties.getProperty(databaseAlias + "." + databaseProperty, ""));
                        }
                        synchronized (databaseLock) {
                            sDatabaseSettings.put(databaseAlias, database);
                            sDatabaseConnections.put(databaseAlias, new ArrayList<DatabaseConnection>());
                            queuedDatabaseRequests.put(databaseAlias, 0);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            initProps();
        }
    } else if (hydraDir.mkdirs()) {
        sHydraDir += File.separator;
        initProps();
    } else {
        ctx.log("properties doesn't exist, and creating it failed at: " + sHydraDir);
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

private Resource getResource(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext, String locations) {
    Resource resource = null;//  www  .  j  a va  2  s.  c  o  m
    String[] configFileLocations = locations == null ? DEFAULT_PROFILE_CONFIG_FILE_LOCATIONS
            : StringUtils.commaDelimitedListToStringArray(locations);
    for (String location : configFileLocations) {
        location = applicationContext.getEnvironment().resolvePlaceholders(location);
        servletContext.log("Testing for YAML resources at: " + location);
        resource = applicationContext.getResource(location);
        if (resource != null && resource.exists()) {
            break;
        }
    }
    return resource;
}

From source file:com.github.gagu.web.util.Log4jWebConfigurer.java

/**
 * Initialize log4j, including setting the web app root system property.
 * @param servletContext the current ServletContext
 * @see WebUtils#setWebAppRootSystemProperty
 *//*ww  w. j a  v  a2s  .c om*/
public static void initLogging(ServletContext servletContext) {
    // Expose the web app root system property.
    if (exposeWebAppRoot(servletContext)) {
        WebUtils.setWebAppRootSystemProperty(servletContext);
    }

    // Only perform custom log4j initialization in case of a config file.
    // e.g. "/WEB-INF/config/log4j.properties"
    String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    //TODO load default log4j.xml specified
    if (StringUtils.isEmpty(location)) {
        location = "com/github/gagu/web/util/framework-log4j.xml";
    }

    if (location != null) {
        // Perform actual log4j initialization; else rely on log4j's default initialization.
        try {
            // Resolve property placeholders before potentially resolving a real path.
            location = ServletContextPropertyUtils.resolvePlaceholders(location, servletContext);

            // Leave a URL (e.g. "classpath:" or "file:") as-is.
            if (!ResourceUtils.isUrl(location)) {
                // Consider a plain file path as relative to the web application root directory.
                // e.g. "/Users/hanyosh/git/gagu/gagu-example/target/gagu-example/WEB-INF/config/log4j.properties"
                location = WebUtils.getRealPath(servletContext, location);
            }

            // Write log message to server log.
            servletContext.log("Initializing log4j from [" + location + "]");

            // Check whether refresh interval was specified.
            String intervalString = servletContext.getInitParameter(REFRESH_INTERVAL_PARAM);
            if (StringUtils.hasText(intervalString)) {
                // Initialize with refresh interval, i.e. with log4j's watchdog thread,
                // checking the file in the background.
                try {
                    long refreshInterval = Long.parseLong(intervalString);
                    Log4jConfigurer.initLogging(location, refreshInterval);
                } catch (NumberFormatException ex) {
                    throw new IllegalArgumentException(
                            "Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());
                }
            } else {
                // Initialize without refresh check, i.e. without log4j's watchdog thread.
                Log4jConfigurer.initLogging(location);
            }
        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());
        }
    }
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

/**
 * Close Spring's web application context for the given servlet context. If
 * the default {@link #loadParentContext(ServletContext)} implementation,
 * which uses ContextSingletonBeanFactoryLocator, has loaded any shared
 * parent context, release one reference to that shared parent context.
 * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have
 * to override this method as well.//from www  .ja v a2  s .  c o  m
 * @param servletContext the ServletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
    servletContext.log("Closing Spring root WebApplicationContext");
    try {
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ((ConfigurableWebApplicationContext) this.context).close();
        }
    } finally {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == DhccContextLoader.class.getClassLoader()) {
            currentContext = null;
        } else if (ccl != null) {
            currentContextPerThread.remove(ccl);
        }
        servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        if (this.parentContextRef != null) {
            this.parentContextRef.release();
        }
    }
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substition with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded// ww  w  . ja  v a 2s.c o m
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
    Assert.notNull(servletContext, "ServletContext must not be null");
    String root = servletContext.getRealPath("/");
    if (root == null) {
        throw new IllegalStateException(
                "Cannot set web app root system property when WAR file is not expanded");
    }
    String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
    String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
    String oldValue = System.getProperty(key);
    if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
        throw new IllegalStateException("Web app root system property already set to different value: '" + key
                + "' = [" + oldValue + "] instead of [" + root + "] - "
                + "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
    }
    System.setProperty(key, root);
    servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}

From source file:nl.strohalm.cyclos.http.LifecycleListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *///from  w  ww .j ava 2s .  c o  m
@Override
public void contextDestroyed(final ServletContextEvent event) {
    LoggedUser.runAsSystem(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            try {
                final ServletContext context = event.getServletContext();
                final LocalSettings settings = settingsService == null ? null
                        : settingsService.getLocalSettings();

                // Shutdown the application service
                if (applicationService != null) {
                    applicationService.shutdown();
                }

                final String applicationName = settings == null ? null : settings.getApplicationName();
                context.log(applicationName == null ? "Cyclos" : applicationName + " destroyed");

                // Suggest a GC as probably there were several released resources
                System.gc();

            } catch (final Throwable e) {
                LOG.error("Error on LifecycleListener.contextDestroyed()", e);
                throw new RuntimeException(e);
            }
            return null; // required by compiler
        }
    });
}

From source file:org.springframework.boot.legacy.context.web.NonEmbeddedWebApplicationContext.java

/**
 * Prepare the {@link WebApplicationContext} with the given fully loaded
 * {@link ServletContext}. This method is usually called from
 * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
 * functionality usually provided by a {@link ContextLoaderListener}.
 * @param servletContext the operational servlet context
 *///ww  w .j  a va2 s . c om
protected void prepareWebApplicationContext(ServletContext servletContext) {
    Object rootContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (rootContext != null) {
        if (rootContext == this) {
            throw new IllegalStateException(
                    "Cannot initialize context because there is already a root application context present - "
                            + "check whether you have multiple ServletContextInitializers!");
        } else {
            return;
        }
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring embedded WebApplicationContext");
    WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory(), getServletContext());
    WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), getServletContext());
    try {
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
                    + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - getStartupDate();
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {

    Resource resource = null;//  w  w  w.ja v  a 2 s .  com
    ServletContext servletContext = applicationContext.getServletContext();
    WebApplicationContextUtils.initServletPropertySources(
            applicationContext.getEnvironment().getPropertySources(), servletContext,
            applicationContext.getServletConfig());

    ServletConfig servletConfig = applicationContext.getServletConfig();
    String locations = servletConfig == null ? null
            : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
    resource = getResource(servletContext, applicationContext, locations);

    if (resource == null) {
        servletContext.log("No YAML environment properties from servlet.  Defaulting to servlet context.");
        locations = servletContext.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
        resource = getResource(servletContext, applicationContext, locations);
    }

    try {
        servletContext.log("Loading YAML environment properties from location: " + resource);
        YamlMapFactoryBean factory = new YamlMapFactoryBean();
        factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);

        List<Resource> resources = new ArrayList<Resource>();

        String defaultLocation = servletConfig == null ? null
                : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_DEFAULT);
        if (defaultLocation != null) {
            Resource defaultResource = new ClassPathResource(defaultLocation);
            if (defaultResource.exists()) {
                resources.add(defaultResource);
            }
        }

        resources.add(resource);
        factory.setResources(resources.toArray(new Resource[resources.size()]));

        Map<String, Object> map = factory.getObject();
        String yamlStr = (new Yaml()).dump(map);
        map.put(rawYamlKey, yamlStr);
        NestedMapPropertySource properties = new NestedMapPropertySource("servletConfigYaml", map);
        applicationContext.getEnvironment().getPropertySources().addLast(properties);
        applySpringProfiles(applicationContext.getEnvironment(), servletContext);
        applyLog4jConfiguration(applicationContext.getEnvironment(), servletContext);

    } catch (Exception e) {
        servletContext.log("Error loading YAML environment properties from location: " + resource, e);
    }

}

From source file:org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.java

/**
 * Prepare the {@link WebApplicationContext} with the given fully loaded
 * {@link ServletContext}. This method is usually called from
 * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
 * functionality usually provided by a {@link ContextLoaderListener}.
 * @param servletContext the operational servlet context
 *//*from   w ww. j  av a2s .  co  m*/
protected void prepareEmbeddedWebApplicationContext(ServletContext servletContext) {
    Object rootContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (rootContext != null) {
        if (rootContext == this) {
            throw new IllegalStateException(
                    "Cannot initialize context because there is already a root application context present - "
                            + "check whether you have multiple ServletContextInitializers!");
        }
        return;
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring embedded WebApplicationContext");
    try {
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
                    + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        setServletContext(servletContext);
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - getStartupDate();
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}