Example usage for javax.servlet ServletContextEvent getServletContext

List of usage examples for javax.servlet ServletContextEvent getServletContext

Introduction

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

Prototype

public ServletContext getServletContext() 

Source Link

Document

Return the ServletContext that changed.

Usage

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    try {// w ww .  j  av a2 s .  c o  m
        ServletContext sc = servletContextEvent.getServletContext();
        ServletContextHolder.setServletContext(sc);

        initAppComponents(sc);
        initAppProperties(sc);
        afterInitAppProperties();

        beforeInitAppContext();
        initAppContext();
        afterInitAppContext();

        ApplicationContext applicationContext = AppContext.getApplicationContext();

        applicationContext.getBean(Events.class)
                .publish(new ServletContextInitializedEvent(sc, applicationContext));

        AppContext.Internals.startContext();
        log.info("AppContext started");
    } catch (RuntimeException e) {
        log.error("Error initializing application", e);
        try {
            ApplicationContext springContext = AppContext.getApplicationContext();
            if (springContext != null) {
                ((ConfigurableApplicationContext) springContext).close();
            }
        } catch (Exception e1) {
            log.debug("Error closing application context: {}", e1.toString());
        }
        throw e;
    }
}

From source file:com.wavemaker.runtime.WMAppContext.java

private WMAppContext(ServletContextEvent event) {
    this.context = event.getServletContext();
    this.appName = this.context.getServletContextName();
    if (this.appName == null) {
        this.appName = "Project Name";
    }/*  w  w w.ja v a  2  s.c  om*/

    // In Studio, the tenant field and def tenant ID is injected by ProjectManager when a project opens
    if (!this.appName.equals(DataServiceConstants.WAVEMAKER_STUDIO)) {
        // Store types.js contents in memory
        try {
            Resource typesResource = new ServletContextResource(this.context, "/types.js");
            String s = IOUtils.toString(typesResource.getInputStream());
            this.typesObj = new JSONObject(s.substring(11));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Set up multi-tenant info
        Resource appPropsResource = null;
        try {
            appPropsResource = new ServletContextResource(this.context,
                    "/WEB-INF/" + CommonConstants.APP_PROPERTY_FILE);
        } catch (WMRuntimeException re) {
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        if (!appPropsResource.exists()) {
            return;
        }

        Properties props;

        try {
            props = new Properties();
            InputStream is = appPropsResource.getInputStream();
            props.load(is);
            is.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return;
        }

        this.tenantFieldName = props.getProperty(DataServiceConstants.TENANT_FIELD_PROPERTY_NAME);
        this.tenantColumnName = props.getProperty(DataServiceConstants.TENANT_COLUMN_PROPERTY_NAME);
        this.defaultTenantID = Integer
                .parseInt(props.getProperty(DataServiceConstants.DEFAULT_TENANT_ID_PROPERTY_NAME));
    }
}

From source file:no.kantega.publishing.spring.OpenAksessContextLoaderListener.java

@Override
public void contextInitialized(final ServletContextEvent event) {

    this.event = event;

    ServletContext servletContext = event.getServletContext();

    log.info("Starting OpenAksess " + getOpenAksessVersion());

    dataDirectory = getDataDirectory(event.getServletContext());

    log.info("Using data directory " + dataDirectory.getAbsolutePath());

    configurationLoader = createConfigurationLoader(servletContext, dataDirectory);

    log.info("Loading configuration");

    properties = configurationLoader.loadConfiguration();

    initContext();/*from ww w  .  j  a  va2 s.  c o m*/

}

From source file:org.openflamingo.engine.util.VersionConfigurer.java

/**
 * Notification that the web application initialization
 * process is starting./*from w  w w . j a  va  2s  .co m*/
 * All ServletContextListeners are notified of context
 * initialization before any filter or servlet in the web
 * application is initialized.
 *
 * @param servletContextEvent {@link javax.servlet.ServletContextEvent}
 */
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext());

    Properties properties = new Properties();
    ServletContext context = servletContextEvent.getServletContext();
    InputStream inputStream = null;
    try {
        inputStream = context.getResourceAsStream("/WEB-INF/version.properties");
        properties.load(inputStream);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot load a '/WEB/INF/version.properties' file.", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    StringBuilder builder = new StringBuilder();

    printHeader(builder, "Application Information");
    Properties appProps = new Properties();
    appProps.put("Application", "Flamingo Workflow Engine");
    appProps.put("Version", properties.get("version"));
    appProps.put("Build Date", properties.get("build.timestamp"));
    appProps.put("Build Number", properties.get("build.number"));
    appProps.put("Revision Number", properties.get("revision.number"));
    appProps.put("Build Key", properties.get("build.key"));

    if (context != null) {
        appProps.put("Application Server", context.getServerInfo() + " - Servlet API "
                + context.getMajorVersion() + "." + context.getMinorVersion());
    }

    Properties systemProperties = System.getProperties();
    appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    printHeader(builder, "JVM Heap Information");

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    Properties sysProps = new Properties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
        sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> getenv = System.getenv();
    Properties envProps = new Properties();
    Set<String> strings = getenv.keySet();
    for (String key : strings) {
        String message = getenv.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    logger.info("=================================================");
    logger.info(" Flamingo Workflow Engine starting...");
    logger.info("=================================================\n{}", builder.toString());
}

From source file:org.dicen.recolnat.services.context.ColaboratoryContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {

    OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
    String homeDir = System.getenv("COLABORATORY_HOME");
    if (homeDir == null) {
        sce.getServletContext().log("ERROR. No COLABORATORY_HOME environment variable. Application will fail.");
        return;//w  w w .j ava2 s .com
    }
    sce.getServletContext().log("COLABORATORY_HOME=" + homeDir);
    sce.getServletContext().log("Looking for configuration file colaboratory-socket.yml in COLABORATORY_HOME");

    String configurationFileName = homeDir + File.separator + "colaboratory-socket.yml";
    try {
        Configuration.loadConfiguration(configurationFileName, sce.getServletContext());
    } catch (FileNotFoundException ex) {
        sce.getServletContext().log("Unable to load configuration file.");
        return;
    }

    LOG.info("Configuring databases");
    //    Orient.instance().startup();
    //    Orient.instance().removeShutdownHook();
    Configuration.configureDatabases();
    LOG.info("Configuring authentication methods");
    Configuration.configureUserAuthentication();

    // Configure periodic backup
    LOG.info("Setting up automatic backup");
    SimpleDateFormat dateParser = new SimpleDateFormat("u-HH:mm");

    Date firstBackupDate;
    try {
        firstBackupDate = dateParser.parse(Configuration.Databases.Backup.FIRST_EXECUTION);
    } catch (ParseException ex) {
        LOG.error(
                "Unable to parse first backup execution date. Expected format is 'u-HH:mm'. Databases will NOT be backed up.");
        return;
    }
    Date now;
    try {
        now = dateParser.parse(dateParser.format(new Date()));
    } catch (ParseException ex) {
        LOG.error(
                "Unable to parse current date. Perhaps a Java version (expected 8) problem? Databases will NOT be backed up.");
        return;
    }
    long delay = firstBackupDate.getTime() - now.getTime();
    if (delay < 0) {
        delay += 7 * DateUtils.MILLIS_PER_DAY;
    }

    LOG.info("Backups will begin in " + delay + " milliseconds");
    LOG.info("Backup will run every " + Configuration.Databases.Backup.FREQUENCY + " days");

    BACKUP_TIMER.scheduleAtFixedRate(new BackupTask(), delay,
            Configuration.Databases.Backup.FREQUENCY * DateUtils.MILLIS_PER_DAY);
}

From source file:org.apache.pluto.driver.PortalStartupListener.java

/**
 * Recieve notification that the context is being shut down and subsequently
 * destroy the container.//from   w  w w.j  a v  a 2  s  . co  m
 *
 * @param event the destrubtion event.
 */
public void contextDestroyed(ServletContextEvent event) {
    ServletContext servletContext = event.getServletContext();
    if (LOG.isInfoEnabled()) {
        LOG.info("Shutting down Pluto Portal Driver...");
    }
    //        destroyVWBConfiguration(servletContext);
    destroyContainer(servletContext);
    destroyAdminConfiguration(servletContext);
    destroyDriverConfiguration(servletContext);
    if (LOG.isInfoEnabled()) {
        LOG.info("********** Pluto Portal Driver Shut Down **********\n\n");
    }
}

From source file:nl.b3p.catalog.config.CatalogAppConfig.java

public void contextInitialized(ServletContextEvent sce) {

    String configParam = sce.getServletContext().getInitParameter("config");

    if (configParam == null) {
        throw new IllegalArgumentException("No config file specified in \"config\" context init parameter");
    }//  w  ww  .ja v  a 2s. c o  m

    File f = new File(configParam);
    if (!f.isAbsolute()) {
        String catalinaBase = System.getProperty("catalina.base");
        if (catalinaBase != null) {
            f = new File(catalinaBase, configParam);
        } else {
            // just use current directory whatever that may be
        }
    }
    String canonicalPath = null;
    try {
        canonicalPath = f.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = "[IOException: " + e.getMessage() + "]";
    }
    log.info("Loading configuration from file " + canonicalPath);

    if (!f.exists() || !f.canRead()) {
        throw new IllegalArgumentException(String.format(
                "Config file specified in \"config\" context init parameter with value \"%s\" (canonical path \"%s\") does not exist or cannot be read",
                configParam, canonicalPath));
    }

    try {
        config = loadFromFile(f);
        log.debug("Configuration loaded; marshalling for log");

        JAXBContext ctx = JAXBContext.newInstance(CatalogAppConfig.class);
        Marshaller m = ctx.createMarshaller();
        m.setProperty("jaxb.formatted.output", Boolean.TRUE);

        StringWriter sw = new StringWriter();
        m.marshal(config, sw);
        log.info("Parsed configuration: \n" + sw.toString());

        if (!CURRENT_VERSION.equals(config.getVersion())) {
            throw new Exception(String.format("Wrong configuration file version: %s, must be %s",
                    config.getVersion(), CURRENT_VERSION));
        }
    } catch (Exception e) {
        log.error("Error loading configuration", e);
        throw new IllegalArgumentException("Error loading configuration from file \"" + canonicalPath + '"', e);
    }

    if (log.isDebugEnabled()) {
        for (Root r : config.getRoots()) {
            log.debug(String.format("Role access list for root %s: %s", r.getName(),
                    r.getRoleAccessList().toString()));
        }
    }
}

From source file:dinistiq.web.DinistiqContextLoaderListener.java

/**
 * Web related dinistiq initialization with parameters taken from the web.xml.
 *
 * Looks up relevant packages for scanning and a custom class resolver's implementation class name. Exposes any
 * bean from the dinistiq scope to the application scope (servlet context) of the web layer including an instance
 * of dinistiq itself.//from  w  w w.  j  ava 2  s  .  c  o  m
 *
 * @param contextEvent
 */
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    // just to check what our log instance looks like
    LOG.warn("contextInitialized() log: {}", LOG.getClass().getName());
    ServletContext context = contextEvent.getServletContext();
    Set<String> packages = new HashSet<>();
    String packagNameString = context.getInitParameter(DINISTIQ_PACKAGES);
    if (StringUtils.isNotBlank(packagNameString)) {
        for (String packageName : packagNameString.split(",")) {
            packageName = packageName.trim();
            packages.add(packageName);
        } // for
    } // if
    String classResolverName = context.getInitParameter(DINISTIQ_CLASSRESOLVER);
    ClassResolver classResolver = null;
    if (StringUtils.isNotBlank(classResolverName)) {
        try {
            Class<?> forName = Class.forName(classResolverName);
            Object[] args = new Object[1];
            args[0] = packages;
            classResolver = (ClassResolver) forName.getConstructors()[0].newInstance(args);
        } catch (Exception e) {
            LOG.error("contextInitialized() cannot obtain custom class resolver", e);
        } // try/catch
    } // if
    LOG.info("contextInitialized() classResolver: {} :{}", classResolver, classResolverName);
    classResolver = (classResolver == null) ? new SimpleClassResolver(packages) : classResolver;
    try {
        Map<String, Object> externalBeans = new HashMap<>();
        externalBeans.put("servletContext", context);
        Dinistiq dinistiq = new Dinistiq(classResolver, externalBeans);
        context.setAttribute(DINISTIQ_INSTANCE, dinistiq);
        for (String name : dinistiq.getAllBeanNames()) {
            context.setAttribute(name, dinistiq.findBean(Object.class, name));
        } // for
        Collection<RegisterableServlet> servlets = dinistiq.findBeans(RegisterableServlet.class);
        List<RegisterableServlet> orderedServlets = new ArrayList<>(servlets.size());
        orderedServlets.addAll(servlets);
        Collections.sort(orderedServlets);
        LOG.debug("contextInitialized() servlets {}", orderedServlets);
        for (RegisterableServlet servlet : orderedServlets) {
            ServletRegistration registration = context.addServlet(servlet.getClass().getSimpleName(), servlet);
            for (String urlPattern : servlet.getUrlPatterns()) {
                LOG.debug("contextInitialized() * {}", urlPattern);
                registration.addMapping(urlPattern);
            } // for
        } // for
    } catch (Exception ex) {
        LOG.error("init()", ex);
    } // try/catch
}

From source file:info.magnolia.cms.servlets.PropertyInitializer.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *//*from   w  ww . j a v  a  2 s .  c om*/
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();

    String propertiesLocationString = context.getInitParameter(MAGNOLIA_INITIALIZATION_FILE);

    if (log.isDebugEnabled()) {
        log.debug("{} value in web.xml is :[{}]", MAGNOLIA_INITIALIZATION_FILE, propertiesLocationString); //$NON-NLS-1$
    }
    if (StringUtils.isEmpty(propertiesLocationString)) {
        propertiesLocationString = DEFAULT_INITIALIZATION_PARAMETER;
    }

    String[] propertiesLocation = StringUtils.split(propertiesLocationString, ',');

    String servername = null;

    try {
        servername = StringUtils.lowerCase(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        log.error(e.getMessage());
    }

    String rootPath = StringUtils.replace(context.getRealPath(StringUtils.EMPTY), "\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
    String webapp = StringUtils.substringAfterLast(rootPath, "/"); //$NON-NLS-1$

    File logs = new File(webapp + File.separator + "logs");
    File tmp = new File(webapp + File.separator + "tmp");
    if (!logs.exists()) {
        logs.mkdir();
        log.debug("Creating " + logs.getAbsoluteFile() + " folder");
    }

    if (!tmp.exists()) {
        tmp.mkdir();
        log.debug("Creating " + tmp.getAbsoluteFile() + " folder");
    }

    if (log.isDebugEnabled()) {
        log.debug("rootPath is {}, webapp is {}", rootPath, webapp); //$NON-NLS-1$ 
    }

    for (int j = 0; j < propertiesLocation.length; j++) {
        String location = StringUtils.trim(propertiesLocation[j]);
        location = StringUtils.replace(location, "${servername}", servername); //$NON-NLS-1$
        location = StringUtils.replace(location, "${webapp}", webapp); //$NON-NLS-1$

        File initFile = new File(rootPath, location);

        if (!initFile.exists() || initFile.isDirectory()) {
            if (log.isDebugEnabled()) {
                log.debug("Configuration file not found with path [{}]", //$NON-NLS-1$
                        initFile.getAbsolutePath());
            }
            continue;
        }

        InputStream fileStream;
        try {
            fileStream = new FileInputStream(initFile);
        } catch (FileNotFoundException e1) {
            log.debug("Configuration file not found with path [{}]", //$NON-NLS-1$
                    initFile.getAbsolutePath());
            return;
        }

        try {
            envProperties.load(fileStream);

            log.info("Loading configuration at {}", initFile.getAbsolutePath());//$NON-NLS-1$

            Log4jConfigurer.initLogging(context, envProperties);

            new ConfigLoader(context, envProperties);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fileStream);
        }
        return;

    }

    log.error(MessageFormat.format(
            "No configuration found using location list {0}. [servername] is [{1}], [webapp] is [{2}] and base path is [{3}]", //$NON-NLS-1$
            new Object[] { ArrayUtils.toString(propertiesLocation), servername, webapp, rootPath }));

}

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

@Override
public void contextInitialized(ServletContextEvent evt) {
    super.contextInitialized(evt);
    ServletContext ctx = evt.getServletContext();

    // First - Load Custom Error List 
    try {//  w  ww.  ja va  2s.c  om
        Class.forName("com.osbitools.ws.shared.prj.CustErrorList");
    } catch (ClassNotFoundException e) {
        // Ignore Error 
    }

    // Initialize Entity Utils
    IEntityUtils eut = getEntityUtils();
    ctx.setAttribute("entity_utils", eut);

    // Initiate LangSetFileUtils
    ctx.setAttribute("ll_set_utils", new LangSetUtils());

    // Check if git repository exists and create one
    // Using ds subdirectory as git root repository 
    File drepo = new File(
            getConfigDir(ctx) + File.separator + eut.getPrjRootDirName() + File.separator + ".git");
    Git git;
    try {

        if (!drepo.exists()) {
            if (!drepo.mkdirs())
                throw new RuntimeErrorException(
                        new Error("Unable create directory '" + drepo.getAbsolutePath() + "'"));

            try {
                git = createGitRepo(drepo);
            } catch (Exception e) {
                throw new RuntimeErrorException(new Error(
                        "Unable create new repo on path: " + drepo.getAbsolutePath() + ". " + e.getMessage()));
            }

            getLogger(ctx).info("Created new git repository '" + drepo.getAbsolutePath() + "'");
        } else if (!drepo.isDirectory()) {
            throw new RuntimeErrorException(
                    new Error(drepo.getAbsolutePath() + " is regular file and not a directory"));
        } else {
            git = Git.open(drepo);
            getLogger(ctx).debug("Open existing repository " + drepo.getAbsolutePath());
        }
    } catch (IOException e) {
        // Something unexpected and needs to be analyzed
        e.printStackTrace();

        throw new RuntimeErrorException(new Error(e));
    }

    // Save git handler
    ctx.setAttribute("git", git);

    // Check if remote destination set/changed
    StoredConfig config = git.getRepository().getConfig();
    String rname = (String) ctx.getAttribute(PrjMgrConstants.PREMOTE_GIT_NAME);
    String rurl = (String) ctx.getAttribute("git_remote_url");

    if (!Utils.isEmpty(rname) && !Utils.isEmpty(rurl)) {
        String url = config.getString("remote", rname, "url");
        if (!rurl.equals(url)) {
            config.setString("remote", rname, "url", rurl);
            try {
                config.save();
            } catch (IOException e) {
                getLogger(ctx).error("Error saving git remote url. " + e.getMessage());
            }
        }
    }

    // Temp directory for files upload
    String tname = System.getProperty("java.io.tmpdir");
    getLogger(ctx).info("Using temporarily directory '" + tname + "' for file uploads");
    File tdir = new File(tname);

    if (!tdir.exists())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not found"));
    if (!tdir.isDirectory())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not a directory"));

    DiskFileItemFactory dfi = new DiskFileItemFactory();
    dfi.setSizeThreshold(
            ((Integer) ctx.getAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)) * 1024 * 1024);
    dfi.setRepository(tdir);
    evt.getServletContext().setAttribute("dfi", dfi);

    // Save entity utils in context
    evt.getServletContext().setAttribute("entity_utils", getEntityUtils());
}