@Test
  public void testSendBuilderWithEndpointName() {
    reset(applicationContextMock);
    when(applicationContextMock.getBean(TestActionListeners.class))
        .thenReturn(new TestActionListeners());
    when(applicationContextMock.getBeansOfType(SequenceBeforeTest.class))
        .thenReturn(new HashMap<String, SequenceBeforeTest>());
    when(applicationContextMock.getBeansOfType(SequenceAfterTest.class))
        .thenReturn(new HashMap<String, SequenceAfterTest>());
    MockTestDesigner builder =
        new MockTestDesigner(applicationContextMock) {
          @Override
          public void configure() {
            send("fooMessageEndpoint")
                .payload("<TestRequest><Message>Hello World!</Message></TestRequest>");
          }
        };

    builder.configure();

    TestCase test = builder.getTestCase();
    Assert.assertEquals(test.getActionCount(), 1);
    Assert.assertEquals(test.getActions().get(0).getClass(), SendMessageAction.class);

    SendMessageAction action = ((SendMessageAction) test.getActions().get(0));
    Assert.assertEquals(action.getName(), "send");
    Assert.assertEquals(action.getEndpointUri(), "fooMessageEndpoint");
  }
  @Test(
      expectedExceptions = CitrusRuntimeException.class,
      expectedExceptionsMessageRegExp = "Invalid use of http and soap action builder")
  public void testSendBuilderWithSoapAndHttpMixed() {
    reset(applicationContextMock);
    when(applicationContextMock.getBean(TestActionListeners.class))
        .thenReturn(new TestActionListeners());
    when(applicationContextMock.getBeansOfType(SequenceBeforeTest.class))
        .thenReturn(new HashMap<String, SequenceBeforeTest>());
    when(applicationContextMock.getBeansOfType(SequenceAfterTest.class))
        .thenReturn(new HashMap<String, SequenceAfterTest>());
    MockTestDesigner builder =
        new MockTestDesigner(applicationContextMock) {
          @Override
          public void configure() {
            send("httpClient")
                .http()
                .payload("<TestRequest><Message>Hello World!</Message></TestRequest>")
                .header("operation", "soapOperation")
                .soap();
          }
        };

    builder.configure();

    TestCase test = builder.getTestCase();
    Assert.assertEquals(test.getActionCount(), 1);
    Assert.assertEquals(test.getActions().get(0).getClass(), SendMessageAction.class);

    SendMessageAction action = ((SendMessageAction) test.getActions().get(0));
    Assert.assertEquals(action.getName(), "send");
    Assert.assertEquals(action.getEndpointUri(), "httpClient");
    Assert.assertEquals(action.getMessageType(), MessageType.XML.name());
  }
  @Test
  public void testSendBuilderWithDictionary() {
    final DataDictionary dictionary = new NodeMappingDataDictionary();

    reset(applicationContextMock);

    when(applicationContextMock.getBean(TestActionListeners.class))
        .thenReturn(new TestActionListeners());
    when(applicationContextMock.getBeansOfType(SequenceBeforeTest.class))
        .thenReturn(new HashMap<String, SequenceBeforeTest>());
    when(applicationContextMock.getBeansOfType(SequenceAfterTest.class))
        .thenReturn(new HashMap<String, SequenceAfterTest>());

    MockTestDesigner builder =
        new MockTestDesigner(applicationContext) {
          @Override
          public void configure() {
            send(messageEndpoint)
                .payload("{ \"TestRequest\": { \"Message\": \"?\" }}")
                .dictionary(dictionary);
          }
        };

    builder.configure();

    TestCase test = builder.getTestCase();
    Assert.assertEquals(test.getActionCount(), 1);
    Assert.assertEquals(test.getActions().get(0).getClass(), SendMessageAction.class);

    SendMessageAction action = ((SendMessageAction) test.getActions().get(0));
    Assert.assertEquals(action.getName(), "send");

    Assert.assertEquals(action.getEndpoint(), messageEndpoint);
    Assert.assertEquals(action.getDataDictionary(), dictionary);
  }
Beispiel #4
0
 private Map<String, Refresh> allRefresh() {
   Map<String, Refresh> refreshs = ctx.getBeansOfType(Refresh.class);
   ApplicationContext parent = ctx.getParent();
   if (parent != null) {
     refreshs.putAll(parent.getBeansOfType(Refresh.class));
   }
   return refreshs;
 }
Beispiel #5
0
  @Test
  public void testBeanProfiles() {
    System.setProperty(PROFILES_ACTIVE_PROPERTY, "dev");
    ApplicationContext context = createApplicationContext();
    Map<String, Database> beans = context.getBeansOfType(Database.class);
    System.out.println(beans);
    System.out.println(beans.values().iterator().next().getName());

    // PROD
    System.setProperty(PROFILES_ACTIVE_PROPERTY, "prod");
    context = createApplicationContext();
    beans = context.getBeansOfType(Database.class);
    System.out.println(beans);
    System.out.println(beans.values().iterator().next().getName());
  }
  @Test
  public void testResolveJmsEndpoint() throws Exception {
    reset(applicationContext);

    expect(applicationContext.getBeansOfType(EndpointComponent.class))
        .andReturn(Collections.<String, EndpointComponent>emptyMap())
        .once();
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(EasyMock.createMock(ConnectionFactory.class))
        .once();

    replay(applicationContext);

    TestContext context = new TestContext();
    context.setApplicationContext(applicationContext);

    DefaultEndpointFactory factory = new DefaultEndpointFactory();
    Endpoint endpoint = factory.create("jms:Sample.Queue.Name", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(),
        "Sample.Queue.Name");

    verify(applicationContext);
  }
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;

    // Gets all of the Validator beans from the application Context.
    Map<String, Validator> beanValidators = applicationContext.getBeansOfType(Validator.class);
    String[] mnbDaoBeans = applicationContext.getBeanNamesForType(BaseDao.class);

    for (int i = 0; i < mnbDaoBeans.length; i++) {

      // Gets the Class type that the Dao handles
      BaseDao type = (BaseDao) applicationContext.getBean(mnbDaoBeans[i]);

      Iterator<String> itr = beanValidators.keySet().iterator();
      List<Validator> validators = new ArrayList<Validator>();
      while (itr.hasNext()) {
        String key = itr.next();
        Validator validator = beanValidators.get(key);

        if (validator.supports(type.getEntityClass())) {
          validators.add(validator);
        }
      }

      if (validators.size() > 0) {
        this.cachedValidatorsMap.put(type.getEntityClass(), validators);
      }
    }

    logger.info("Validation Framework is bootstrapped and ready to roll");
  }
Beispiel #8
0
  /** @return list of application links */
  public Map<String, List<Link>> getApplicationLinks() throws DataStoreException {
    List<LinkGroup> categories = linkGroupService.list();
    if (categories != null) {
      Map<String, List<Link>> applicationLinks = new HashMap<>(categories.size());
      List<Link> firstlevelLinks;
      for (LinkGroup group : categories) {
        firstlevelLinks = linkGroupService.getFirstLevelLinks(group.getName());
        if (firstlevelLinks != null) {
          for (Link link : firstlevelLinks) {
            link.setChildren(listChildren(link.getName()));
          }
          applicationLinks.put(group.getName(), firstlevelLinks);
        }
      }

      Map<String, LinkProvider> beansMap = applicationContext.getBeansOfType(LinkProvider.class);

      for (Map.Entry<String, LinkProvider> entry : beansMap.entrySet()) {
        applicationLinks.put(entry.getKey(), entry.getValue().getLinks());
      }
      return applicationLinks;
    }

    return null;
  }
 /** 初始化所有配置为Spring Bean的邮件上下文。 */
 protected void initMailContexts() {
   Map<String, MailContext> mailContextBeans =
       applicationContext.getBeansOfType(MailContext.class);
   for (Entry<String, MailContext> mail : mailContextBeans.entrySet()) {
     mailContextHolder.put(mail.getKey(), mail.getValue());
   }
 }
  /*
   * Redirects the response the the given URI
   */
  private Object redirectResponse(
      String actualUri, HttpServletRequest request, HttpServletResponse response) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Dynamic method [redirect] forwarding request to [" + actualUri + "]");
    }

    try {

      if (LOG.isDebugEnabled()) {
        LOG.debug("Executing redirect with response [" + response + "]");
      }

      String redirectUrl = useJessionId ? response.encodeRedirectURL(actualUri) : actualUri;
      response.sendRedirect(redirectUrl);
      Map<String, RedirectEventListener> redirectListeners =
          applicationContext.getBeansOfType(RedirectEventListener.class);
      for (RedirectEventListener redirectEventListener : redirectListeners.values()) {
        redirectEventListener.responseRedirected(redirectUrl);
      }

      request.setAttribute(GRAILS_REDIRECT_ISSUED, true);

    } catch (IOException e) {
      throw new CannotRedirectException(
          "Error redirecting request for url [" + actualUri + "]: " + e.getMessage(), e);
    }
    return null;
  }
  private static void assertEntityLinksSetUp(ApplicationContext context) {

    Map<String, EntityLinks> discoverers = context.getBeansOfType(EntityLinks.class);
    assertThat(
        discoverers.values(),
        Matchers.<EntityLinks>hasItem(instanceOf(DelegatingEntityLinks.class)));
  }
  @Before
  public void setUp() throws Exception {
    mockApplicationContext = mock(ApplicationContext.class);
    mockEventStore = mock(EventStore.class);

    testSubject = new SpringAggregateSnapshotterFactoryBean();
    testSubject.setApplicationContext(mockApplicationContext);
    when(mockApplicationContext.getBeansOfType(AggregateFactory.class))
        .thenReturn(
            Collections.singletonMap(
                "myFactory",
                new AbstractAggregateFactory<StubAggregate>(StubAggregate.class) {
                  @Override
                  public StubAggregate doCreateAggregate(
                      String aggregateIdentifier, DomainEventMessage firstEvent) {
                    return new StubAggregate(aggregateIdentifier);
                  }
                }));
    testSubject.setEventStore(mockEventStore);
    mockTransactionManager = mock(PlatformTransactionManager.class);
    aggregateIdentifier = UUID.randomUUID().toString();

    String type = "testAggregate";
    DomainEventMessage event1 =
        new GenericDomainEventMessage<>(
            type, aggregateIdentifier, 0L, "Mock contents", MetaData.emptyInstance());
    DomainEventMessage event2 =
        new GenericDomainEventMessage<>(
            type, aggregateIdentifier, 1L, "Mock contents", MetaData.emptyInstance());
    when(mockEventStore.readEvents(aggregateIdentifier))
        .thenReturn(DomainEventStream.of(event1, event2));
  }
  private void loadListeners() {
    final Map<String, ? extends GBSettingsListener> listeners =
        applicationContext.getBeansOfType(GBSettingsListener.class);
    for (Entry<String, ? extends GBSettingsListener> pair : listeners.entrySet()) {
      final GBSettingsListener listener = pair.getValue();
      if (LOGGER.isInfoEnabled())
        LOGGER.info(
            "Loading listener " + pair.getKey() + " (" + listener.getClass().getSimpleName() + ")");

      // init the listener
      try {
        listener.onStartup(settingsDAO);
      } catch (Exception e) {
        LOGGER.warn(
            "Error initializing listener "
                + pair.getKey()
                + " ("
                + listener.getClass().getSimpleName()
                + ")",
            e);
      }

      // register the listener
      settingsCatalog.addListener(listener);
    }
  }
  private static void assertRelProvidersSetUp(ApplicationContext context) {

    Map<String, RelProvider> discoverers = context.getBeansOfType(RelProvider.class);
    assertThat(
        discoverers.values(),
        Matchers.<RelProvider>hasItem(instanceOf(DelegatingRelProvider.class)));
  }
 private Blueprint getBlueprintById(String blueprintId) {
   Map<String, Blueprint> projects = appContext.getBeansOfType(Blueprint.class);
   for (Blueprint blueprint : projects.values()) {
     if (blueprintId.equals(blueprint.getId())) {
       return blueprint;
     }
   }
   throw new IllegalStateException("No blueprint found for id '" + blueprintId + "'");
 }
  @Override
  public void afterPropertiesSet() throws Exception {

    final Map<String, HealthIndicator> healthIndicators =
        applicationContext.getBeansOfType(HealthIndicator.class);
    for (Map.Entry<String, HealthIndicator> entry : healthIndicators.entrySet()) {
      healthIndicator.addHealthIndicator(entry.getKey(), entry.getValue());
    }
  }
Beispiel #17
0
 @Autowired
 public UserRealm(ApplicationContext ctx) {
   super();
   // 不能注入 因为获取bean依赖顺序问题造成可能拿不到某些bean报错
   // why?
   // 因为spring在查找findAutowireCandidates时对FactoryBean做了优化,即只获取Bean,但不会autowire属性,
   // 所以如果我们的bean在依赖它的bean之前初始化,那么就得不到ObjectType(永远是Repository)
   // 所以此处我们先getBean一下 就没有问题了
   ctx.getBeansOfType(SimpleBaseRepositoryFactoryBean.class);
 }
  // once-per-game initialization
  private void initOnce() {
    initialized = true;

    log.info("initOnce()");
    visualizerService.newRun();

    // registrations for message listeners:
    Collection<MessageHandler> handlers = context.getBeansOfType(MessageHandler.class).values();
    for (MessageHandler handler : handlers) {
      log.debug("initializing..." + handler.getClass().getName());
      handler.initialize();
    }

    Collection<DomainRepo> repos = context.getBeansOfType(DomainRepo.class).values();
    for (DomainRepo repo : repos) {
      log.debug("recycling..." + repos.getClass().getName());
      repo.recycle();
    }
  }
 @SuppressWarnings("unchecked")
 public static <T> T getBean(Class<T> clazz) {
   checkApplicationContext();
   Map beanMaps = applicationContext.getBeansOfType(clazz);
   if (beanMaps != null && !beanMaps.isEmpty()) {
     return (T) beanMaps.values().iterator().next();
   } else {
     return null;
   }
 }
 @Override
 public void preProcessModule(Module module) {
   assertEquals(
       "module commonContext should not contain any Plugins",
       0,
       moduleCommonContext.getBeansOfType(Plugin.class).size());
   Properties properties = new Properties();
   properties.setProperty("xd.stream.name", module.getDeploymentMetadata().getGroup());
   module.addProperties(properties);
 }
  @Test
  public void testCommandBusIsAutowired() throws Exception {
    testSubject.setCommandBus(null);
    Map<String, CommandBus> map = new HashMap<String, CommandBus>();
    map.put("ignored", mockCommandBus);
    when(mockApplicationContext.getBeansOfType(CommandBus.class)).thenReturn(map);

    testSubject.afterPropertiesSet();

    verify(mockApplicationContext).getBeansOfType(CommandBus.class);
  }
Beispiel #22
0
 /**
  * 容器加载bean后,调用此函数用来注入资源ServBaseResource的实现类,令使用者可调用 {@link #getResource(ModelUser,
  * EResourceType)}来获取各种资源
  */
 @SuppressWarnings("unchecked")
 @Override
 public boolean init(ApplicationContext applicationContext) {
   @SuppressWarnings("rawtypes")
   Map<String, IServBaseResource> map = applicationContext.getBeansOfType(IServBaseResource.class);
   Iterator<String> iter = map.keySet().iterator();
   while (iter.hasNext()) {
     addServResource(map.get(iter.next()));
   }
   return true;
 }
 @Override
 public void afterPropertiesSet() throws Exception {
   if (this.repositories.isEmpty()) {
     ApplicationContext appCtx = applicationContext;
     while (null != appCtx) {
       Map<String, CrudRepository> beans = appCtx.getBeansOfType(CrudRepository.class);
       setRepositories(beans.values());
       appCtx = appCtx.getParent();
     }
   }
 }
  /**
   * @see
   *     org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext)
   */
  @Override
  public void prepareTestInstance(TestContext testContext) throws Exception {
    synchronized (doneMonitor) {
      if (done) {
        return;
      } else {
        TestSuiteAwareExecutionListener.preparationDone();
      }

      ApplicationContext ctx = testContext.getApplicationContext();

      SequenceBeforeSuite beforeSuite = null;
      if (ctx.getBeansOfType(SequenceBeforeSuite.class).size() == 1) {
        beforeSuite = ctx.getBean(SequenceBeforeSuite.class);
      }

      SequenceAfterSuite afterSuite = null;
      if (ctx.getBeansOfType(SequenceAfterSuite.class).size() == 1) {
        afterSuite = ctx.getBean(SequenceAfterSuite.class);
      }

      com.consol.citrus.context.TestContext context =
          ctx.getBean(com.consol.citrus.context.TestContext.class);
      TestSuiteListeners testSuiteListener = ctx.getBean(TestSuiteListeners.class);

      if (beforeSuite != null) {
        try {
          beforeSuite.execute(context);
        } catch (Exception e) {
          throw new CitrusRuntimeException("Before suite failed with errors", e);
        }
      } else {
        testSuiteListener.onStart();
        testSuiteListener.onStartSuccess();
      }

      Runtime.getRuntime()
          .addShutdownHook(
              new Thread(new AfterSuiteShutdownHook(afterSuite, context, testSuiteListener)));
    }
  }
 @Test
 public void testRetrieveAggregateFactoryFromRepositoryIfNotExplicitlyAvailable()
     throws Exception {
   testSubject.setEventStore(null);
   reset(mockApplicationContext);
   when(mockApplicationContext.getBean(EventStore.class)).thenReturn(mockEventStore);
   when(mockApplicationContext.getBeansOfType(EventSourcingRepository.class))
       .thenReturn(
           Collections.singletonMap(
               "myRepository",
               new EventSourcingRepository<>(StubAggregate.class, mockEventStore)));
   testSnapshotCreated_NoTransaction();
 }
  @Override
  public <B> Iterator<BindingDescriptor<B>> getBindings(Class<B> clazz) {

    List<BindingDescriptor<B>> result = new ArrayList<BindingDescriptor<B>>();

    Map<String, B> beansOfType = applicationContext.getBeansOfType(clazz);

    for (Entry<String, B> beans : beansOfType.entrySet()) {
      result.add(new SpringBindingDescriptorAdapter<B>(beans));
    }

    return result.iterator();
  }
  public void sessionDestroyed(HttpSessionEvent se) {
    if (ctx == null) {
      logger.warn("cannot find applicationContext");

      return;
    }

    Collection<HttpSessionListener> httpSessionListeners =
        ctx.getBeansOfType(HttpSessionListener.class).values();

    for (HttpSessionListener httpSessionListener : httpSessionListeners) {
      httpSessionListener.sessionDestroyed(se);
    }
  }
  public GeneratorRunnerConfigFactory(String filePath) {

    // Set up Spring context
    ApplicationContext context = new FileSystemXmlApplicationContext(new String[] {filePath});

    // Get thread configuration
    ThreadConfig threadConfig = (ThreadConfig) context.getBean("threadConfig");

    // Get generators
    Map<String, GeneratorContext> generators = context.getBeansOfType(GeneratorContext.class);

    // Create GeneratorConfig
    this.generatorConfig = new GeneratorRunnerConfig(threadConfig, generators.values());
  }
Beispiel #29
0
  public static void main(String[] args) {
    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    CliUi cli = (CliUi) context.getBeansOfType(CliUi.class).values().toArray()[0];

    if (args != null && args.length > 0) {
      if ("add".equals(args[0])) {
        cli.add(args);
      } else {
        cli.process(args);
      }
    } else {
      cli.help();
    }
  }
 protected void extractHandlerMappings(
     ApplicationContext applicationContext, Map<String, Object> result) {
   if (applicationContext != null) {
     Map<String, AbstractUrlHandlerMapping> mappings =
         applicationContext.getBeansOfType(AbstractUrlHandlerMapping.class);
     for (String name : mappings.keySet()) {
       AbstractUrlHandlerMapping mapping = mappings.get(name);
       Map<String, Object> handlers = getHandlerMap(mapping);
       for (String key : handlers.keySet()) {
         result.put(key, Collections.singletonMap("bean", name));
       }
     }
   }
 }