@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();
  }
コード例 #2
0
  public void testFilterExactAttribute() {

    try {
      GenericApplicationContext gContext =
          BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
      GroupDataConnector gdc = (GroupDataConnector) gContext.getBean("testFilterExactAttribute");

      Filter filter = gdc.getFilter();

      Set<Group> groups = filter.getResults(grouperSession);

      assertEquals(1, groups.size());

      assertTrue(groups.contains(groupA));
      assertFalse(groups.contains(groupB));
      assertFalse(groups.contains(groupC));

      assertTrue(filter.matches(groupA));
      assertFalse(filter.matches(groupB));
      assertFalse(filter.matches(groupC));
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(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());
   }
 }
コード例 #4
0
 private void registerUnrefreshedBeansWithRegistry(BeanDefinitionRegistry registry) {
   if (context != null) {
     for (String beanName : context.getBeanDefinitionNames()) {
       registry.registerBeanDefinition(beanName, context.getBeanDefinition(beanName));
     }
   }
 }
  @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"));
  }
コード例 #6
0
  @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());
  }
コード例 #7
0
  /**
   * Assert that the attributes returned from the data connector match the provided attributes.
   *
   * @param dataConnectorName the data connector name
   * @param principalName the principalName
   * @param correctMap the correct attributes
   */
  private void runAttributeDefinitionTest(
      String dataConnectorName,
      String principalName,
      AttributeMap correctMap,
      String attributeDefinitionName) {
    try {
      GenericApplicationContext gContext =
          BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
      ShibbolethResolutionContext ctx = getShibContext(principalName);

      // resolve data connector dependency
      GroupDataConnector gdc = (GroupDataConnector) gContext.getBean(dataConnectorName);
      gdc.resolve(ctx);
      ctx.getResolvedPlugins().put(gdc.getId(), gdc);

      // resolve attribute definition
      AttributeDefinition ad = (AttributeDefinition) gContext.getBean(attributeDefinitionName);
      BaseAttribute attr = ad.resolve(ctx);

      // assert equality
      AttributeMap currentMap = new AttributeMap();
      currentMap.setAttribute(attr);
      LOG.debug("correctMap\n{}", correctMap);
      LOG.debug("currentMap\n{}", currentMap);
      assertEquals(correctMap, currentMap);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
 @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());
   }
 }
コード例 #9
0
  @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
     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());
   }
 }
コード例 #11
0
 @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);
 }
コード例 #12
0
  @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");
    }
  }
コード例 #13
0
  @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);
  }
コード例 #14
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);
    }
  }
コード例 #15
0
 /**
  * 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(expected = ChannelResolutionException.class)
 public void lookupNonRegisteredChannel() {
   GenericApplicationContext context = new GenericApplicationContext();
   context.refresh();
   BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(context);
   resolver.resolveChannelName("noSuchChannel");
 }
コード例 #17
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;
 }
コード例 #18
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 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());
 }
 @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());
 }
コード例 #22
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();
  }
コード例 #23
0
 public void testGroupNotFound() {
   try {
     GenericApplicationContext gContext =
         BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
     GroupDataConnector gdc = (GroupDataConnector) gContext.getBean("testAttributesOnly");
     Map<String, BaseAttribute> map = gdc.resolve(getShibContext("notfound"));
     assertTrue(map.isEmpty());
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  @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();
  }
 @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 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);
 }
コード例 #28
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;
  }
コード例 #29
0
 /**
  * Assert that the attributes returned from the data connector match the provided attributes.
  *
  * @param dataConnectorName the data connector name
  * @param group the group
  * @param correctMap the correct attributes
  */
 private void runResolveTest(String dataConnectorName, Group group, AttributeMap correctMap) {
   try {
     GenericApplicationContext gContext =
         BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG);
     GroupDataConnector gdc = (GroupDataConnector) gContext.getBean(dataConnectorName);
     AttributeMap currentMap = new AttributeMap(gdc.resolve(getShibContext(group.getName())));
     LOG.debug("correctMap\n{}", correctMap);
     LOG.debug("currentMap\n{}", currentMap);
     assertEquals(correctMap, currentMap);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 @Test
 public void testPropertyPlaceholderConfigurerPresent() throws FileNotFoundException {
   IntegrationContext ic =
       (IntegrationContext)
           builder.build(new FileInputStream("src/test/resources/messageflow1.groovy"));
   GenericApplicationContext gac = (GenericApplicationContext) ic.getApplicationContext();
   boolean ppcPresent = false;
   for (Object obj : gac.getBeanFactoryPostProcessors()) {
     System.out.println(obj.getClass().getName());
     ppcPresent = ppcPresent || obj instanceof PropertySourcesPlaceholderConfigurer;
   }
   assertTrue(ppcPresent);
 }