@Test
  public void testTwoContextDifferentClass() {
    GenericApplicationContext context = new GenericApplicationContext();
    context.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class));
    context.refresh();
    MessageHeaders headers = new MessageHeaders(null);
    assertEquals(1, headers.getId().getMostSignificantBits());
    assertEquals(2, headers.getId().getLeastSignificantBits());

    GenericApplicationContext context2 = new GenericApplicationContext();
    context2.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context2.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator2.class));
    try {
      context2.refresh();
      fail("Expected exception");
    } catch (BeanDefinitionStoreException e) {
      assertEquals(
          "'MessageHeaders.idGenerator' has already been set and can not be set again",
          e.getMessage());
    }

    context.close();
    context2.close();
  }
  @Test
  public void testTwoContextsSameClass() throws Exception {
    GenericApplicationContext context = new GenericApplicationContext();
    context.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class));
    context.refresh();
    MessageHeaders headers = new MessageHeaders(null);
    assertEquals(1, headers.getId().getMostSignificantBits());
    assertEquals(2, headers.getId().getLeastSignificantBits());

    GenericApplicationContext context2 = new GenericApplicationContext();
    context2.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context2.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class));
    context2.refresh();

    context.close();
    context2.close();

    headers = new MessageHeaders(null);
    assertNotEquals(1, headers.getId().getMostSignificantBits());
    assertNotEquals(2, headers.getId().getLeastSignificantBits());

    assertNull(TestUtils.getPropertyValue(headers, "idGenerator"));
  }
 @Test(expected = ChannelResolutionException.class)
 public void lookupNonRegisteredChannel() {
   GenericApplicationContext context = new GenericApplicationContext();
   context.refresh();
   BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(context);
   resolver.resolveChannelName("noSuchChannel");
 }
  @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();
  }
 @Test
 public void prototypeCreationIsFastEnough() {
   if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) {
     // Skip this test: Trace logging blows the time limit.
     return;
   }
   GenericApplicationContext ac = new GenericApplicationContext();
   RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class);
   rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
   rbd.getConstructorArgumentValues().addGenericArgumentValue("#{systemProperties.name}");
   rbd.getPropertyValues().add("country", "#{systemProperties.country}");
   ac.registerBeanDefinition("test", rbd);
   ac.refresh();
   StopWatch sw = new StopWatch();
   sw.start("prototype");
   System.getProperties().put("name", "juergen");
   System.getProperties().put("country", "UK");
   try {
     for (int i = 0; i < 100000; i++) {
       TestBean tb = (TestBean) ac.getBean("test");
       assertEquals("juergen", tb.getName());
       assertEquals("UK", tb.getCountry());
     }
     sw.stop();
   } finally {
     System.getProperties().remove("country");
     System.getProperties().remove("name");
   }
   assertTrue(
       "Prototype creation took too long: " + sw.getTotalTimeMillis(),
       sw.getTotalTimeMillis() < 6000);
 }
  @Test
  public void prototypeCreationReevaluatesExpressions() {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
    RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
    rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    rbd.getPropertyValues().add("country", "#{systemProperties.country}");
    rbd.getPropertyValues().add("country2", new TypedStringValue("#{systemProperties.country}"));
    ac.registerBeanDefinition("test", rbd);
    ac.refresh();

    try {
      System.getProperties().put("name", "juergen1");
      System.getProperties().put("country", "UK1");
      PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
      assertEquals("juergen1", tb.getName());
      assertEquals("UK1", tb.getCountry());
      assertEquals("UK1", tb.getCountry2());

      System.getProperties().put("name", "juergen2");
      System.getProperties().put("country", "UK2");
      tb = (PrototypeTestBean) ac.getBean("test");
      assertEquals("juergen2", tb.getName());
      assertEquals("UK2", tb.getCountry());
      assertEquals("UK2", tb.getCountry2());
    } finally {
      System.getProperties().remove("name");
      System.getProperties().remove("country");
    }
  }
  @SuppressWarnings("resource")
  @Before
  public void setup() throws Exception {
    DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory();
    dlbf.registerSingleton("mvcValidator", testValidator());
    GenericApplicationContext ctx = new GenericApplicationContext(dlbf);
    ctx.refresh();
    this.resolver =
        new PayloadArgumentResolver(
            ctx, new MethodParameterConverter(new ObjectMapper(), new GenericConversionService()));
    this.payloadMethod =
        getClass()
            .getDeclaredMethod(
                "handleMessage",
                String.class,
                String.class,
                String.class,
                String.class,
                String.class,
                String.class,
                String.class,
                Integer.class);

    this.paramAnnotated = getMethodParameter(this.payloadMethod, 0);
    this.paramAnnotatedNotRequired = getMethodParameter(this.payloadMethod, 1);
    this.paramAnnotatedRequired = getMethodParameter(this.payloadMethod, 2);
    this.paramWithSpelExpression = getMethodParameter(this.payloadMethod, 3);
    this.paramValidated = getMethodParameter(this.payloadMethod, 4);
    this.paramValidated.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    this.paramValidatedNotAnnotated = getMethodParameter(this.payloadMethod, 5);
    this.paramNotAnnotated = getMethodParameter(this.payloadMethod, 6);
  }
Пример #8
0
  /**
   * Will load additional settings from the web app config. Creates a map object that contains
   * workflow parameters to be provided as input to the runner
   *
   * @param form form definition of the workflow being run
   * @return a map of the settings
   */
  private static Map<String, String> settingsFromConfig(FormDefinition form) {
    try {
      Map<String, String> settings = new HashMap<String, String>();

      // Get the workspace basedir from application.conf
      String workspace = ConfigFactory.defaultApplication().getString("jython.workspace");

      // Load workflow yaml file to check parameters
      GenericApplicationContext springContext = new GenericApplicationContext();
      YamlBeanDefinitionReader yamlBeanReader = new YamlBeanDefinitionReader(springContext);
      yamlBeanReader.loadBeanDefinitions(loadYamlStream(form.yamlFile), "-");
      springContext.refresh();

      WorkflowConfig workflowConfig = springContext.getBean(WorkflowConfig.class);

      // Create a workspace
      Path path = Paths.get(workspace, "workspace_" + UUID.randomUUID());
      path.toFile().mkdir();

      // If the "workspace" parameter is present in the workflow set it to the path defined in the
      // config
      if (workflowConfig.getParameters().containsKey("workspace")) {
        settings.put("workspace", path.toString());
      }

      return settings;
    } catch (IOException e) {
      throw new RuntimeException("Error creating workspace directory.", e);
    } catch (Exception e) {
      throw new RuntimeException("Error reading yaml file for parameters.", e);
    }
  }
 @Test
 public void
     testAutowiredFieldDoesNotResolveWithMultipleQualifierValuesAndMultipleMatchingCandidates() {
   GenericApplicationContext context = new GenericApplicationContext();
   ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
   cavs1.addGenericArgumentValue(JUERGEN);
   RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
   AutowireCandidateQualifier qualifier =
       new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class);
   qualifier.setAttribute("number", 123);
   person1.addQualifier(qualifier);
   ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
   cavs2.addGenericArgumentValue(MARK);
   RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
   AutowireCandidateQualifier qualifier2 =
       new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class);
   qualifier2.setAttribute("number", 123);
   qualifier2.setAttribute("value", "default");
   person2.addQualifier(qualifier2);
   context.registerBeanDefinition(JUERGEN, person1);
   context.registerBeanDefinition(MARK, person2);
   context.registerBeanDefinition(
       "autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   try {
     context.refresh();
     fail("expected BeanCreationException");
   } catch (BeanCreationException e) {
     assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
     assertEquals("autowired", e.getBeanName());
   }
 }
  @Test
  public void testIncrementing() {
    GenericApplicationContext context = new GenericApplicationContext();
    context.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context.registerBeanDefinition(
        "foo", new RootBeanDefinition(SimpleIncrementingIdGenerator.class));
    context.refresh();
    IdGenerator idGenerator = context.getBean(IdGenerator.class);
    MessageHeaders headers = new MessageHeaders(null);
    assertEquals(0, headers.getId().getMostSignificantBits());
    assertEquals(1, headers.getId().getLeastSignificantBits());
    headers = new MessageHeaders(null);
    assertEquals(0, headers.getId().getMostSignificantBits());
    assertEquals(2, headers.getId().getLeastSignificantBits());
    AtomicLong bottomBits = TestUtils.getPropertyValue(idGenerator, "bottomBits", AtomicLong.class);
    bottomBits.set(0xffffffff);
    headers = new MessageHeaders(null);
    assertEquals(1, headers.getId().getMostSignificantBits());
    assertEquals(0, headers.getId().getLeastSignificantBits());
    headers = new MessageHeaders(null);
    assertEquals(1, headers.getId().getMostSignificantBits());
    assertEquals(1, headers.getId().getLeastSignificantBits());

    context.close();
  }
 @Test
 public void
     testAutowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() {
   GenericApplicationContext context = new GenericApplicationContext();
   ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
   cavs1.addGenericArgumentValue("the real juergen");
   RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
   person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
   ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
   cavs2.addGenericArgumentValue("juergen imposter");
   RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
   person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
   context.registerBeanDefinition("juergen1", person1);
   context.registerBeanDefinition("juergen2", person2);
   context.registerBeanDefinition(
       "autowired",
       new RootBeanDefinition(
           QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   try {
     context.refresh();
     fail("expected BeanCreationException");
   } catch (BeanCreationException e) {
     assertTrue(e instanceof UnsatisfiedDependencyException);
     assertEquals("autowired", e.getBeanName());
   }
 }
  @Test
  public void testXPathRouter() {
    // route to a channel determined by outcome of the xpath expression

    // Build the route
    DirectChannel inputChannel = new DirectChannel();
    inputChannel.setBeanName("input");
    XPathRouter router = new XPathRouter("//subject/text()");
    router.setEvaluateAsString(true);
    inputChannel.subscribe(router);
    QueueChannel testChannel = new QueueChannel();
    GenericApplicationContext context = new GenericApplicationContext();
    context.getBeanFactory().registerSingleton("testChannel", testChannel);

    router.setBeanFactory(context);
    context.refresh();

    // Create message
    Object correlationId = "123-ABC";
    String xmlSource = "<xml><subject>testChannel</subject></xml>";
    Message<String> message =
        MessageBuilder.withPayload(xmlSource).setCorrelationId(correlationId).build();

    // Send and receive message
    inputChannel.send(message);
    Message<?> reply = testChannel.receive(0);
    assertEquals(xmlSource, reply.getPayload());
  }
 /**
  * Create a Spring {@link ConfigurableApplicationContext} for use by this test.
  *
  * <p>The default implementation creates a standard {@link GenericApplicationContext} instance,
  * calls the {@link #prepareApplicationContext} prepareApplicationContext} method and the {@link
  * #customizeBeanFactory customizeBeanFactory} method to allow for customizing the context and its
  * DefaultListableBeanFactory, populates the context from the specified config {@code locations}
  * through the configured {@link #createBeanDefinitionReader(GenericApplicationContext)
  * BeanDefinitionReader}, and finally {@link ConfigurableApplicationContext#refresh() refreshes}
  * the context.
  *
  * @param locations the config locations (as Spring resource locations, e.g. full classpath
  *     locations or any kind of URL)
  * @return the GenericApplicationContext instance
  * @see #loadContext(String...)
  * @see #customizeBeanFactory(DefaultListableBeanFactory)
  * @see #createBeanDefinitionReader(GenericApplicationContext)
  */
 private ConfigurableApplicationContext createApplicationContext(String... locations) {
   GenericApplicationContext context = new GenericApplicationContext();
   new XmlBeanDefinitionReader(context).loadBeanDefinitions(locations);
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   context.refresh();
   return context;
 }
 @Test
 public void testAutowiredFieldResolvesWithMultipleQualifierValuesAndExplicitDefaultValue() {
   GenericApplicationContext context = new GenericApplicationContext();
   ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
   cavs1.addGenericArgumentValue(JUERGEN);
   RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
   AutowireCandidateQualifier qualifier =
       new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class);
   qualifier.setAttribute("number", 456);
   person1.addQualifier(qualifier);
   ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
   cavs2.addGenericArgumentValue(MARK);
   RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
   AutowireCandidateQualifier qualifier2 =
       new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class);
   qualifier2.setAttribute("number", 123);
   qualifier2.setAttribute("value", "default");
   person2.addQualifier(qualifier2);
   context.registerBeanDefinition(JUERGEN, person1);
   context.registerBeanDefinition(MARK, person2);
   context.registerBeanDefinition(
       "autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   context.refresh();
   QualifiedFieldWithMultipleAttributesTestBean bean =
       (QualifiedFieldWithMultipleAttributesTestBean) context.getBean("autowired");
   assertEquals(MARK, bean.getPerson().getName());
 }
 @Test
 public void
     testAutowiredFieldDoesNotResolveCandidateWithDefaultValueAndConflictingValueOnBeanDefinition() {
   GenericApplicationContext context = new GenericApplicationContext();
   ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
   cavs1.addGenericArgumentValue(JUERGEN);
   RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
   // qualifier added, and non-default value specified
   person1.addQualifier(
       new AutowireCandidateQualifier(TestQualifierWithDefaultValue.class, "not the default"));
   ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
   cavs2.addGenericArgumentValue(MARK);
   RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
   context.registerBeanDefinition(JUERGEN, person1);
   context.registerBeanDefinition(MARK, person2);
   context.registerBeanDefinition(
       "autowired", new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class));
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   try {
     context.refresh();
     fail("expected BeanCreationException");
   } catch (BeanCreationException e) {
     assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
     assertEquals("autowired", e.getBeanName());
   }
 }
Пример #16
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;
 }
Пример #17
0
  @BeforeClass
  public void setUp() throws ServletException {
    servlet = new CitrusDispatcherServlet(httpServer);

    GenericApplicationContext applicationContext = new GenericApplicationContext();
    applicationContext.refresh();

    servlet.init(new MockServletConfig("citrus"));
    servlet.initStrategies(applicationContext);
  }
 @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());
 }
 @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 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);
 }
Пример #21
0
  /**
   * @param springCfgPath Spring configuration file path.
   * @return Grid configuration.
   * @throws Exception If failed.
   */
  protected static IgniteConfiguration loadConfiguration(String springCfgPath) throws Exception {
    URL url;

    try {
      url = new URL(springCfgPath);
    } catch (MalformedURLException e) {
      url = IgniteUtils.resolveIgniteUrl(springCfgPath);

      if (url == null)
        throw new IgniteCheckedException(
            "Spring XML configuration path is invalid: "
                + springCfgPath
                + ". Note that this path should be either absolute or a relative local file system path, "
                + "relative to META-INF in classpath or valid URL to IGNITE_HOME.",
            e);
    }

    GenericApplicationContext springCtx;

    try {
      springCtx = new GenericApplicationContext();

      new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));

      springCtx.refresh();
    } catch (BeansException e) {
      throw new Exception(
          "Failed to instantiate Spring XML application context [springUrl="
              + url
              + ", err="
              + e.getMessage()
              + ']',
          e);
    }

    Map<String, IgniteConfiguration> cfgMap;

    try {
      cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
    } catch (BeansException e) {
      throw new Exception(
          "Failed to instantiate bean [type="
              + IgniteConfiguration.class
              + ", err="
              + e.getMessage()
              + ']',
          e);
    }

    if (cfgMap == null || cfgMap.isEmpty())
      throw new Exception("Failed to find ignite configuration in: " + url);

    return cfgMap.values().iterator().next();
  }
 @Test
 public void lookupRegisteredChannel() {
   GenericApplicationContext context = new GenericApplicationContext();
   QueueChannel testChannel = new QueueChannel();
   testChannel.setBeanName("testChannel");
   context.getBeanFactory().registerSingleton("testChannel", testChannel);
   context.refresh();
   BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(context);
   MessageChannel lookedUpChannel = resolver.resolveChannelName("testChannel");
   assertNotNull(testChannel);
   assertSame(testChannel, lookedUpChannel);
 }
 @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
   }
 }
  @Test
  public void testNoBeans() throws Exception {
    GenericApplicationContext context = new GenericApplicationContext();
    context.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context.refresh();

    MessageHeaders headers = new MessageHeaders(null);
    assertNull(TestUtils.getPropertyValue(headers, "idGenerator"));

    context.close();
  }
Пример #26
0
  /**
   * Create a parent context that initializes a {@link
   * org.apache.camel.spi.PackageScanClassResolver} to exclude a set of given classes from being
   * resolved. Typically this is used at test time to exclude certain routes, which might otherwise
   * be just noisy, from being discovered and initialized.
   *
   * <p>To use this filtering mechanism it is necessary to provide the {@link ApplicationContext}
   * returned from here as the parent context to your test context e.g.
   *
   * <pre>
   * protected AbstractXmlApplicationContext createApplicationContext() {
   *     return new ClassPathXmlApplicationContext(new String[] {&quot;test-context.xml&quot;}, getRouteExcludingApplicationContext());
   * }
   * </pre>
   *
   * This will, in turn, call the template methods <code>excludedRoutes</code> and <code>
   * excludedRoute</code> to determine the classes to be excluded from scanning.
   *
   * @return ApplicationContext a parent {@link ApplicationContext} configured to exclude certain
   *     classes from package scanning
   */
  protected ApplicationContext getRouteExcludingApplicationContext() {
    GenericApplicationContext routeExcludingContext = new GenericApplicationContext();
    routeExcludingContext.registerBeanDefinition(
        "excludingResolver", new RootBeanDefinition(ExcludingPackageScanClassResolver.class));
    routeExcludingContext.refresh();

    ExcludingPackageScanClassResolver excludingResolver =
        (ExcludingPackageScanClassResolver) routeExcludingContext.getBean("excludingResolver");
    List<Class<?>> excluded = CastUtils.cast(Arrays.asList(excludeRoutes()));
    excludingResolver.setExcludedClasses(new HashSet<Class<?>>(excluded));

    return routeExcludingContext;
  }
	@Test
	public void testPostConstructAndPreDestroyWithApplicationContextAndPostProcessor() {
		GenericApplicationContext ctx = new GenericApplicationContext();
		ctx.registerBeanDefinition("bpp1", new RootBeanDefinition(InitDestroyBeanPostProcessor.class));
		ctx.registerBeanDefinition("bpp2", new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class));
		ctx.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedInitDestroyBean.class));
		ctx.refresh();

		AnnotatedInitDestroyBean bean = (AnnotatedInitDestroyBean) ctx.getBean("annotatedBean");
		assertTrue(bean.initCalled);
		ctx.close();
		assertTrue(bean.destroyCalled);
	}
  @Test
  public void testJdk() {
    GenericApplicationContext context = new GenericApplicationContext();
    context.registerBeanDefinition(
        "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class));
    context.registerBeanDefinition("foo", new RootBeanDefinition(JdkIdGenerator.class));
    context.refresh();
    MessageHeaders headers = new MessageHeaders(null);
    assertSame(
        context.getBean(IdGenerator.class), TestUtils.getPropertyValue(headers, "idGenerator"));

    context.close();
  }
  /**
   * 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();
      }
    }
  }
  @Before
  public void setup() {

    BeanDefinitionBuilder builder =
        BeanDefinitionBuilder.rootBeanDefinition(DummyRepositoryFactoryBean.class);
    builder.addPropertyValue("repositoryInterface", EntityRepository.class);

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    factory.registerBeanDefinition("provider", builder.getBeanDefinition());

    context = new GenericApplicationContext(factory);
    context.refresh();
    registrar = new DomainClassPropertyEditorRegistrar();
  }