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.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    final ServletContext servletContext = servletContextEvent.getServletContext();
    stopThreads = !"false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
    stopTimerThreads = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
    executeShutdownHooks = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
    threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs",
            THREAD_WAIT_MS_DEFAULT);/*from w  w w  . j a v  a  2 s .c om*/
    shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs",
            SHUTDOWN_HOOK_WAIT_MS_DEFAULT);

    info("Settings for " + this.getClass().getName() + " (CL: 0x"
            + Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
    info("  stopThreads = " + stopThreads);
    info("  stopTimerThreads = " + stopTimerThreads);
    info("  executeShutdownHooks = " + executeShutdownHooks);
    info("  threadWaitMs = " + threadWaitMs + " ms");
    info("  shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");

    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        // If package org.jboss is found, we may be running under JBoss
        mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
    } catch (Exception ex) {
        // Do nothing
    }

    info("Initializing context by loading some known offenders with system classloader");

    // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener  
    // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
    try {
        // Switch to system classloader in before we load/call some JRE stuff that will cause 
        // the current classloader to be available for garbage collection
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread

        java.security.Security.getProviders();

        java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader

        javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()

        try {
            Class.forName("javax.security.auth.Policy").getMethod("getPolicy").invoke(null);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (ClassNotFoundException e) {
            // Ignore silently - class is deprecated
        }

        try {
            javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception ex) { // Example: ParserConfigurationException
            error(ex);
        }

        try {
            Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        try {
            Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        // This probably does not affect classloaders, but prevents some problems with .jar files
        try {
            // URL needs to be well-formed, but does not need to exist
            new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
        } catch (Exception ex) {
            error(ex);
        }

        /////////////////////////////////////////////////////
        // Load Sun specific classes that may cause leaks

        final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");

        try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        }

        try {
            Class.forName("sun.java2d.Disposer"); // Will start a Thread
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE && !mayBeJBoss) // JBoss blocks this package/class, so don't warn
                error(cnfex);
        }

        try {
            Class<?> gcClass = Class.forName("sun.misc.GC");
            final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
            requestLatency.invoke(null, 3600000L);
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        }

        // Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader  
        try {
            Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
        } catch (ClassNotFoundException e) {
            // Ignore silently - class not present
        }
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {

    _logger.info("Shutting down...");

    // interrupt the page monitor if we have one
    if (_monitor != null)
        _monitor.interrupt();//from  w w w  .  j  av a2  s . c o m

    // get the servletContext
    ServletContext servletContext = event.getServletContext();

    // get all of the applications
    Applications applications = (Applications) servletContext.getAttribute("applications");
    // if we got some
    if (applications != null) {
        // loop the application ids
        for (String id : applications.getIds()) {
            // get the application
            Versions versions = applications.getVersions(id);
            // loop the versions of each app
            for (String version : versions.keySet()) {
                // get the application
                Application application = applications.get(id, version);
                // have it close any sensitive resources 
                application.close(servletContext);
            }
        }
    }

    // sleep for 2 seconds to allow any database connection cleanup to complete
    try {
        Thread.sleep(2000);
    } catch (Exception ex) {
    }

    // This manually deregisters JDBC drivers, which prevents Tomcat from complaining about memory leaks from this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            _logger.info(String.format("Deregistering jdbc driver: %s", driver));
        } catch (SQLException e) {
            _logger.error(String.format("Error deregistering driver %s", driver), e);
        }
    }

    // Thanks to http://stackoverflow.com/questions/11872316/tomcat-guice-jdbc-memory-leak
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Abandoned connection cleanup thread")) {
            synchronized (t) {
                try {
                    _logger.info("Forcing stop of Abandoned connection cleanup thread");
                    t.stop(); //don't complain, it works
                } catch (Exception ex) {
                    _logger.info("Error forcing stop of Abandoned connection cleanup thread", ex);
                }
            }
        }
    }

    // sleep for 1 second to allow any database connection cleanup to complete
    try {
        Thread.sleep(1000);
    } catch (Exception ex) {
    }

    // last log
    _logger.info("Logger shutdown");
    // shutdown logger
    if (_logger != null)
        LogManager.shutdown();

}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

public void contextInitialized(ServletContextEvent servletContextEvent) {

    final ServletContext servletContext = servletContextEvent.getServletContext();
    stopThreads = !"false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
    stopTimerThreads = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
    executeShutdownHooks = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
    threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs",
            THREAD_WAIT_MS_DEFAULT);// ww  w .  j a  v  a 2s.  co  m
    shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs",
            SHUTDOWN_HOOK_WAIT_MS_DEFAULT);

    info("Settings for " + this.getClass().getName() + " (CL: 0x"
            + Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
    info("  stopThreads = " + stopThreads);
    info("  stopTimerThreads = " + stopTimerThreads);
    info("  executeShutdownHooks = " + executeShutdownHooks);
    info("  threadWaitMs = " + threadWaitMs + " ms");
    info("  shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");

    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        // If package org.jboss is found, we may be running under JBoss
        mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
    } catch (Exception ex) {
        // Do nothing
    }

    info("Initializing context by loading some known offenders with system classloader");

    // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener  
    // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
    try {
        // Switch to system classloader in before we load/call some JRE stuff that will cause 
        // the current classloader to be available for garbage collection
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        // Christopher: Uncommented as it will not work on some containers as google app engine  
        //java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
        java.security.Security.getProviders();

        java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader

        // Christopher: Uncommented as it will not work on some containers as google app engine  
        //javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()

        try {
            Class.forName("javax.security.auth.Policy").getMethod("getPolicy").invoke(null);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (ClassNotFoundException e) {
            // Ignore silently - class is deprecated
        }

        try {
            javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception ex) { // Example: ParserConfigurationException
            error(ex);
        }

        try {
            Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        try {
            Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        // This probably does not affect classloaders, but prevents some problems with .jar files
        try {
            // URL needs to be well-formed, but does not need to exist
            new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
        } catch (Exception ex) {
            error(ex);
        }

        /////////////////////////////////////////////////////
        // Load Sun specific classes that may cause leaks

        final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");

        try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        }

        try {
            Class.forName("sun.java2d.Disposer"); // Will start a Thread
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE && !mayBeJBoss) // JBoss blocks this package/class, so don't warn
                error(cnfex);
        }

        try {
            Class<?> gcClass = Class.forName("sun.misc.GC");
            final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
            requestLatency.invoke(null, 3600000L);
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        }

        // Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader  
        try {
            Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
        } catch (ClassNotFoundException e) {
            // Ignore silently - class not present
        }
    } catch (Throwable ex) {
        error(ex);
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {//www.j a  va  2  s .  c om

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:com.silverpeas.bootstrap.SilverpeasContextBootStrapper.java

/**
 * Initialise the System.properties according to Silverpeas needs and configuration.
 *
 * @param sce//from  www . j a v a  2  s  .  c o  m
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
    ResourceBundle silverpeasInitialisationSettings = FileUtil.loadBundle(
            "org.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
            new Locale("fr", ""));

    loadExternalJarLibraries();

    String systemSettingsPath = silverpeasInitialisationSettings.getString("pathInitialize");
    if (!StringUtil.isDefined(systemSettingsPath)) {
        Logger.getLogger("bootstrap").log(Level.SEVERE,
                "Repository Initialize for systemSettings.properties file is not defined in Settings.");
    } else {
        File pathInitialize = new File(systemSettingsPath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(pathInitialize, "systemSettings.properties"));
            Properties systemFileProperties = new Properties(System.getProperties());
            systemFileProperties.load(fis);

            // Fix - empty proxy port and proxy host not supported by Spring Social
            if (!StringUtil.isDefined(systemFileProperties.getProperty("http.proxyPort"))) {
                systemFileProperties.remove("http.proxyPort");
            }
            if (!StringUtil.isDefined(systemFileProperties.getProperty("http.proxyHost"))) {
                systemFileProperties.remove("http.proxyHost");
            }

            System.setProperties(systemFileProperties);
            if (isTrustoreConfigured()) {
                registerSSLSocketFactory();
            }
        } catch (FileNotFoundException e) {
            Logger.getLogger("bootstrap").log(Level.SEVERE,
                    "File systemSettings.properties in directory {0} not found.", pathInitialize);
        } catch (IOException e) {
            Logger.getLogger("bootstrap").log(Level.SEVERE, "Unable to read systemSettings.properties.");
        } catch (GeneralSecurityException e) {
            Logger.getLogger("bootstrap").log(Level.SEVERE, "Unable to configure the trustore.");
        } finally {
            IOUtils.closeQuietly(fis);
        }

    }
    URLManager.setSilverpeasVersion(sce.getServletContext().getInitParameter("SILVERPEAS_VERSION"));
    springContextListener.contextInitialized(sce);
}

From source file:com.lwr.software.reporter.utils.Q2RContextListener.java

@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    logger.info("Creating directories if already created");

    logger.info("Creating config directory tree " + DashboardConstants.CONFIG_PATH);
    File dir = new File(DashboardConstants.CONFIG_PATH);
    if (dir.exists()) {
        logger.info("Config directory tree already exists");
    } else {/*from www .  j  a  v  a2 s.  c o  m*/
        boolean dirCreated = dir.mkdirs();
        if (dirCreated) {
            logger.info("Config directory tree created successfully");
        } else {
            logger.error("Config directory tree creation failed, please check for file permission on "
                    + DashboardConstants.CONFIG_PATH);
        }
    }

    logger.info("Creating public report directory tree " + DashboardConstants.PUBLIC_REPORT_DIR);
    dir = new File(DashboardConstants.PUBLIC_REPORT_DIR);
    if (dir.exists()) {
        logger.info("Public report directory tree already exists");
    } else {
        boolean dirCreated = dir.mkdirs();
        if (dirCreated) {
            logger.info("Public report directory tree created successfully");
        } else {
            logger.error("Public report directory tree creation failed, please check for file permission on "
                    + DashboardConstants.PUBLIC_REPORT_DIR);
        }
    }

    logger.info("Creating private report directory tree " + DashboardConstants.PRIVATE_REPORT_DIR);
    dir = new File(DashboardConstants.PRIVATE_REPORT_DIR);
    if (dir.exists()) {
        logger.info("Private report directory tree already exists");
    } else {
        boolean dirCreated = dir.mkdirs();
        if (dirCreated) {
            logger.info("Private report directory tree created successfully");
        } else {
            logger.error("Private report directory tree creation failed, please check for file permission on "
                    + DashboardConstants.PRIVATE_REPORT_DIR);
        }
    }

    logger.info("Creating private report directory tree " + DashboardConstants.APPLN_TEMP_DIR);
    dir = new File(DashboardConstants.APPLN_TEMP_DIR);
    if (dir.exists()) {
        logger.info("Private report directory tree already exists");
    } else {
        boolean dirCreated = dir.mkdirs();
        if (dirCreated) {
            logger.info("Private report directory tree created successfully");
        } else {
            logger.error("Private report directory tree creation failed, please check for file permission on "
                    + DashboardConstants.APPLN_TEMP_DIR);
        }
    }

    File logoFile = new File(DashboardConstants.APPLN_LOGO_FILE);
    if (logoFile.exists()) {
        String appLogo = contextEvent.getServletContext().getRealPath("/") + File.separatorChar + "images"
                + File.separatorChar + "q2r.png";
        File appLogoFile = new File(appLogo);
        logger.info("Coping of custom logo file " + logoFile.getAbsolutePath() + " to folder "
                + appLogoFile.getAbsolutePath());
        try {
            Files.copy(logoFile, appLogoFile);
            logger.info("Coping of custom logo file " + logoFile.getAbsolutePath() + " to folder "
                    + appLogoFile.getAbsolutePath() + " -- Copied");
        } catch (IOException e) {
            logger.error("Coping of custom logo file " + logoFile.getAbsolutePath() + " to folder "
                    + appLogoFile.getAbsolutePath() + " -- Failed", e);
        }
    }

    Q2RProperties.getInstance();
    logger.info("Loading build time from manifest file");
    try {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(inputStream);
        String buildTime = manifest.getMainAttributes().getValue("Build-Time");
        logger.info("Build time is " + buildTime);
        if (buildTime != null)
            Q2RProperties.getInstance().put("buildTime", buildTime);
    } catch (IOException e) {
        logger.error("Error loading manifest file", e);
    }
}

From source file:com.amazonaws.services.kinesis.aggregators.app.AggregatorsBeanstalkApp.java

@SuppressWarnings({ "unchecked" })
@Override//from  w  w  w  . j a v a  2  s.  c  o m
public void contextInitialized(ServletContextEvent contextEvent) {
    String configPath = System.getProperty(AggregatorsConstants.CONFIG_URL_PARAM);

    if (configPath != null && !configPath.equals("")) {
        LOG.info("Starting Managed Beanstalk Aggregators Worker");
        String streamNameParam = System.getProperty(AggregatorsConstants.STREAM_NAME_PARAM);
        String appNameParam = System.getProperty(AggregatorsConstants.APP_NAME_PARAM);
        String regionNameParam = System.getProperty(AggregatorsConstants.REGION_PARAM);
        String streamPosParam = System.getProperty(AggregatorsConstants.STREAM_POSITION_PARAM);
        String maxRecordsParam = System.getProperty(AggregatorsConstants.MAX_RECORDS_PARAM);
        String environmentParam = System.getProperty(AggregatorsConstants.ENVIRONMENT_PARAM);
        String failuresToleratedParam = System.getProperty(AggregatorsConstants.FAILURES_TOLERATED_PARAM);

        if (streamNameParam == null || streamNameParam.equals("") || appNameParam == null
                || appNameParam.equals("")) {
            LOG.error(String.format(
                    "Unable to run Beanstalk Managed Aggregator Consumer without Configuration of Parameters %s and %s. Application is Idle.",
                    AggregatorsConstants.STREAM_NAME_PARAM, AggregatorsConstants.APP_NAME_PARAM));
            return;
        }

        InitialPositionInStream initialPosition = null;
        if (streamPosParam != null) {
            try {
                initialPosition = InitialPositionInStream.valueOf(streamPosParam);
                LOG.info(String.format("Starting from %s Position in Stream", streamPosParam));
            } catch (Exception e) {
                LOG.error(String.format("%s is an invalid Initial Position in Stream", streamPosParam));
                return;
            }
        }

        try {
            AggregatorConsumer consumer = new AggregatorConsumer(streamNameParam, appNameParam, configPath);

            // add consumer parameters, if set from System Properties
            if (regionNameParam != null && !regionNameParam.equals("")) {
                consumer.withRegionName(regionNameParam);
            }

            if (initialPosition != null) {
                consumer.withInitialPositionInStream(initialPosition.name());
            }

            if (maxRecordsParam != null && !maxRecordsParam.equals("")) {
                consumer.withMaxRecords(Integer.parseInt(maxRecordsParam));
            }

            if (environmentParam != null && !environmentParam.equals("")) {
                consumer.withEnvironment(environmentParam);
            }

            if (failuresToleratedParam != null && !failuresToleratedParam.equals("")) {
                consumer.withToleratedWorkerFailures(Integer.parseInt(failuresToleratedParam));
            }

            // configure the consumer so that the aggregators get
            // instantiated
            consumer.configure();

            AggregatorGroup aggGroup = consumer.getAggregators();

            // put the aggregator group reference and configureation
            // references into the application context
            contextEvent.getServletContext().setAttribute(AGGREGATOR_GROUP_PARAM, aggGroup);
            contextEvent.getServletContext().setAttribute(AggregatorsConstants.STREAM_NAME_PARAM,
                    streamNameParam);

            LOG.info("Registered Stream and Aggregator Group with Servlet Context");

            // start the consumer
            final class ConsumerRunner implements Runnable {
                final AggregatorConsumer consumer;

                public ConsumerRunner(AggregatorConsumer consumer) {
                    this.consumer = consumer;
                }

                @Override
                public void run() {
                    try {
                        consumer.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error(e);
                    }
                }
            }
            t = new Thread(new ConsumerRunner(consumer));
            t.start();
        } catch (Exception e) {
            LOG.error(e);
        }
    } else {
        LOG.warn(String.format(
                "No Aggregators Configuration File found in Beanstalk Configuration %s. Application is Idle",
                AggregatorsConstants.CONFIG_URL_PARAM));
    }
}

From source file:com.sampleapp.db.DAOInitContextListener.java

@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    String dao = null;/* w w w .  j  a v  a 2 s  .c  om*/
    Properties serviceProperties = null;

    // Find database service - assumes only one
    Map<String, String> env;
    String vcap;
    JSONObject jsonProperties, credentials;

    env = System.getenv();
    vcap = env.get("VCAP_SERVICES");
    try {
        JSONObject vcap_services = new JSONObject(vcap);
        Iterator iter = vcap_services.keys();

        if (vcap == null) {
            System.err.println("DAOContextListener: No VCAP_SERVICES found!");
            return;
        }

        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (key.startsWith("mongodb")) {
                dao = DAOFactory.MONGO;
                jsonProperties = vcap_services.getJSONArray(key).getJSONObject(0);
                credentials = jsonProperties.getJSONObject("credentials");
                serviceProperties = new Properties();
                serviceProperties.put("hostname", credentials.getString("hostname"));
                serviceProperties.put("port", credentials.getString("port"));
                serviceProperties.put("username", credentials.getString("username"));
                serviceProperties.put("password", credentials.getString("password"));
                serviceProperties.put("db", credentials.getString("db"));

                break;
            }
            if (key.startsWith("SQLDB")) {
                dao = DAOFactory.SQLDB;
                jsonProperties = vcap_services.getJSONArray(key).getJSONObject(0);
                credentials = jsonProperties.getJSONObject("credentials");
                serviceProperties = new Properties();
                serviceProperties.put("jdbcurl", credentials.getString("jdbcurl"));
                serviceProperties.put("username", credentials.getString("username"));
                serviceProperties.put("password", credentials.getString("password"));
                break;
            }
            if (key.startsWith("mysql")) {
                dao = DAOFactory.MYSQL;
                jsonProperties = vcap_services.getJSONArray(key).getJSONObject(0);
                credentials = jsonProperties.getJSONObject("credentials");
                serviceProperties = new Properties();
                serviceProperties.put("name", credentials.getString("name"));
                serviceProperties.put("port", credentials.getString("port"));
                serviceProperties.put("username", credentials.getString("username"));
                serviceProperties.put("password", credentials.getString("password"));
                serviceProperties.put("host", credentials.getString("host"));
                break;
            }
            if (key.startsWith("postgresql")) {
                dao = DAOFactory.POSTGRES;
                jsonProperties = vcap_services.getJSONArray(key).getJSONObject(0);
                credentials = jsonProperties.getJSONObject("credentials");
                serviceProperties = new Properties();
                serviceProperties.put("name", credentials.getString("name"));
                serviceProperties.put("port", credentials.getString("port"));
                serviceProperties.put("username", credentials.getString("username"));
                serviceProperties.put("password", credentials.getString("password"));
                serviceProperties.put("host", credentials.getString("host"));
                break;
            }
            if (key.startsWith("user-provided")) {
                JSONArray array = vcap_services.getJSONArray(key);
                JSONObject obj = array.getJSONObject(0);
                if (obj.getString("name").startsWith("Cloudant")) {
                    dao = DAOFactory.CLOUDANT;
                    credentials = obj.getJSONObject("credentials");
                    serviceProperties = new Properties();
                    serviceProperties.put("url", credentials.getString("url"));
                    serviceProperties.put("username", credentials.getString("username"));
                    serviceProperties.put("password", credentials.getString("password"));
                    serviceProperties.put("database", credentials.getString("database"));
                    break;
                }
            }
            if (key.startsWith("JSONDB")) {
                dao = DAOFactory.JSONDB;
                jsonProperties = vcap_services.getJSONArray(key).getJSONObject(0);
                credentials = jsonProperties.getJSONObject("credentials");
                serviceProperties = new Properties();
                serviceProperties.put("hostname", credentials.getString("hostname"));
                serviceProperties.put("port", credentials.getString("port"));
                serviceProperties.put("username", credentials.getString("username"));
                serviceProperties.put("password", credentials.getString("password"));
                serviceProperties.put("db", credentials.getString("db"));
                break;
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    if (dao == null) {
        System.err.println("DAOContextListener: Fatal error no DB service found !");
        return;
    }

    System.out.println("DAOContextListener: " + dao + " database service found");
    final DAOFactory daoFactory = DAOFactory.getDAOFactory(dao, serviceProperties);
    contextEvent.getServletContext().setAttribute("daoname", dao);
    contextEvent.getServletContext().setAttribute("daofactory", daoFactory);

}

From source file:de.innovationgate.wgpublisher.WGACore.java

public void contextInitialized(ServletContextEvent arg0) {

    try {/*from w w  w .  j  a v a  2  s . c om*/
        _context = arg0.getServletContext();

        // General inits
        this.instanceActiveSince = new Date();
        arg0.getServletContext().setAttribute(ATTRIB_CORE, this);
        WGFactory.setAuthModuleFactory(new WGAAuthModuleFactory(this));
        WGFactory.setMimetypeDeterminationService(new WGAMimetypeDeterminationService());

        // Create temp dir
        File mainTempDir = new File(System.getProperty("java.io.tmpdir"));
        this.wgaTempDir = new File(mainTempDir, ".wgatemp");
        if (wgaTempDir.exists()) {
            killTempDir(wgaTempDir);
        }
        wgaTempDir.mkdir();
        WGFactory.setTempDir(wgaTempDir);
        TemporaryFile.prepareDirectory(wgaTempDir);

        // Creating logger
        initLoggingFile();
        String debug = System.getProperty(SYSPROPERTY_DEBUG);
        if (debug != null) {
            for (String target : WGUtils.deserializeCollection(debug, ",", true)) {
                Logger logger = Logger.getLogger(target);
                logger.setLevel(Level.DEBUG);
            }
        }

        // Try to retrieve build properties
        _buildSignature = "NOSIGNATURE";
        try {
            InputStream buildPropIn = _context.getResourceAsStream("/WEB-INF/wgabuild.properties");
            Properties props = new Properties();
            props.load(buildPropIn);
            if (props.containsKey("signature")) {
                _buildSignature = props.getProperty("signature");
            }
        } catch (RuntimeException e1) {
        }

        // Retrieving platform info
        String endDate = (new SimpleDateFormat("yyyy")).format(new Date());
        log.info(getReleaseString() + " (c) 2001-" + endDate + " Innovation Gate GmbH");
        try {
            this.servletPlatform = new Double(arg0.getServletContext().getMajorVersion() + "."
                    + arg0.getServletContext().getMinorVersion()).doubleValue();
            this.jspPlatform = new Double(
                    javax.servlet.jsp.JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion())
                            .doubleValue();
            log.info("On platform " + arg0.getServletContext().getServerInfo() + " (Servlet Engine "
                    + this.servletPlatform + ", JSP Engine " + this.jspPlatform + ")");
        } catch (Exception ecx) {
            log.warn("Unable to retrieve platform info. Assuming Servlet Engine 3.0, JSP Engine 2.2", ecx);
            this.servletPlatform = 3.0;
            this.jspPlatform = 2.2;
        }
        arg0.getServletContext().setAttribute(WGACore.ATTRIB_SERVLET_ENGINE, new Double(this.servletPlatform));
        arg0.getServletContext().setAttribute(WGACore.ATTRIB_JSP_ENGINE, new Double(this.jspPlatform));

        // Starting other non-servlet services
        this._deployer = new WGPDeployer(this);

        // Create the statistics object
        _usageStatistics = new WGAUsageStatistics(this);

        // Test some neccessary running conditions for WGA

        // We test for exploded WAR
        if (getServletContext().getRealPath("/") == null) {
            log.fatal(
                    "WGA is not deployed as exploded WGA archive which is absolutely mandatory! WebTML deploying and rendering will not work correctly.");
        }

        // Eventually overwrite wga configpath/datapath/permanent log sysvar with init parameter
        String initConfigPath = getServletContext().getInitParameter(SYSPROPERTY_CONFIGPATH);
        if (initConfigPath != null) {
            log.info("Using WGA config path from servlet init parameter: " + initConfigPath);
            System.setProperty(SYSPROPERTY_CONFIGPATH, initConfigPath);
        }
        String initDataPath = getServletContext().getInitParameter(SYSPROPERTY_DATAPATH);
        if (initDataPath != null) {
            log.info("Using WGA data path from servlet init parameter: " + initDataPath);
            System.setProperty(SYSPROPERTY_DATAPATH, initDataPath);
        }
        String initPermLog = getServletContext().getInitParameter(SYSPROPERTY_LOGPATH);
        if (initPermLog != null) {
            log.info("Using WGA permanent log path from servlet init parameter: " + initPermLog);
            System.setProperty(SYSPROPERTY_LOGPATH, initPermLog);
        }

        // Do startup
        fireCoreEvent(new WGACoreEvent(WGACoreEvent.TYPE_PRE_STARTUP, null, this));
        startup();
    } catch (Throwable e) {
        log.fatal("Fatal error initializing wga", e);
        e.printStackTrace();
    }

}