/** * Load the application context using a single classloader * * @param ac The spring application context * @param config a list of configurations represented as List of resources * @param loader the classloader to use */ public void loadComponent( ConfigurableApplicationContext ac, List<Resource> config, ClassLoader loader) { ClassLoader current = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); try { // make a reader XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) ac.getBeanFactory()); // In Spring 2, classes aren't loaded during bean parsing unless // this // classloader property is set. reader.setBeanClassLoader(loader); reader.loadBeanDefinitions(config.toArray(new Resource[0])); } catch (Throwable t) { log.warn("loadComponentPackage: exception loading: " + config + " : " + t, t); } finally { // restore the context loader Thread.currentThread().setContextClassLoader(current); } }
@BeforeClass public static void prepare() throws Exception // NOPMD { Registry.activateStandaloneMode(); Utilities.setJUnitTenant(); LOG.debug("Preparing..."); final ApplicationContext appCtx = Registry.getGlobalApplicationContext(); assertTrue( "Application context of type " + appCtx.getClass() + " is not a subclass of " + ConfigurableApplicationContext.class, appCtx instanceof ConfigurableApplicationContext); final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) appCtx; final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); assertTrue( "Bean Factory of type " + beanFactory.getClass() + " is not of type " + BeanDefinitionRegistry.class, beanFactory instanceof BeanDefinitionRegistry); final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory); xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class); xmlReader.loadBeanDefinitions( new ClassPathResource( "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-test.xml")); xmlReader.loadBeanDefinitions( new ClassPathResource( "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-test-fraudcheck.xml")); xmlReader.loadBeanDefinitions( new ClassPathResource( "/merchandisefulfilmentprocess/test/process/order-process-spring.xml")); modelService = (ModelService) getBean("modelService"); processService = (DefaultBusinessProcessService) getBean("businessProcessService"); definitonFactory = processService.getProcessDefinitionFactory(); LOG.warn("Prepare Process Definition factory..."); definitonFactory.add( "classpath:/merchandisefulfilmentprocess/test/process/payment-process.xml"); // setup command factory to mock final DefaultCommandFactoryRegistryImpl commandFactoryReg = appCtx.getBean(DefaultCommandFactoryRegistryImpl.class); commandFactoryReg.setCommandFactoryList( Arrays.asList((CommandFactory) appCtx.getBean("mockupCommandFactory"))); taskServiceStub = appCtx.getBean(TaskServiceStub.class); productService = appCtx.getBean("defaultProductService", DefaultProductService.class); cartService = appCtx.getBean("defaultCartService", DefaultCartService.class); userService = appCtx.getBean("defaultUserService", DefaultUserService.class); }
@Override public void customizeContext( ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { if (!this.filterClasses.isEmpty()) { context .getBeanFactory() .registerSingleton(EXCLUDE_FILTER_BEAN_NAME, createDelegatingTypeExcludeFilter()); } }
@After public void tearDown() { final ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) Registry.getApplicationContext(); final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ctx.getBeanFactory(); beanFactory.removeBeanDefinition(PROCEDURAL_ACTION_ID); beanFactory.removeBeanDefinition(JOURNAL_ID); processDefinitionsCache.clear(); }
/** * Load one component package into the AC * * @param packageRoot The file path to the component package * @param ac The ApplicationContext to load into */ protected void loadComponentPackage(File dir, ConfigurableApplicationContext ac) { // setup the classloader onto the thread ClassLoader current = Thread.currentThread().getContextClassLoader(); ClassLoader loader = newPackageClassLoader(dir); M_log.info("loadComponentPackage: " + dir); Thread.currentThread().setContextClassLoader(loader); File xml = null; try { // load this xml file File webinf = new File(dir, "WEB-INF"); xml = new File(webinf, "components.xml"); // make a reader XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) ac.getBeanFactory()); // In Spring 2, classes aren't loaded during bean parsing unless this // classloader property is set. reader.setBeanClassLoader(loader); List<Resource> beanDefList = new ArrayList<Resource>(); beanDefList.add(new FileSystemResource(xml.getCanonicalPath())); // Load the demo components, if necessary File demoXml = new File(webinf, "components-demo.xml"); if ("true".equalsIgnoreCase(System.getProperty("sakai.demo"))) { if (M_log.isDebugEnabled()) M_log.debug("Attempting to load demo components"); if (demoXml.exists()) { if (M_log.isInfoEnabled()) M_log.info("Loading demo components from " + dir); beanDefList.add(new FileSystemResource(demoXml.getCanonicalPath())); } } else { if (demoXml.exists()) { // Only log that we're skipping the demo components if they exist if (M_log.isInfoEnabled()) M_log.info("Skipping demo components from " + dir); } } reader.loadBeanDefinitions(beanDefList.toArray(new Resource[0])); } catch (Exception e) { M_log.warn("loadComponentPackage: exception loading: " + xml + " : " + e, e); } finally { // restore the context loader Thread.currentThread().setContextClassLoader(current); } }
/** * 动态注册bean * * @author JohnGao */ public <T> void register(String beanName, Class<T> classType, Map<String, String> values) { ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) aContext; DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory(); if (defaultListableBeanFactory.isBeanNameInUse(beanName)) { defaultListableBeanFactory.removeBeanDefinition(beanName); logger.info("beanName-->" + beanName + "成功删除"); } BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(classType); for (String key : values.keySet()) beanDefinitionBuilder.addPropertyValue(key, values.get(key)); defaultListableBeanFactory.registerBeanDefinition( beanName, beanDefinitionBuilder.getRawBeanDefinition()); logger.info("beanName-->" + beanName + "成功注册"); }
@AfterClass public static void removeProcessDefinitions() { LOG.debug("cleanup..."); final ApplicationContext appCtx = Registry.getGlobalApplicationContext(); assertTrue( "Application context of type " + appCtx.getClass() + " is not a subclass of " + ConfigurableApplicationContext.class, appCtx instanceof ConfigurableApplicationContext); final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) appCtx; final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); assertTrue( "Bean Factory of type " + beanFactory.getClass() + " is not of type " + BeanDefinitionRegistry.class, beanFactory instanceof BeanDefinitionRegistry); final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory); xmlReader.loadBeanDefinitions( new ClassPathResource( "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-testcleanup.xml")); // cleanup command factory final Map<String, CommandFactory> commandFactoryList = applicationContext.getBeansOfType(CommandFactory.class); commandFactoryList.remove("mockupCommandFactory"); final DefaultCommandFactoryRegistryImpl commandFactoryReg = appCtx.getBean(DefaultCommandFactoryRegistryImpl.class); commandFactoryReg.setCommandFactoryList(commandFactoryList.values()); // if (definitonFactory != null) // { // TODO this test seems to let processes run after method completion - therefore we cannot // remove definitions !!! // definitonFactory.remove("testPlaceorder"); // definitonFactory.remove("testConsignmentFulfilmentSubprocess"); // } processService.setTaskService(appCtx.getBean(DefaultTaskService.class)); definitonFactory = null; processService = null; }
@Before public void setup() { recipientListRouter = mock(CustomRecipientListRouter.class); configurableApplicationContext = mock(ConfigurableApplicationContext.class); beanFactory = mock(ConfigurableListableBeanFactory.class); when(configurableApplicationContext.getBeanFactory()).thenReturn(beanFactory); TaskScheduler taskScheduler = mock(TaskScheduler.class); Executor executor = mock(Executor.class); monitorRegistry = new MonitorRegistry(); monitorRegistry.setRecipientListRouter(recipientListRouter); monitorRegistry.setConfigurableApplicationContext(configurableApplicationContext); monitorRegistry.setExecutor(executor); monitorRegistry.setTaskScheduler(taskScheduler); }
/** * Fine the bean definition from a given context or from any of the parent contexts. * * @param beanName the bean name. * @return the bean definition. * @throws NoSuchBeanDefinitionException if the bean definition could not be found. */ private BeanDefinition findBeanDefinition(String beanName) { ConfigurableApplicationContext current = springContext; BeanDefinition beanDef = null; do { try { return current.getBeanFactory().getBeanDefinition(beanName); } catch (NoSuchBeanDefinitionException e) { final ApplicationContext parent = current.getParent(); if (parent != null && parent instanceof ConfigurableApplicationContext) { current = (ConfigurableApplicationContext) parent; } else { throw e; } } } while (beanDef == null && current != null); return beanDef; }
@Before public void setUp() { final ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) Registry.getApplicationContext(); final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ctx.getBeanFactory(); beanFactory.registerBeanDefinition( JOURNAL_ID, BeanDefinitionBuilder.rootBeanDefinition(ActionsJournal.class) .setScope("singleton") .getBeanDefinition()); beanFactory.registerBeanDefinition( PROCEDURAL_ACTION_ID, BeanDefinitionBuilder.rootBeanDefinition(RecordableProceduralAction.class) .setScope("singleton") .addConstructorArgValue(PROCEDURAL_ACTION_ID) .addConstructorArgReference(JOURNAL_ID) .getBeanDefinition()); }
/** * Processes a new {@link Trigger} being added. Currently, it supports adding {@link * CronTrigger}s. The {@link Trigger} is added to the common {@link * ConfigurableApplicationContext}. */ @Override public void preProcessModule(Module module) { if (!TRIGGER.equals(module.getType())) { return; } Assert.notNull( commonApplicationContext, "The 'commonApplicationContext' property must not be null."); Map<String, Trigger> triggers = new HashMap<String, Trigger>(); if (module.getProperties().containsKey(TriggerType.cron.name())) { Trigger trigger = new CronTrigger(module.getProperties().getProperty(TriggerType.cron.name())); triggers.put(TriggerType.cron.name(), trigger); } if (module.getProperties().containsKey(TriggerType.fixedDelay.name())) { Trigger trigger = new PeriodicTrigger( Long.parseLong(module.getProperties().getProperty(TriggerType.fixedDelay.name()))); triggers.put(TriggerType.fixedDelay.name(), trigger); } if (module.getProperties().containsKey(TriggerType.fixedRate.name())) { PeriodicTrigger trigger = new PeriodicTrigger( Long.parseLong(module.getProperties().getProperty(TriggerType.fixedRate.name()))); trigger.setFixedRate(true); triggers.put(TriggerType.fixedRate.name(), trigger); } if (triggers.size() == 0) { throw new ResourceDefinitionException( "No valid trigger property. Expected one of: cron, fixedDelay or fixedRate"); } else if (triggers.size() > 1) { throw new ResourceDefinitionException( "Only one trigger property allowed, but received: " + StringUtils.collectionToCommaDelimitedString(triggers.keySet())); } commonApplicationContext .getBeanFactory() .registerSingleton(makeTriggerBeanName(module), triggers.values().iterator().next()); configureProperties(module); }
@AfterClass public static void removeProcessDefinitions() { LOG.debug("cleanup..."); final ApplicationContext appCtx = Registry.getApplicationContext(); assertTrue( "Application context of type " + appCtx.getClass() + " is not a subclass of " + ConfigurableApplicationContext.class, appCtx instanceof ConfigurableApplicationContext); final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) appCtx; final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); assertTrue( "Bean Factory of type " + beanFactory.getClass() + " is not of type " + BeanDefinitionRegistry.class, beanFactory instanceof BeanDefinitionRegistry); final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory); xmlReader.loadBeanDefinitions( new ClassPathResource( "/octannerfulfilmentprocess/test/octannerfulfilmentprocess-spring-testcleanup.xml")); // cleanup command factory final Map<String, CommandFactory> commandFactoryList = applicationContext.getBeansOfType(CommandFactory.class); commandFactoryList.remove("mockupCommandFactory"); final DefaultCommandFactoryRegistryImpl commandFactoryReg = appCtx.getBean(DefaultCommandFactoryRegistryImpl.class); commandFactoryReg.setCommandFactoryList(commandFactoryList.values()); processService.setTaskService(appCtx.getBean(DefaultTaskService.class)); definitonFactory = null; processService = null; }
@Override public void removeModule(Module module) { String beanName = makeTriggerBeanName(module); ConfigurableListableBeanFactory beanFactory = commonApplicationContext.getBeanFactory(); ((DefaultSingletonBeanRegistry) beanFactory).destroySingleton(beanName); }
@BeforeClass public static void prepare() throws Exception // NOPMD { Registry.activateStandaloneMode(); Utilities.setJUnitTenant(); LOG.debug("Preparing..."); final ApplicationContext appCtx = Registry.getApplicationContext(); // final ConfigurationService configurationService = (ConfigurationService) // appCtx.getBean("configurationService"); // configurationService.getConfiguration().setProperty("processengine.event.lockProcess", // "true"); assertTrue( "Application context of type " + appCtx.getClass() + " is not a subclass of " + ConfigurableApplicationContext.class, appCtx instanceof ConfigurableApplicationContext); final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) appCtx; final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); assertTrue( "Bean Factory of type " + beanFactory.getClass() + " is not of type " + BeanDefinitionRegistry.class, beanFactory instanceof BeanDefinitionRegistry); final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory); xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class); xmlReader.loadBeanDefinitions( new ClassPathResource( "/octannerfulfilmentprocess/test/octannerfulfilmentprocess-spring-test.xml")); xmlReader.loadBeanDefinitions( new ClassPathResource("/octannerfulfilmentprocess/test/process/order-process-spring.xml")); xmlReader.loadBeanDefinitions( new ClassPathResource( "/octannerfulfilmentprocess/test/process/consignment-process-spring.xml")); modelService = (ModelService) getBean("modelService"); processService = (DefaultBusinessProcessService) getBean("businessProcessService"); definitonFactory = processService.getProcessDefinitionFactory(); LOG.warn("Prepare Process Definition factory..."); definitonFactory.add("classpath:/octannerfulfilmentprocess/test/process/order-process.xml"); definitonFactory.add( "classpath:/octannerfulfilmentprocess/test/process/consignment-process.xml"); LOG.warn( "loaded 'order-process-test':" + definitonFactory.getProcessDefinition("order-process-test") + " in factory " + definitonFactory); // setup command factory to mock taskServiceStub = appCtx.getBean(TaskServiceStub.class); processService.setTaskService(taskServiceStub); final DefaultCommandFactoryRegistryImpl commandFactoryReg = appCtx.getBean(DefaultCommandFactoryRegistryImpl.class); commandFactoryReg.setCommandFactoryList( Arrays.asList((CommandFactory) appCtx.getBean("mockupCommandFactory"))); }
/*初始化方法*/ public void init() { beanDefinitionReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) applicationContext.getBeanFactory()); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(applicationContext)); }
/** Create a new ApplicationContextAwareProcessor for the given context. */ public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) { this.applicationContext = applicationContext; this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory()); }