@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);
  }
  /**
   * Load the bean definitions with the given XmlBeanDefinitionReader.
   *
   * <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory} method;
   * hence this method is just supposed to load and/or register bean definitions.
   *
   * @param reader the XmlBeanDefinitionReader to use
   * @throws BeansException in case of bean registration errors
   * @throws IOException if the required XML document isn't found
   * @see #refreshBeanFactory
   * @see #getConfigLocations
   * @see #getResources
   * @see #getResourcePatternResolver
   */
  protected void loadBeanDefinitions(XmlBeanDefinitionReader reader)
      throws BeansException, IOException {

    // 直接resource加载,通过子类实现setResource的方法设置
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
      reader.loadBeanDefinitions(configResources);
    }

    // filesystem 在初始化的时候,setLocation为文件的路径名,通过继承AbstractRefreshableConfigApplicationContext#set方法
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
      reader.loadBeanDefinitions(configLocations);
    }
  }
  @Test
  public void parseInternal_withMinimalConfig_shouldCreateDefaultTemplate() throws Exception {
    // Arrange
    DefaultListableBeanFactory registry = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry);

    // Act
    reader.loadBeanDefinitions(
        new ClassPathResource(getClass().getSimpleName() + "-minimal.xml", getClass()));

    // Assert
    NotificationMessagingTemplate notificationMessagingTemplate =
        registry.getBean(NotificationMessagingTemplate.class);
    assertSame(
        registry.getBean(AmazonSNSClient.class),
        ReflectionTestUtils.getField(notificationMessagingTemplate, "amazonSns"));

    Object cachingDestinationResolverProxy =
        ReflectionTestUtils.getField(notificationMessagingTemplate, "destinationResolver");
    Object targetDestinationResolver =
        ReflectionTestUtils.getField(cachingDestinationResolverProxy, "targetDestinationResolver");
    assertEquals(
        registry.getBean(GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME),
        ReflectionTestUtils.getField(targetDestinationResolver, "resourceIdResolver"));

    assertTrue(
        StringMessageConverter.class.isInstance(
            notificationMessagingTemplate.getMessageConverter()));
    assertEquals(
        String.class,
        ReflectionTestUtils.getField(
            notificationMessagingTemplate.getMessageConverter(), "serializedPayloadClass"));
  }
 private void loadBeanDefinitions(String fileName) {
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.appContext);
   ClassPathResource resource =
       new ClassPathResource(fileName, MessageBrokerBeanDefinitionParserTests.class);
   reader.loadBeanDefinitions(resource);
   this.appContext.refresh();
 }
  @Before
  public void setUp() throws Exception {
    // reset counter just to be sure
    DummyListener.BIND_CALLS = 0;
    DummyListener.UNBIND_CALLS = 0;

    DummyListenerServiceSignature.BIND_CALLS = 0;
    DummyListenerServiceSignature.UNBIND_CALLS = 0;

    DummyListenerServiceSignature2.BIND_CALLS = 0;
    DummyListenerServiceSignature2.UNBIND_CALLS = 0;

    BundleContext bundleContext =
        new MockBundleContext() {
          // service reference already registered
          public ServiceReference[] getServiceReferences(String clazz, String filter)
              throws InvalidSyntaxException {
            return new ServiceReference[] {
              new MockServiceReference(new String[] {Cloneable.class.getName()})
            };
          }
        };

    appContext = new GenericApplicationContext();
    appContext
        .getBeanFactory()
        .addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
    appContext.setClassLoader(getClass().getClassLoader());

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    // reader.setEventListener(this.listener);
    reader.loadBeanDefinitions(
        new ClassPathResource("osgiReferenceNamespaceHandlerTests.xml", getClass()));
    appContext.refresh();
  }
예제 #6
0
  @Test
  public void testFactoryMethodsSingletonOnTargetClass() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    TestBean tb = (TestBean) xbf.getBean("defaultTestBean");
    assertEquals("defaultInstance", tb.getName());
    assertEquals(1, tb.getAge());

    FactoryMethods fm = (FactoryMethods) xbf.getBean("default");
    assertEquals(0, fm.getNum());
    assertEquals("default", fm.getName());
    assertEquals("defaultInstance", fm.getTestBean().getName());
    assertEquals("setterString", fm.getStringValue());

    fm = (FactoryMethods) xbf.getBean("testBeanOnly");
    assertEquals(0, fm.getNum());
    assertEquals("default", fm.getName());
    // This comes from the test bean
    assertEquals("Juergen", fm.getTestBean().getName());

    fm = (FactoryMethods) xbf.getBean("full");
    assertEquals(27, fm.getNum());
    assertEquals("gotcha", fm.getName());
    assertEquals("Juergen", fm.getTestBean().getName());

    FactoryMethods fm2 = (FactoryMethods) xbf.getBean("full");
    assertSame(fm, fm2);

    xbf.destroySingletons();
    assertTrue(tb.wasDestroyed());
  }
 private void loadBeanDefinitions(String fileName) {
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
   ClassPathResource resource =
       new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
   reader.loadBeanDefinitions(resource);
   appContext.refresh();
 }
예제 #8
0
 /**
  * Overriden superclass method. Creates a single application context containing all the service
  * beans
  *
  * @throws PlatformException
  */
 protected void loadServiceContexts() throws PlatformException {
   // locate and load the individual service bean XML files using the common batch beans context as
   // parent
   File[] serviceBeansFiles =
       FileLocator.findFiles(ServiceFrameworkConstants.SPRING_SERVICES_CONFIG);
   List<String> fileNamesList = new LinkedList<String>();
   for (File serviceBeansFile : serviceBeansFiles) {
     // dont load the individual service context, just register an empty context for display
     // purposes
     GenericApplicationContext nonRefreshedServiceContext = new GenericApplicationContext();
     XmlBeanDefinitionReader beanDefReader =
         new XmlBeanDefinitionReader(nonRefreshedServiceContext);
     // add the "file:" prefix to file names to explicitly state that it is on the file system and
     // not a classpath resource
     beanDefReader.loadBeanDefinitions(
         ServiceConfigInfo.FILE_PREFIX + serviceBeansFile.getAbsolutePath());
     ServiceConfigInfo nonInitedServiceConfigInfo =
         new ServiceConfigInfo(serviceBeansFile, null, nonRefreshedServiceContext);
     super.registerServiceContext(nonInitedServiceConfigInfo);
     // add the "file:" prefix to file names to get around strange behavior of
     // FileSystemXmlApplicationContext that converts absolute path to relative path
     fileNamesList.add(ServiceConfigInfo.FILE_PREFIX + serviceBeansFile.getAbsolutePath());
   }
   this.servicesContext =
       new FileSystemXmlApplicationContext(
           (String[]) fileNamesList.toArray(new String[0]),
           SpringServicesContainer.getCommonServiceBeansContext());
   super.registerServiceContext(
       new ServiceConfigInfo(
           new File(ServiceFrameworkConstants.SPRING_SERVICES_CONFIG),
           null,
           this.servicesContext));
 }
예제 #9
0
  /** Tests where the static factory method is on a different class. */
  @Test
  public void testFactoryMethodsOnExternalClass() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithoutArgs"));
    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithArgs"));
    String[] names = xbf.getBeanNamesForType(TestBean.class);
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs"));
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithArgs"));

    TestBean tb = (TestBean) xbf.getBean("externalFactoryMethodWithoutArgs");
    assertEquals(2, tb.getAge());
    assertEquals("Tristan", tb.getName());
    tb = (TestBean) xbf.getBean("externalFactoryMethodWithArgs");
    assertEquals(33, tb.getAge());
    assertEquals("Rod", tb.getName());

    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithoutArgs"));
    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithArgs"));
    names = xbf.getBeanNamesForType(TestBean.class);
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs"));
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithArgs"));
  }
  /**
   * 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);
    }
  }
예제 #11
0
  private static GenericApplicationContext initAppCtx(com.wavemaker.tools.io.File r) {

    ClassPathResource servicetypes = new ClassPathResource("servicetypes.xml");

    GenericApplicationContext ctx = new GenericApplicationContext();

    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);

    xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);

    xmlReader.loadBeanDefinitions(servicetypes);
    xmlReader.loadBeanDefinitions(new InputSource(r.getContent().asInputStream()));

    ctx.refresh();

    return ctx;
  }
 @Before
 public void setUp() throws Exception {
   beanFactory = new DefaultListableBeanFactory();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
   reader.loadBeanDefinitions(
       new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()));
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
 }
 @Before
 public void setUp() throws Exception {
   this.beanFactory = new DefaultListableBeanFactory();
   this.beanFactory.registerScope("request", new RequestScope());
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
   reader.loadBeanDefinitions(new ClassPathResource("requestScopedProxyTests.xml", getClass()));
   this.beanFactory.preInstantiateSingletons();
 }
예제 #14
0
 /**
  * Load the springified server configuration.
  *
  * @return
  */
 protected ApplicationContext loadServerApplicationContext(File configFile)
     throws SiteWhereException {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
   reader.loadBeanDefinitions(new FileSystemResource(configFile));
   context.refresh();
   return context;
 }
 public void testWithInputSourceAndExplicitValidationMode() {
   SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
   ;
   InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml"));
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry);
   reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_DTD);
   reader.loadBeanDefinitions(resource);
   testBeanDefinitions(registry);
 }
예제 #16
0
  @Test
  public void testPrivateFactoryMethod() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    TestBean tb = (TestBean) xbf.getBean("defaultTestBean.private");
    assertEquals(1, tb.getAge());
  }
  /**
   * Will parse the module xml definition file, looking for "${foo}" placeholders and advertise a
   * {@link ModuleOption} for each of those.
   *
   * <p>Note that this may end up in false positives and does not convey much information.
   *
   * @param classLoaderToUse
   */
  private ModuleOptionsMetadata inferModuleOptionsMetadata(
      ModuleDefinition definition, ClassLoader classLoaderToUse) {
    final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    reader.setResourceLoader(new PathMatchingResourcePatternResolver(classLoaderToUse));
    reader.loadBeanDefinitions(definition.getResource());

    return defaultModuleOptionsMetadataCollector.collect(beanFactory);
  }
 /**
  * Load the bean definitions with the given XmlBeanDefinitionReader.
  *
  * <p>The lifecycle of the bean factory is handled by the refreshBeanFactory method; therefore
  * this method is just supposed to load and/or register bean definitions.
  *
  * <p>Delegates to a ResourcePatternResolver for resolving location patterns into Resource
  * instances.
  *
  * @throws org.springframework.beans.BeansException in case of bean registration errors
  * @throws java.io.IOException if the required XML document isn't found
  * @see #refreshBeanFactory
  * @see #getConfigLocations
  * @see #getResources
  * @see #getResourcePatternResolver
  */
 protected void loadBeanDefinitions(XmlBeanDefinitionReader reader)
     throws BeansException, IOException {
   String[] configLocations = getConfigLocations();
   if (configLocations != null) {
     for (int i = 0; i < configLocations.length; i++) {
       reader.loadBeanDefinitions(configLocations[i]);
     }
   }
 }
예제 #19
0
  @Test
  public void testFactoryMethodForJavaMailSession() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    MailSession session = (MailSession) xbf.getBean("javaMailSession");
    assertEquals("someuser", session.getProperty("mail.smtp.user"));
    assertEquals("somepw", session.getProperty("mail.smtp.password"));
  }
 @Test
 public void testLazyInitFalse() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultLazyInitFalseTests.xml");
   assertFalse(
       "lazy-init should be false", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit());
   assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT);
   context.refresh();
   assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT);
 }
 @Test
 public void testAutowireNo() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireNoTests.xml");
   context.refresh();
   DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
   assertNull("no dependencies should have been autowired", bean.getConstructorDependency());
   assertNull("no dependencies should have been autowired", bean.getPropertyDependency1());
   assertNull("no dependencies should have been autowired", bean.getPropertyDependency2());
 }
예제 #22
0
  @Test
  public void testFactoryMethodsWithAutowire() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    FactoryMethods fm = (FactoryMethods) xbf.getBean("fullWithAutowire");
    assertEquals(27, fm.getNum());
    assertEquals("gotchaAutowired", fm.getName());
    assertEquals("Juergen", fm.getTestBean().getName());
  }
 @Test
 public void testDefaultInitAndDestroyMethodsDefined() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultInitAndDestroyMethodsTests.xml");
   context.refresh();
   DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
   assertTrue("bean should have been initialized", bean.isInitialized());
   context.close();
   assertTrue("bean should have been destroyed", bean.isDestroyed());
 }
 @Test
 public void testDependencyCheckAll() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultDependencyCheckAllTests.xml");
   try {
     context.refresh();
     fail("expected exception due to dependency check");
   } catch (UnsatisfiedDependencyException e) {
     // expected
   }
 }
 @Test
 public void testAutowireByType() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireByTypeTests.xml");
   try {
     context.refresh();
     fail("expected exception due to multiple matches for byType autowiring");
   } catch (UnsatisfiedDependencyException e) {
     // expected
   }
 }
예제 #26
0
 @Test
 public void testFactoryMethodNoMatchingStaticMethod() {
   DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
   reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
   try {
     xbf.getBean("noMatchPrototype");
     fail("No static method matched");
   } catch (BeanCreationException ex) {
     // Ok
   }
 }
예제 #27
0
 @Test
 public void testCannotSpecifyFactoryMethodArgumentsOnSingleton() {
   DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
   reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
   try {
     xbf.getBean("testBeanOnly", new TestBean());
     fail("Shouldn't allow args to be passed to a singleton");
   } catch (BeanDefinitionStoreException ex) {
     // OK
   }
 }
예제 #28
0
  @Test
  public void testFactoryMethodsWithInvalidDestroyMethod() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    try {
      xbf.getBean("defaultTestBeanWithInvalidDestroyMethod");
      fail("Should have thrown BeanCreationException");
    } catch (BeanCreationException ex) {
      // expected
    }
  }
  /**
   * called before @BeforeTransaction methods
   *
   * @see
   *     org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext)
   */
  @Override
  public void prepareTestInstance(TestContext testContext) throws Exception {
    StartModule startModuleAnnotation = testContext.getTestClass().getAnnotation(StartModule.class);

    // if the developer listed some modules with the @StartModule annotation on the class
    if (startModuleAnnotation != null) {

      if (!lastClassRun.equals(testContext.getTestClass().getSimpleName())) {
        // mark this with our class so that the services are only restarted once
        lastClassRun = testContext.getTestClass().getSimpleName();

        if (!Context.isSessionOpen()) Context.openSession();

        // load the omods that the dev defined for this class
        String modulesToLoad = StringUtils.join(startModuleAnnotation.value(), " ");

        Properties props = BaseContextSensitiveTest.runtimeProperties;
        props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD, modulesToLoad);
        try {
          ModuleUtil.startup(props);
        } catch (Exception e) {
          System.out.println("Error while starting modules: ");
          e.printStackTrace(System.out);
          throw e;
        }
        Assert.assertTrue(
            "Some of the modules did not start successfully for "
                + testContext.getTestClass().getSimpleName()
                + ". Only "
                + ModuleFactory.getStartedModules().size()
                + " modules started instead of "
                + startModuleAnnotation.value().length,
            startModuleAnnotation.value().length <= ModuleFactory.getStartedModules().size());

        /*
         * Refresh spring so the Services are recreated (aka serializer gets put into the SerializationService)
         * To do this, wrap the applicationContext from the testContext into a GenericApplicationContext, allowing
         * loading beans from moduleApplicationContext into it and then calling ctx.refresh()
         * This approach ensures that the application context remains consistent
         */
        GenericApplicationContext ctx =
            new GenericApplicationContext(testContext.getApplicationContext());
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("moduleApplicationContext.xml"));
        ctx.refresh();

        // session is closed by the test framework
        // Context.closeSession();
      }
    }
  }
예제 #30
0
  /**
   * 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);
    }
  }