/* * Registers a subcontext with red5 */ public void registerSubContext(String webAppKey) { // get the sub contexts - servlet context ServletContext ctx = servletContext.getContext(webAppKey); if (ctx == null) { ctx = servletContext; } ContextLoader loader = new ContextLoader(); ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader.initWebApplicationContext(ctx); appCtx.setParent(applicationContext); appCtx.refresh(); ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx); ConfigurableBeanFactory appFactory = appCtx.getBeanFactory(); logger.debug("About to grab Webcontext bean for " + webAppKey); Context webContext = (Context) appCtx.getBean("web.context"); webContext.setCoreBeanFactory(parentFactory); webContext.setClientRegistry(clientRegistry); webContext.setServiceInvoker(globalInvoker); webContext.setScopeResolver(globalResolver); webContext.setMappingStrategy(globalStrategy); WebScope scope = (WebScope) appFactory.getBean("web.scope"); scope.setServer(server); scope.setParent(global); scope.register(); scope.start(); // register the context so we dont try to reinitialize it registeredContexts.add(ctx); }
@Test public void updateTargetUrlWithContextLoader() throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class); MockServletContext servletContext = new MockServletContext(); ContextLoader contextLoader = new ContextLoader(wac); contextLoader.initWebApplicationContext(servletContext); try { RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class); wac.getBean(RequestDataValueProcessorWrapper.class) .setRequestDataValueProcessor(mockProcessor); RedirectView rv = new RedirectView(); rv.setUrl("/path"); MockHttpServletRequest request = createRequest(); HttpServletResponse response = new MockHttpServletResponse(); given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123"); rv.render(new ModelMap(), request, response); verify(mockProcessor).processUrl(request, "/path"); } finally { contextLoader.closeWebApplicationContext(servletContext); } }
public void init(ServletContext sCtx) throws Exception { if (null != sCtx) { ContextLoader ctloader = new ContextLoader(); webCtx = ctloader.initWebApplicationContext(sCtx); } if (null == webCtx) { clsPathCtx = new ClassPathXmlApplicationContext(beanConfigFiles()); } }
public void exportmain( String exportType, Map parameters, String jaspername, List lists, String defaultFilename, String url) { // logger.debug("进入导出 The method======= exportmain() start......................."); ActionContext ct = ActionContext.getContext(); // HttpServletRequest request = (HttpServletRequest) ct.get(ServletActionContext.HTTP_REQUEST); // HttpServletResponse response = ServletActionContext.getResponse(); String filenurl = null; // filenurl = ServletActionContext.getRequest().getRealPath(url + jaspername);// // jasper文件放在WebRoot/ireport/xx.jasper</span> filenurl = ContextLoader.getCurrentWebApplicationContext() .getServletContext() .getRealPath(url + jaspername); File file = new File(filenurl); InputStream is = null; try { is = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } export(lists, parameters, exportType, defaultFilename, is); }
/** * Extension of {@link ResourceBundle}, which gets resources from the database. * * @author Evgeny Mironenko */ public class DatabaseResourceBundle extends ResourceBundle { private final ResourceService service = (ResourceService) ContextLoader.getCurrentWebApplicationContext().getBean("resourceService"); private Locale locale; public DatabaseResourceBundle() { this.locale = Locale.ENGLISH; } public DatabaseResourceBundle(Locale locale) { this.locale = locale; } @Override protected Object handleGetObject(String key) { return service.getValue(locale, key); } @Override public Enumeration<String> getKeys() { return service.getKeys(locale); } }
@Override public void notify(DelegateExecution execution) throws Exception { if (execution.getVariable(Constants.CURRENT_BUSINESS_ID) != null) { WebApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); VehicleUsesRegService vehicleUsesRegService = (VehicleUsesRegService) ctx.getBean("vehicleUsesRegService"); Integer id = Integer.valueOf(execution.getVariable(Constants.CURRENT_BUSINESS_ID).toString()); vehicleUsesRegService.updateProcStatus(id, "2"); } }
/** * getInstance. * * @return a {@link net.sourceforge.seqware.common.ContextImpl} object. */ public static synchronized ContextImpl getInstance() { if (ctx == null) { ApplicationContext c = ContextLoader.getCurrentWebApplicationContext(); if (c == null) { Log.info("ContextImpl: Could not find web context. Switching to XML context."); c = new ClassPathXmlApplicationContext("applicationContext.xml"); } ctx = (ContextImpl) c.getBean("contextImpl"); } return ctx; }
@Override public void init() throws ServletException { super.init(); if (_delegate == null) { WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext(); DescriptorService delegate = applicationContext.getBean(DescriptorService.class); if (delegate == null) { throw new ServletException("No delegate found in application context!"); } _delegate = delegate; } }
public static String getCache() { WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); ServletContext servletContext = webApplicationContext.getServletContext(); cache = servletContext.getRealPath("/").replace('\\', '/'); // cache = Option.class.getClassLoader().getResource("").getPath() + "/svg"; // cache = // "C:/Development/JAVA/Tomacat/apache-tomcat-8.0.28-windows-x64/apache-tomcat-8.0.28/me-webapps/gridCPProject"; // cache = "D:/tongyuan/works/configuration/syslink/Cache"; // cache = Option.class.getClassLoader().getResource("").getPath() + "svg"; // cache = // "C:/Development/JAVA/Tomacat/apache-tomcat-8.0.28-windows-x64/apache-tomcat-8.0.28/me-webapps/gridCPProject/static/svg"; // cache = "D:/tongyuan/works/configuration/syslink/Cache"; // System.out.println("getCache: " + cache); return cache; }
@SuppressWarnings("unchecked") @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { // this is servlet container application context WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); if (wac == null) { String message = "Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?"; logger.error(message); throw new IllegalStateException(message); } // obtain spring application context WebApplicationContext springWac = WebApplicationContextUtils.getWebApplicationContext( wac.getServletContext(), FrameworkServlet.SERVLET_CONTEXT_PREFIX + "appServlet"); String beanName = ClassUtils.getShortNameAsProperty(endpointClass); if (springWac.containsBean(beanName)) { T endpoint = springWac.getBean(beanName, endpointClass); if (logger.isTraceEnabled()) { logger.trace("Using @ServerEndpoint singleton " + endpoint); } return endpoint; } Component annot = AnnotationUtils.findAnnotation(endpointClass, Component.class); if ((annot != null) && springWac.containsBean(annot.value())) { T endpoint = springWac.getBean(annot.value(), endpointClass); if (logger.isTraceEnabled()) { logger.trace("Using @ServerEndpoint singleton " + endpoint); } return endpoint; } beanName = getBeanNameByType(springWac, endpointClass); if (beanName != null) { return (T) springWac.getBean(beanName); } if (logger.isTraceEnabled()) { logger.trace("Creating new @ServerEndpoint instance of type " + endpointClass); } return springWac.getAutowireCapableBeanFactory().createBean(endpointClass); }
@Scheduled(fixedRate = 20000) public void httpConnectionRelease() { PoolingHttpClientConnectionManager connectionManager = (PoolingHttpClientConnectionManager) ContextLoader.getCurrentWebApplicationContext().getBean("httpPoolManager"); if (logger.isInfoEnabled()) { logger.info( "release start connect count:=" + connectionManager.getTotalStats().getAvailable()); } // Close expired connections connectionManager.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than readTimeout*2 MILLISECONDS connectionManager.closeIdleConnections(60000, TimeUnit.MILLISECONDS); if (logger.isInfoEnabled()) { logger.info("release end connect count:=" + connectionManager.getTotalStats().getAvailable()); logger.info("release end connect count:=" + connectionManager.getTotalStats().getMax()); } }
public void init() { initialized = true; AbstractApplicationContext applicationContext = (AbstractApplicationContext) ContextLoader.getCurrentWebApplicationContext(); if (applicationContext == null) { LOG.warn( "No Web Spring-ApplicationContext found, try to resolve via application context provider."); applicationContext = (AbstractApplicationContext) ApplicationContextProvider.getApplicationContext(); } if (null != applicationContext) { LOG.info("ApplicationContext found."); applicationContextFound = true; beanFactory = applicationContext.getBeanFactory(); } else { LOG.warn("No Spring-ApplicationContext found."); } }
// Notification that the web application is ready to process requests @Override public void contextInitialized(ServletContextEvent sce) { if (null != servletContext) { return; } System.setProperty("red5.deployment.type", "war"); servletContext = sce.getServletContext(); String prefix = servletContext.getRealPath("/"); long time = System.currentTimeMillis(); logger.info("RED5 Server (http://www.osflash.org/red5)"); logger.info("WAR loader"); logger.debug("Path: " + prefix); try { // instance the context loader contextLoader = createContextLoader(); applicationContext = (ConfigurableWebApplicationContext) contextLoader.initWebApplicationContext(servletContext); logger.debug("Root context path: " + applicationContext.getServletContext().getContextPath()); ConfigurableBeanFactory factory = applicationContext.getBeanFactory(); // register default factory.registerSingleton("default.context", applicationContext); // get the main factory parentFactory = (DefaultListableBeanFactory) factory.getParentBeanFactory(); } catch (Throwable t) { logger.error("", t); } long startupIn = System.currentTimeMillis() - time; logger.info("Startup done in: " + startupIn + " ms"); }
private PersonService getPersonService() { // Get Spring Bean Factory ApplicationContext appContext = ContextLoader.getCurrentWebApplicationContext(); return appContext.getBean(this.personServiceBeanId, PersonService.class); }
/** * @Author:LZY @Date:2015/2/8 @Function:获取SpringBean根据类名 @2015/2/28 * * @desc Fixed a Exception 服务启动的时候可能还没做完context,就被调用 * @throws ClassNotFoundException * @throws BeansException */ public static Object getBean(String beanName) throws BeansException, ClassNotFoundException { ApplicationContext ac = ContextLoader.getCurrentWebApplicationContext(); return ac == null ? null : ac.getBean(Class.forName(beanName)); }
/** * @Author:LZY @Date:2015/2/8 @Function:获取SpringBean根据Class @2015/2/28 Fixed a Exception * 服务启动的时候可能还没做完context,就被调用 * * @return */ public static <T> T getBean(Class<T> clasz) { ApplicationContext ac = ContextLoader.getCurrentWebApplicationContext(); return ac == null ? null : ac.getBean(clasz); }
public ICryptoUtil getCryptoUtil() { if (cryptoUtil != null) { return cryptoUtil; } return ContextLoader.getCurrentWebApplicationContext().getBean(ICryptoUtil.class); }
/** This class controls the way jobs are submited */ public enum MergerManager { INSTANCE; @Value("${max.running.time}") private long maxRunning; @Value("${max.queueing.time}") private long maxQueueing; // Max Number of jobs at a given time @Value("${max.jobs}") private int maxJobs = 200; // App Context private WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); private JobLauncher jobLauncher = context.getBean(JobLauncher.class); private Job job = context.getBean(Job.class); // Map that contains the executions private Map<String, JobExecution> executions = new ConcurrentHashMap<String, JobExecution>(); /** * Starts a new job * * @param params * @return */ public String submitJob(JobParametersBuilder params) { if (maxJobs - getActiveExecutionsCount() > 0) { try { String id = UUID.randomUUID().toString(); params.addString("id", id); JobExecution ex = jobLauncher.run(job, params.toJobParameters()); executions.put(id, ex); return id; } catch (JobExecutionAlreadyRunningException e) { e.printStackTrace(); } catch (JobRestartException e) { e.printStackTrace(); } catch (JobInstanceAlreadyCompleteException e) { e.printStackTrace(); } catch (JobParametersInvalidException e) { e.printStackTrace(); } } return "Server bussy, please try agan later"; } /** * Returns the status of a given job * * @param id * @return */ public String getStatus(String id) { JobExecution ex = executions.get(id); if (ex != null) { BatchStatus st = ex.getStatus(); String status = ""; if (BatchStatus.FAILED == st) { status = "Clustering job aborted."; // Please make sure the given parameters comply with the // specification."; List<Throwable> lst = ex.getAllFailureExceptions(); for (Throwable e : lst) { e.printStackTrace(); status += "\n " + e.getMessage(); } } else if (ex.getExecutionContext().containsKey("status")) { status = ex.getExecutionContext().getString("status"); } return st.name() + " - " + status; } if (FileManager.INSTANCE.getTaskFile(id) != null) return "COMPLETED - clustered job '" + id + "'"; return "Unknown job '" + id + "'"; } /** Job clearance */ public void checkExecutions() { for (String key : executions.keySet()) { JobExecution ex = executions.get(key); // if something has been running for more than one day, then is killed if (ex.getStatus() == BatchStatus.STARTED) { long milis = (new Date().getTime() - ex.getStartTime().getTime()); if (milis > maxRunning) { ex.stop(); } // if a job is complete and has been around form more than a week, then is stoped and // removed from the // execution list } else { long milis = (new Date().getTime() - ex.getStartTime().getTime()); if (milis > maxQueueing) { ex.stop(); executions.remove(key); // if completed remove file as well if (ex.getStatus() == BatchStatus.COMPLETED) { FileManager.INSTANCE.deleteFile(key); } } } } } /** * Returns the number of executions currently running * * @return */ private int getActiveExecutionsCount() { int count = 0; for (String key : executions.keySet()) { JobExecution ex = executions.get(key); if (ex.isRunning()) { count++; } } return count; } }
private UserService getTamLdapUserService() { // Get Spring Bean Factory ApplicationContext appContext = ContextLoader.getCurrentWebApplicationContext(); return appContext.getBean(this.tamLdapUserServiceBeanId, UserService.class); }
/** * 获取Spring WebApplicationContext * * @return */ public static WebApplicationContext getWebApplicationContext() { return ContextLoader.getCurrentWebApplicationContext(); }
/** * 得到WEBAPP上下文路径 * * @return */ public static String getContextPath() { return ContextLoader.getCurrentWebApplicationContext().getServletContext().getContextPath(); }