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.glaf.core.context.StartupListener.java

public void contextInitialized(ServletContextEvent event) {
    logger.info("initializing servlet context......");
    ServletContext context = event.getServletContext();
    String root = context.getRealPath("/");
    com.glaf.core.context.ApplicationContext.setAppPath(root);
    com.glaf.core.context.ApplicationContext.setContextPath(event.getServletContext().getContextPath());
    String webAppRootKey = event.getServletContext().getInitParameter("webAppRootKey");
    if (StringUtils.isNotEmpty(webAppRootKey)) {
        System.setProperty(webAppRootKey, SystemProperties.getAppPath());
    } else {/*from  w  w  w  .  ja va 2 s.  c o  m*/
        System.setProperty("webapp.root", SystemProperties.getAppPath());
    }
    for (int i = 1; i <= 20; i++) {
        System.setProperty("webapp" + i + ".root", SystemProperties.getAppPath());
    }
    System.setProperty("app.path", SystemProperties.getAppPath());
    System.setProperty("config.path", SystemProperties.getAppPath() + "/WEB-INF");
    if (DBConnectionFactory.checkConnection()) {
        DatabaseFactory.getInstance().reload();
        this.beforeContextInitialized(context);
        super.contextInitialized(event);
        this.setupContext(context);
    } else {
        logger.error("??");
    }
    if (SystemProperties.getDeploymentSystemName() != null) {
        String deploymentSystemName = SystemProperties.getDeploymentSystemName();
        String path = SystemProperties.getConfigRootPath() + Constants.DEPLOYMENT_JDBC_PATH
                + deploymentSystemName + "/jdbc";
        try {
            FileUtils.mkdirs(path);
        } catch (IOException ex) {
        }
        String log_path = SystemProperties.getConfigRootPath() + "/logs/" + deploymentSystemName;
        try {
            FileUtils.mkdirs(log_path);
        } catch (IOException ex) {
        }
    }

    try {
        File file = new File(SystemProperties.getConfigRootPath() + "/key");
        if (!(file.exists() || file.isFile())) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 32; i++) {
                sb.append(UUID32.getUUID());
            }
            FileUtils.save(SystemProperties.getConfigRootPath() + "/key", sb.toString().getBytes());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        ExecutionManager.getInstance().execute();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.jtalks.poulpe.web.listener.LoggerInitializationListener.java

/**
 * Initializing logger. For an idea how configuration file looks like, see class javadocs.
 *
 * @param event standard listener servlet event
 * @see <a href="http://wiki.apache.org/logging-log4j/Log4jXmlFormat">Log4j XML configuration apache tutorial</a>
 *///from w ww. j av  a  2 s  .com
@Override
public void contextInitialized(ServletContextEvent event) {
    servletContext = event.getServletContext();
    FileInfo fileInfo = log4jConfigLocation();
    // Skip standard Log4j auto configuration on first call
    String previousLog4jInitOverrideValue = System.setProperty(LOG4J_INIT_OVERRIDE_PROPERTY, "true");
    if (!loadLog4jConfigurationFromExternalFile(fileInfo)) {
        loadEmbeddedLog4jConfiguration();
    }
    // Return previous auto configuration property. It's shared between all applications in Tomcat
    if (previousLog4jInitOverrideValue == null) {
        System.clearProperty(LOG4J_INIT_OVERRIDE_PROPERTY);
    } else {
        System.setProperty(LOG4J_INIT_OVERRIDE_PROPERTY, previousLog4jInitOverrideValue);
    }
}

From source file:org.alfresco.web.app.ContextListener.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *//*from   ww  w . j  a  v  a  2s .  co  m*/
public void contextInitialized(ServletContextEvent event) {
    // make sure that the spaces store in the repository exists
    this.servletContext = event.getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

    // If no context has been initialised, exit silently so config changes can be made
    if (ctx == null) {
        return;
    }

    ServiceRegistry registry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    TransactionService transactionService = registry.getTransactionService();
    NodeService nodeService = registry.getNodeService();
    SearchService searchService = registry.getSearchService();
    NamespaceService namespaceService = registry.getNamespaceService();
    AuthenticationContext authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext");

    // repo bootstrap code for our client
    UserTransaction tx = null;
    NodeRef companySpaceNodeRef = null;
    try {
        tx = transactionService.getUserTransaction();
        tx.begin();
        authenticationContext.setSystemUserAsCurrentUser();

        // get and setup the initial store ref and root path from config
        StoreRef storeRef = Repository.getStoreRef(servletContext);

        // get root path
        String rootPath = Application.getRootPath(servletContext);

        // Extract company space id and store it in the Application object
        companySpaceNodeRef = Repository.getCompanyRoot(nodeService, searchService, namespaceService, storeRef,
                rootPath);
        Application.setCompanyRootId(companySpaceNodeRef.getId());

        // commit the transaction
        tx.commit();
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
        }

        logger.error("Failed to initialise ", e);
        throw new AlfrescoRuntimeException("Failed to initialise ", e);
    } finally {
        try {
            authenticationContext.clearCurrentSecurityContext();
        } catch (Exception ex) {
        }
    }
}

From source file:com.swiftcorp.portal.common.listener.CustomContextLoaderListener.java

public void contextInitialized(ServletContextEvent event) {
    System.out.println("Framework-->>StartupListener::");
    log.debug("initializing context...");

    super.contextInitialized(event);
    ServletContext ctx = event.getServletContext();

    /*/* w  w w . ja v  a 2 s.c om*/
     * FileStoragePath fileStoragePath =
     * (FileStoragePath)((ApplicationContext)ctx).getBean
     * ("FileStoragePath"); ReportServiceImpl reportService =
     * (ReportServiceImpl)((ApplicationContext)ctx).getBean
     * ("ReportService");
     * 
     * ApplicationConstants.REPORT_SERVICE = reportService ;
     * ApplicationConstants.FILE_STORAGE_DIR =
     * fileStoragePath.getFileStorageDirectory();
     * 
     * ApplicationConstants.FILE_STORAGE_UPLOAD_DIR =
     * ApplicationConstants.FILE_STORAGE_DIR + "upload/";
     * ApplicationConstants.FILE_STORAGE_TEMPLATE_DIR=
     * ApplicationConstants.FILE_STORAGE_DIR + "templates/";
     * ApplicationConstants.FILE_STORAGE_REPORT_DIR =
     * ApplicationConstants.FILE_STORAGE_DIR + "reports/";
     */
    boolean registered = true;// licensingService.isRegistered();
    if (registered) {
        // ctx.setAttribute ( ApplicationConstants.REGISTERED, "registered"
        // );

        log.info("******************************************************************************************");
        log.info("                   SERVER REGISTRATION SUCCESSFUL");
        log.info("******************************************************************************************");

        System.out.println(
                "******************************************************************************************");
        System.out.println("                   SERVER STARTED SUCCESSFULLY");
        System.out.println(
                "******************************************************************************************");
    } else {
        log.info("******************************************************************************************");
        log.info("                   SERVER NOT REGISTERED....PLEASE PROVIDE VALID LICENSE");
        log.info("******************************************************************************************");

        System.out.println(
                "******************************************************************************************");
        System.out.println("                   SERVER NOT REGISTERED....PLEASE PROVIDE VALID LICENSE");
        System.out.println(
                "******************************************************************************************");
    }

}

From source file:com.wabacus.WabacusServlet.java

public void contextInitialized(ServletContextEvent event) {
    closeAllDatasources();/*from  ww  w  . jav a2  s . c  om*/
    Config.homeAbsPath = event.getServletContext().getRealPath("/");
    Config.homeAbsPath = FilePathAssistant.getInstance().standardFilePath(Config.homeAbsPath + "\\");
    /*try
    {
    Config.webroot=event.getServletContext().getContextPath();
    if(!Config.webroot.endsWith("/")) Config.webroot+="/";
    }catch(NoSuchMethodError e)
    {
    Config.webroot=null;
    }*/
    Config.webroot = null;
    Config.configpath = event.getServletContext().getInitParameter("configpath");
    if (Config.configpath == null || Config.configpath.trim().equals("")) {
        log.info("??" + Config.homeAbsPath
                + "??");
        Config.configpath = Config.homeAbsPath;
    } else {
        Config.configpath = WabacusAssistant.getInstance().parseConfigPathToRealPath(Config.configpath,
                Config.homeAbsPath);
    }
    loadReportConfigFiles();
    FileUpDataImportThread.getInstance().start();
    TimingThread.getInstance().start();
}

From source file:org.tonguetied.web.servlet.ServletContextInitializer.java

/**
 * Perform a graceful shutdown of the server servlets. If the server is
 * running an embedded database, then this is shut down here.
 * /* w w  w . j ava  2 s .co  m*/
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */
public void contextDestroyed(ServletContextEvent event) {
    Properties props = loadProperties(event.getServletContext(), DIR_WEB_INF + "/jdbc.properties");
    final String dialect = props.getProperty(KEY_HIBERNATE_DIALECT);
    // shutdown the embedded database if it is running
    if (EmbeddedDatabaseServer.isEmbeddable(dialect))
        EmbeddedDatabaseServer.stopDatabase();
}

From source file:org.atmosphere.vibe.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override//  www  . ja v  a  2 s  .  c  o m
        public void on(final ServerSocket socket) {
            socket.on("abort", new VoidAction() {
                @Override
                public void on() {
                    socket.close();
                }
            }).on("echo", new Action<Object>() {
                @Override
                public void on(Object data) {
                    socket.send("echo", data);
                }
            }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() {
                @Override
                public void on(Reply<Map<String, Object>> reply) {
                    Map<String, Object> data = reply.data();
                    switch ((String) data.get("type")) {
                    case "resolved":
                        reply.resolve(data.get("data"));
                        break;
                    case "rejected":
                        reply.reject(data.get("data"));
                        break;
                    }
                }
            }).on("/reply/outbound", new Action<Map<String, Object>>() {
                @Override
                public void on(Map<String, Object> data) {
                    switch ((String) data.get("type")) {
                    case "resolved":
                        socket.send("test", data.get("data"), new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    case "rejected":
                        socket.send("test", data.get("data"), null, new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    }
                }
            });
        }
    });
    final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);

    org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server();
    ServerConnector connector = new ServerConnector(jetty);
    connector.setPort(8000);
    jetty.addConnector(connector);
    ServletContextHandler handler = new ServletContextHandler();
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            // /setup
            ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    Map<String, String[]> params = req.getParameterMap();
                    if (params.containsKey("heartbeat")) {
                        server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0]));
                    }
                    if (params.containsKey("_heartbeat")) {
                        server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0]));
                    }
                }
            });
            regSetup.addMapping("/setup");
            // /vibe
            Servlet servlet = new VibeAtmosphereServlet().onhttp(httpTransportServer)
                    .onwebsocket(wsTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(),
                    servlet);
            reg.setAsyncSupported(true);
            reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString());
            reg.addMapping("/vibe");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    jetty.setHandler(handler);
    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--vibe.transports")
            .addArgument("websocket,httpstream,httplongpoll");
    DefaultExecutor executor = new DefaultExecutor();
    // The exit value of mocha is the number of failed tests.
    executor.execute(cmdLine);

    jetty.stop();
}

From source file:it.pronetics.madstore.crawler.impl.grid.support.MadStoreGridListener.java

public void contextInitialized(ServletContextEvent event) {
    if (MadStoreConfigurationManager.getInstance().getMadStoreConfiguration().isGridModeEnabled()) {
        ApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(event.getServletContext());
        Collection beans = context.getBeansOfType(MadStoreGrid.class).values();
        try {/* ww  w.  jav  a  2s  .  c  o  m*/
            if (beans.size() == 1) {
                madstoreGrid = (MadStoreGrid) beans.iterator().next();
                madstoreGrid.startGrid();
            } else if (beans.size() == 0) {
                throw new IllegalStateException("No grid factory found in Spring application context!");
            } else {
                throw new IllegalStateException(
                        "More than one grid factory found in Spring application context!");
            }
        } catch (GridException ex) {
            throw new RuntimeException("Error during grid startup", ex);
        }
    }
}

From source file:org.apache.struts.faces.taglib.LifecycleListener.java

/**
 * <p>Process a "context initialized" event.</p>
 *
 * @param event The <code>ServletContextEvent</code> that has occurred
 *//* w w w . ja va 2s  . c o m*/
public void contextInitialized(ServletContextEvent event) {

    log.info("contextInitialized()");
    servletContext = event.getServletContext();
    createPropertyResolver();

}

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

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext());

    Properties properties = new Properties();
    ServletContext context = servletContextEvent.getServletContext();
    InputStream inputStream = null;
    try {/*from w  ww  . j a  v a2  s . c o  m*/
        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);

    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 Web Services starting...");
    logger.info("=================================================\n{}", builder.toString());
}