@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"); }
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."); }
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(); }
@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); } }
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."); }
@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); }
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; }
@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); } }
@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); } }
@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); } }
/** * 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; }
@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)); }
@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); } }
@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); }
@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); }
@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"); }
/** * 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()); } }
@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)); }
/** * 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); } }
@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); } }
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 }
@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); }
@Override public void contextInitialized(ServletContextEvent arg0) { logger.info("accessToken监听器启动.........."); timer = new Timer(true); //注册定时任务 registeAccessTokenTimer(); //注册jsapi_ticket定时器 registeJsApiTicketTimer(); }
/** * 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()"); }
@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(); } }
@Override public void contextDestroyed(ServletContextEvent sce) { kmsAudit.shutdown(); kmsAcls.stopReloader(); jmxReporter.stop(); jmxReporter.close(); metricRegistry = null; LOG.info("KMS Stopped"); }
/** * 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()); }
@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 }
@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()); }
@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()); }
@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(""); }
@Override public void contextDestroyed(ServletContextEvent servletContextEvent) { logger.info("stoping DrinkWaterApplication through servlet contextDestroyed"); if (drinkWaterApplication != null) { drinkWaterApplication.stop(); } logger.info("DrinkWaterApplication stopped ..... bok !"); }
@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); }
@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"); }
/** * {@inheritDoc} */ @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); try { context.setAttribute("upTime", System.currentTimeMillis()); } catch (Exception e) { } }
@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); } }