Java 类javax.servlet.ServletContextEvent 实例源码

项目:uavstack    文件:DynamicServletInit.java   
@Override
public void contextInitialized(ServletContextEvent sce) {

    ServletContext ctx = sce.getServletContext();

    ServletRegistration.Dynamic sd = ctx.addServlet("DynamicServlet",
            "com.creditease.monitorframework.fat.DynamicServlet");

    sd.addMapping("/DynamicServlet");
    sd.setInitParameter("test", "test");
    sd.setLoadOnStartup(1);
    sd.setAsyncSupported(false);

    FilterRegistration.Dynamic fd = ctx.addFilter("DynamicFilter",
            "com.creditease.monitorframework.fat.filters.DynamicFilter");

    fd.addMappingForUrlPatterns(null, true, "/DynamicServlet");
    fd.setInitParameter("test2", "test2");
    fd.setAsyncSupported(false);

    ctx.addListener("com.creditease.monitorframework.fat.listeners.TestServletInitListener");
}
项目:asura    文件:QuartzInitializerListener.java   
public void contextDestroyed(ServletContextEvent sce) {

        if (!performShutdown) {
            return;
        }

        try {
            if (scheduler != null) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            log.error("Quartz Scheduler failed to shutdown cleanly: " + e.toString());
            e.printStackTrace();
        }

        log.info("Quartz Scheduler successful shutdown.");
    }
项目:openrouteservice    文件:ORSInitContextListener.java   
public void contextInitialized(ServletContextEvent contextEvent) 
{
    Runnable runnable = () -> {
        try {
            RoutingProfileManager.getInstance().toString();
        }
        catch (Exception e) {
            LOGGER.warn("Unable to initialize ORS.");
            e.printStackTrace();
        } 
    };

    Thread thread = new Thread(runnable);
    thread.setName("ORS-Init");
    thread.start();
}
项目:tomcat7    文件:TestWsServerContainer.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

    ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(
            TesterEchoServer.Basic.class, "/{param}").build();

    try {
        sc.addEndpoint(sec);
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
项目:lams    文件:QuartzInitializerListener.java   
public void contextDestroyed(ServletContextEvent sce) {

        if (!performShutdown) {
            return;
        }

        try {
            if (scheduler != null) {
                scheduler.shutdown(waitOnShutdown);
            }
        } catch (Exception e) {
            log.error("Quartz Scheduler failed to shutdown cleanly: " + e.toString());
            e.printStackTrace();
        }

        log.info("Quartz Scheduler successful shutdown.");
    }
项目:oscm    文件:LoggerInitListenerTest.java   
@Test
public void contextInitialized() throws Exception {
    // given
    ServletContextEvent event = mock(ServletContextEvent.class);

    // when contextInitialized and access logged
    listener.contextInitialized(event);

    logger.logInfo(Log4jLogger.ACCESS_LOG,
            LogMessageIdentifier.INFO_USER_LOGIN_SUCCESS, "test-user",
            "10.140.19.9");

    // then
    final String logEntryRegEx = getInfoEntryStartRegEx()
            + ".*test-user.*logged\\sin.*\\(.*10\\.140\\.19\\.9\\).*";

    assertWrittenToLogFile(logEntryRegEx);

}
项目:scott-eu    文件:ServletListener.java   
private static String getServletUrlPattern(final ServletContextEvent servletContextEvent) throws Exception {
    final ServletContext servletContext = servletContextEvent.getServletContext();

    ServletRegistration servletRegistration = servletContext.getServletRegistration(servletName);
    if (servletRegistration == null) {
        throw new NoSuchElementException("no servlet with name \"" + servletName + "\" is found.");
    }
    java.util.Collection<java.lang.String> mappings = servletRegistration.getMappings();
    if (mappings.size() != 1) {
        throw new NoSuchElementException("unable to identify servlet mappings for servlet with name \"" + servletName + "\".");
    }
    String mapping = (String) mappings.toArray()[0];

    //url patterns in  most cases end with '\*'. But a url-pattern with just '\' may be found for exact matches.
    if (mapping.endsWith("*"))
        mapping = mapping.substring(0, mapping.length()-1);
    return mapping;
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestCloseBug58624.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

    ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute(
            Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

    ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(
            Bug58624ServerEndpoint.class, PATH).build();

    try {
        sc.addEndpoint(sec);
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:TesterEchoServer.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(Async.class);
        sc.addEndpoint(Basic.class);
        sc.addEndpoint(BasicLimitLow.class);
        sc.addEndpoint(BasicLimitHigh.class);
        sc.addEndpoint(RootEcho.class);
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
项目:tomcat7    文件:TestWsWebSocketContainer.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(ServerEndpointConfig.Builder.create(
                ConstantTxEndpoint.class, PATH).build());
        if (TestWsWebSocketContainer.timeoutOnContainer) {
            sc.setAsyncSendTimeout(TIMEOUT_MS);
        }
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
项目:scott-eu    文件:ServletListener.java   
private static String getServletUrlPattern(final ServletContextEvent servletContextEvent) throws Exception {
    final ServletContext servletContext = servletContextEvent.getServletContext();

    ServletRegistration servletRegistration = servletContext.getServletRegistration(servletName);
    if (servletRegistration == null) {
        throw new NoSuchElementException("no servlet with name \"" + servletName + "\" is found.");
    }
    java.util.Collection<java.lang.String> mappings = servletRegistration.getMappings();
    if (mappings.size() != 1) {
        throw new NoSuchElementException("unable to identify servlet mappings for servlet with name \"" + servletName + "\".");
    }
    String mapping = (String) mappings.toArray()[0];

    //url patterns in  most cases end with '\*'. But a url-pattern with just '\' may be found for exact matches.
    if (mapping.endsWith("*"))
        mapping = mapping.substring(0, mapping.length()-1);
    return mapping;
}
项目:lams    文件:ConfigurationUtil.java   
/**
 * Returns the value of the specified servlet context initialization parameter.
 *
 * @param param          the parameter to return
 * @param sce            the <code>ServletContextEvent</code> being handled
 * @param caller         calling object, used for printing information if there is a problem
 * @param throwException if <code>true</code> then the method will throw an exception; if
 *                       <code>false</code> is supplied then it will return <code>null</code>
 * @return the value of the specified servlet context initialization parameter if found;
 *         <code>null</code> otherwise
 * @throws IllegalArgumentException if the parameter does not exist
 */
private static String getServletContextParam(String param, ServletContextEvent sce,
        Object caller, boolean throwException)
        throws IllegalArgumentException
{
    ServletContext context = sce.getServletContext();
    String value = context.getInitParameter(param);

    if (value == null && throwException)
    {
        throw new IllegalArgumentException("'" + param + "' is a required "
                + "servlet context initialization parameter for the \""
                + caller.getClass().getName() + "\" class.  Aborting.");
    }

    return value;
}
项目:apache-tomcat-7.0.73-with-comment    文件:TestWsWebSocketContainer.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(ServerEndpointConfig.Builder.create(
                ConstantTxEndpoint.class, PATH).build());
        if (TestWsWebSocketContainer.timeoutOnContainer) {
            sc.setAsyncSendTimeout(TIMEOUT_MS);
        }
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
项目:hevelian-activemq    文件:WebBrokerInitializerTest.java   
@Test
public void contextDestroyed() throws Exception {
    ServletContext sc = mock(ServletContext.class);

    BrokerService broker = mock(BrokerService.class);
    doReturn(true).when(broker).isStarted();
    doReturn(true).when(broker).waitUntilStarted();

    WebBrokerInitializer i = spy(WebBrokerInitializer.class);
    doReturn(broker).when(i).createBroker(sc);

    i.contextInitialized(new ServletContextEvent(sc));
    i.contextDestroyed(new ServletContextEvent(sc));
}
项目:tomcat7    文件:TesterFirehoseServer.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(Endpoint.class);
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
项目:incubator-servicecomb-java-chassis    文件:TestRestServletContextListener.java   
@Test
public void testcontextInitializedException() {
  boolean status = true;
  RestServletContextListener listener = new RestServletContextListener();
  ServletContextEvent sce = Mockito.mock(ServletContextEvent.class);

  try {
    listener.contextInitialized(sce);
  } catch (Exception | Error e) {
    status = false;
  }
  Assert.assertFalse(status);
}
项目:incubator-servicecomb-java-chassis    文件:TestRestServletContextListener.java   
@Test
public void testInitSpring() {
  boolean status = true;
  RestServletContextListener listener = new RestServletContextListener();
  ServletContextEvent sce = Mockito.mock(ServletContextEvent.class);
  ServletContext context = Mockito.mock(ServletContext.class);
  Mockito.when(sce.getServletContext()).thenReturn(context);
  Mockito.when(sce.getServletContext().getInitParameter("contextConfigLocation")).thenReturn("locations");
  try {
    listener.initSpring(sce);
  } catch (Exception e) {
    status = false;
  }
  Assert.assertFalse(status);
}
项目:lra-service    文件:BeanConfiguration.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    FilterRegistration.Dynamic filterRegistration = sce.getServletContext()
            .addFilter("BraveServletFilter", new TracingFilter(tracer));
    // Explicit mapping to avoid trace on readiness probe
    filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/order");
}
项目:uDetective    文件:ServiceNowListener.java   
/**
 * Initializes listener context
 * @param servletContext 
 */
@Override
public void contextInitialized(ServletContextEvent servletContext) {
    log.info("Context Initialized");

    int fetchInterval = Integer.parseInt(AppProperties.getProperty("fetch_interval"));
    log.debug("Fetch interval =" + fetchInterval);

    try {
        // Setup the Job class and the Job group
        JobDetail job = newJob(ServiceNowJob.class).withIdentity(
                        "CronQuartzJob", "ServiveNow").build();

        Trigger trigger = newTrigger()
            .withIdentity("Trigger_1", "ServiveNow")
            .withSchedule(simpleSchedule()
                .withIntervalInMinutes(fetchInterval)
                .repeatForever()
                .withMisfireHandlingInstructionNextWithExistingCount())
            .build();                        


        // Setup the Job and Trigger with Scheduler & schedule jobs
        scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        log.error(e.toString());
    }
}
项目:hevelian-activemq    文件:WebBrokerInitializerTest.java   
@Test(expected = BrokerLifecycleException.class)
public void contextDestroyed_excDuringWaitUntilStopped_ExcThrown() throws Exception {
    ServletContext sc = mock(ServletContext.class);

    BrokerService broker = mock(BrokerService.class);
    doReturn(true).when(broker).isStarted();
    doReturn(true).when(broker).waitUntilStarted();
    doThrow(new BrokerLifecycleException()).when(broker).waitUntilStopped();

    WebBrokerInitializer i = spy(WebBrokerInitializer.class);
    doReturn(broker).when(i).createBroker(sc);

    i.contextInitialized(new ServletContextEvent(sc));
    i.contextDestroyed(new ServletContextEvent(sc));
}
项目:cas-server-4.2.1    文件:AbstractServletContextInitializer.java   
/**
 * Add endpoint mapping to cas servlet.
 *
 * @param sce the sce
 * @param mapping the mapping
 */
protected final void addEndpointMappingToCasServlet(final ServletContextEvent sce, final String mapping) {
    logger.info("Adding [{}] to {} servlet context", mapping, WebUtils.CAS_SERVLET_NAME);
    final ServletRegistration registration = getCasServletRegistration(sce);
    if (registration != null) {

        registration.addMapping(mapping);
        logger.info("Added [{}] to {} servlet context", mapping, WebUtils.CAS_SERVLET_NAME);
    }
}
项目:ats-framework    文件:AgentWsContextListener.java   
@Override
public void contextInitialized( ServletContextEvent servletEvent ) {

    ServletContext servletContext = servletEvent.getServletContext();
    servletContext.log("Servlet context initialized event is received. Starting registering configurators");
    try {
        new ClasspathUtils().logProblematicJars();
    } catch (RuntimeException e) {
        log.warn("Error caught while trying to get all JARs in classpath", e);
        // do not rethrow exception as this will stop deployment on incompliant servers like JBoss
    }

    // create the default web service configurator
    String pathToConfigFile = servletContext.getRealPath("/WEB-INF");
    AgentConfigurator defaultConfigurator = new AgentConfigurator(pathToConfigFile);
    TemplateActionsConfigurator templateActionsConfigurator = new TemplateActionsConfigurator(pathToConfigFile);
    List<Configurator> configurators = new ArrayList<Configurator>();
    configurators.add(defaultConfigurator);
    configurators.add(templateActionsConfigurator);

    log.info("Initializing ATS Agent web service, start component registration");

    try {
        MainComponentLoader.getInstance().initialize(configurators);
    } catch (AgentException ae) {
        throw new RuntimeException("Unable to initialize Agent component loader", ae);
    }
}
项目:scott-eu    文件:PlannerReasonerManager.java   
public static void contextInitializeServletListener(final ServletContextEvent servletContextEvent)
{

    // Start of user code contextInitializeServletListener
    // TODO Implement code to establish connection to data backbone etc ...
    // End of user code
}
项目:websocket    文件:WebsocketListener.java   
@Override
public void contextInitialized(ServletContextEvent arg0) {
    // 载入配置文件
    final Properties p = PropertyUtil.loadProperties("/ws.properties");
    // context-param 优先级高
    String handleClass = arg0.getServletContext().getInitParameter(
            Constaint.HANDLER_CLASS);
    if (!StringUtil.isEmpty(handleClass))
        p.setProperty(Constaint.HANDLER_CLASS, handleClass);
    // 启动服务
    new Thread(new Runnable() {
        public void run() {
            WebSocketServer.startWebSocket(p);
        }
    }).start();
    // keep alive
    String sizeStr = p.getProperty("webSocketHbSize");
    Integer size = StringUtil.isNumeric(sizeStr) ? Integer
            .parseInt(sizeStr) : 1;
    // 初始化心跳线程池 - 默认单线程
    WebSocketServer.initHeartBeatThreadPool(size);
    // 调度周期 - 默认30s
    String intervalStr = p.getProperty("webSocketHbInterval");
    Integer interval = StringUtil.isNumeric(intervalStr) ? Integer
            .parseInt(intervalStr) : 30;
    s = Executors.newSingleThreadScheduledExecutor();
    s.scheduleWithFixedDelay(new Runnable() {
        public void run() {
            new WebSocketServer().heartBeats();
        }
    }, interval, interval, TimeUnit.SECONDS);
}
项目:framework    文件:TokenListener.java   
@Override
public void contextInitialized(ServletContextEvent arg0) {
    logger.info("accessToken监听器启动..........");
    timer = new Timer(true);
    //注册定时任务
    registeAccessTokenTimer();
    //注册jsapi_ticket定时器
    registeJsApiTicketTimer();
}
项目:apache-tomcat-7.0.73-with-comment    文件:SessionListener.java   
/**
 * Record the fact that this web application has been initialized.
 *
 * @param event
 *            The servlet context event
 */
@Override
public void contextInitialized(ServletContextEvent event) {

    this.context = event.getServletContext();
    log("contextInitialized()");

}
项目:lazycat    文件:WsContextListener.java   
@Override
public void contextDestroyed(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    Object obj = sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    if (obj instanceof WsServerContainer) {
        ((WsServerContainer) obj).destroy();
    }
}
项目:hadoop-oss    文件:KMSWebApp.java   
@Override
public void contextDestroyed(ServletContextEvent sce) {
  kmsAudit.shutdown();
  kmsAcls.stopReloader();
  jmxReporter.stop();
  jmxReporter.close();
  metricRegistry = null;
  LOG.info("KMS Stopped");
}
项目:lams    文件:WebAppServletContextFactoryTest.java   
/**
 * Tests that the new mechanism for configuring a launcher from a 
 * servlet context works.
 * 
 * @throws NamingException a problem with the test
 */
public void testConfiguredContext() throws NamingException
{
    JdbcMigrationLauncherFactory launcherFactory = new JdbcMigrationLauncherFactory();
    MockServletContext sc = new MockServletContext();

    String dbType = "mysql";
    String sysName = "testSystem";

    sc.setInitParameter("migration.systemname", sysName);
    sc.setInitParameter("migration.readonly", "true");
    sc.setInitParameter("migration.databasetype", dbType);
    sc.setInitParameter("migration.patchpath", "patches");
    sc.setInitParameter("migration.datasource", "java:comp/env/jdbc/testsource");

    MockDataSource ds = new MockDataSource();
    InitialContext context = new InitialContext();
    context.bind("java:comp/env/jdbc/testsource", ds);
    ServletContextEvent sce = new ServletContextEvent(sc);
    JdbcMigrationLauncher launcher = null;
    try
    {
        launcher = launcherFactory.createMigrationLauncher(sce);
    } 
    catch (MigrationException e)
    {
        e.printStackTrace();
        fail("There should not have been an exception");
    }

    JdbcMigrationContext jdbcContext = 
        (JdbcMigrationContext) launcher.getContexts().keySet().iterator().next();
    assertEquals(dbType, jdbcContext.getDatabaseType().getDatabaseType());
    assertEquals(sysName, jdbcContext.getSystemName());
    assertEquals(true, launcher.isReadOnly());
}
项目:scott-eu    文件:ServletListener.java   
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
    // Start of user code contextDestroyed_init
    // End of user code

    // Shutdown connections to data backbone etc...
    TwinManager.contextDestroyServletListener(servletContextEvent);

    // Start of user code contextDestroyed_final
    // End of user code
}
项目:oryx2    文件:ClassificationDistributionTest.java   
@Override
public final void contextInitialized(ServletContextEvent sce) {
  ServletContext context = sce.getServletContext();
  context.setAttribute(OryxResource.MODEL_MANAGER_KEY,
                       new MockClassificationServingModelManager(ConfigUtils.getDefault()));
  context.setAttribute(OryxResource.INPUT_PRODUCER_KEY, new MockTopicProducer());
}
项目:hevelian-activemq    文件:ServletContextHolderInitializerTest.java   
@Test
public void contextDestroyed() {
    ServletContextHolderInitializer i = new ServletContextHolderInitializer();
    ServletContext sc = Mockito.mock(ServletContext.class);
    ServletContextHolder.setServletContext(sc);
    i.contextDestroyed(new ServletContextEvent(sc));
    assertFalse(ServletContextHolder.isServletContextSet());
}
项目:javametrics    文件:MetricsContextListener.java   
@Override
public void contextInitialized(ServletContextEvent event) {
    // Uncomment the next line to enable the default hotspot events.
    // DefaultExports.initialize();

    metrics = new Metrics();
    ServletContext context = event.getServletContext();
    context.addServlet("Metrics", new MetricsServlet()).addMapping("");
}
项目:drinkwater-java    文件:DrinkWaterServletContextListener.java   
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    logger.info("stoping DrinkWaterApplication through servlet contextDestroyed");

    if (drinkWaterApplication != null) {
        drinkWaterApplication.stop();
    }

    logger.info("DrinkWaterApplication stopped .....  bok !");
}
项目:apache-tomcat-7.0.73-with-comment    文件:WsContextListener.java   
@Override
public void contextDestroyed(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    Object obj = sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    if (obj instanceof WsServerContainer) {
        ((WsServerContainer) obj).destroy();
    }
}
项目:webauthndemo    文件:OfyHelper.java   
@Override
public void contextInitialized(ServletContextEvent event) {
  ObjectifyService.register(User.class);
  ObjectifyService.register(Credential.class);
  ObjectifyService.register(AttestationSessionData.class);
  ObjectifyService.register(SessionData.class);
  ObjectifyService.register(AuthenticatorAttestationResponse.class);
  ObjectifyService.register(RsaKey.class);
  ObjectifyService.register(EccKey.class);
  ObjectifyService.register(FidoU2fAttestationStatement.class);
  ObjectifyService.register(AndroidSafetyNetAttestationStatement.class);
}
项目:webpage-update-subscribe    文件:InitListener.java   
@Override
public void contextInitialized(ServletContextEvent arg0) {
    System.out.println("Webpage Update Subscribe started");
    MySQLDatabaseConnection.initialDatabaseDeploy();
    try {
        MyCronTrigger.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Initialization complete");
}
项目:java-course    文件:ContextListener.java   
/**
 * {@inheritDoc}
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    try {
        context.setAttribute("upTime", System.currentTimeMillis());
    } catch (Exception e) {
    }
}
项目:lazycat    文件:WsContextListener.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    // Don't trigger WebSocket initialization if a WebSocket Server
    // Container is already present
    if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) {
        WsSci.init(sce.getServletContext(), false);
    }
}